Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedHashMap;
- import java.util.Map;
- import static java.util.function.Function.identity;
- import static java.util.stream.Collectors.counting;
- import static java.util.stream.Collectors.groupingBy;
- public class NonRepeatingLetter {
- public static void main(String[] args) {
- System.out.println(findFirstNonRepeatingLetter(args[0]));
- }
- // "teeter" = 'r'
- // "stress" = 't'
- // "choochoo" = Exception
- // "" = Exception
- public static char findFirstNonRepeatingLetter(final String string) {
- // transform string to a IntStream
- return string.chars()
- // map to Character to use object collectors
- .mapToObj(i -> (char) i) // avoid unnecessary wrapping
- // collect the Characters into a LinkedHashMap (to maintain insertion order) grouping by their count
- .collect(groupingBy(identity(), LinkedHashMap::new, counting()))
- // transform Map<Character, Long> into a Stream<Entry<Character, Long>>
- .entrySet().stream()
- // filter by 1 occurrence
- .filter(e -> e.getValue() == 1)
- // map to the Character
- .map(Map.Entry::getKey) // use a method reference
- // find the first Character that satisfies the filter
- .findFirst()
- // if no Character is found, throw an exception
- .orElseThrow(() -> new RuntimeException("Only duplicates present")); // handle all duplicates or empty
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement