Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save schatterjee4/0771a101f8b548b764a3dca9835be238 to your computer and use it in GitHub Desktop.
Save schatterjee4/0771a101f8b548b764a3dca9835be238 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; } );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment