Last active
September 18, 2020 09:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } ); | |
} | |
} |
Could you provide comments for those new to Java 8
could you please provide comments
What is use of identity function?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, just doing a bit of research and came across this. Lovely use of Java 8