fork(4) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.Collectors;
  7. import java.util.function.Function;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. final Collection<Record> records = new ArrayList<>();
  15. records.add(new Record("11111", "Orlando"));
  16. records.add(new Record("11111", "Orlando"));
  17. records.add(new Record("11111", "Orlando"));
  18. records.add(new Record("11111", "Los Angeles"));
  19. records.add(new Record("11111", "Los Angeles"));
  20. records.add(new Record("11111", "San Francisco"));
  21.  
  22. records.add(new Record("22222", "Cincinatti"));
  23. records.add(new Record("22222", "Cleveland"));
  24. records.add(new Record("22222", "Cleveland"));
  25. records.add(new Record("22222", "Columbus"));
  26. records.add(new Record("22222", "Columbus"));
  27. records.add(new Record("22222", "Columbus"));
  28.  
  29. final Map<String, List<Record>> recordsByZip = records.stream()
  30. .collect(Collectors.groupingBy(Record::getZip));
  31.  
  32. recordsByZip.forEach((zip, entries) -> {
  33. final Map<String, Long> frequencyMap = entries.stream()
  34. .map(Record::getCity)
  35. .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
  36.  
  37. System.out.println("Frequency map for zip " + zip);
  38. frequencyMap.forEach((city, frequency) -> System.out.println(city + ": " + frequency));
  39. System.out.println();
  40. });
  41. }
  42. }
  43.  
  44. class Record {
  45. private String zip;
  46. private String city;
  47.  
  48. public Record(String zip, String city) {
  49. this.zip = zip;
  50. this.city = city;
  51. }
  52.  
  53. public String getZip() {
  54. return zip;
  55. }
  56. public void setZip(String zip) {
  57. this.zip = zip;
  58. }
  59. public String getCity() {
  60. return city;
  61. }
  62. public void setCity(String city) {
  63. this.city = city;
  64. }
  65. }
Success #stdin #stdout 0.1s 711680KB
stdin
Standard input is empty
stdout
Frequency map for zip 11111
San Francisco: 1
Orlando: 3
Los Angeles: 2

Frequency map for zip 22222
Cincinatti: 1
Columbus: 3
Cleveland: 2