Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import java.util.LinkedHashMap;
  2. import java.util.Map;
  3.  
  4. import static java.util.function.Function.identity;
  5. import static java.util.stream.Collectors.counting;
  6. import static java.util.stream.Collectors.groupingBy;
  7.  
  8. public class NonRepeatingLetter {
  9. public static void main(String[] args) {
  10. System.out.println(findFirstNonRepeatingLetter(args[0]));
  11. }
  12.  
  13. // "teeter" = 'r'
  14. // "stress" = 't'
  15. // "choochoo" = Exception
  16. // "" = Exception
  17. public static char findFirstNonRepeatingLetter(final String string) {
  18. // transform string to a IntStream
  19. return string.chars()
  20. // map to Character to use object collectors
  21. .mapToObj(i -> (char) i) // avoid unnecessary wrapping
  22. // collect the Characters into a LinkedHashMap (to maintain insertion order) grouping by their count
  23. .collect(groupingBy(identity(), LinkedHashMap::new, counting()))
  24. // transform Map<Character, Long> into a Stream<Entry<Character, Long>>
  25. .entrySet().stream()
  26. // filter by 1 occurrence
  27. .filter(e -> e.getValue() == 1)
  28. // map to the Character
  29. .map(Map.Entry::getKey) // use a method reference
  30. // find the first Character that satisfies the filter
  31. .findFirst()
  32. // if no Character is found, throw an exception
  33. .orElseThrow(() -> new RuntimeException("Only duplicates present")); // handle all duplicates or empty
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement