Skip to content

Instantly share code, notes, and snippets.

@mwanji
Last active September 18, 2020 09:31
Show Gist options
  • Save mwanji/8180516 to your computer and use it in GitHub Desktop.
Save mwanji/8180516 to your computer and use it in GitHub Desktop.
A Java 8 adaptation of code to find the first non-repeated letter in a string. Original found here: http://javahungry.blogspot.com/2013/12/first-non-repeated-character-in-string-java-program-code-example.html#.UsFH_N8Q8ak
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
public class NonRepeatingLetter {
public static void main(String[] args) {
findFirstNonRepeatingLetter(args[0], System.out::println);
}
private static void findFirstNonRepeatingLetter(String s, Consumer<Character> callback) {
s.chars()
.mapToObj(i -> Character.valueOf((char) i))
.collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst().map(c -> { callback.accept(c); return c; } );
}
}
@stefan-cross
Copy link

Nice, just doing a bit of research and came across this. Lovely use of Java 8

@ronakshah725
Copy link

Could you provide comments for those new to Java 8

@psdhole
Copy link

psdhole commented Nov 23, 2016

could you please provide comments

@gouravtiwari489
Copy link

What is use of identity function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment