I am trying to group the following list of Foo objects by getName() and count occurrences while ordering by getNumber() in ascending order.
Input:
List<Foo> fooList = List.of( new Foo("Alpha", 1.1f), new Foo("Delta", 1.2f), new Foo("Charlie", 3.1f), new Foo("Alpha", 2.1f), new Foo("Charlie", 4.1f), new Foo("Delta", 2.2f) ); Map Output:
{Alpha=2, Delta=2, Charlie=2} My current solution is as follows:
Map<String, Integer> map = new LinkedHashMap<>(); fooList .stream() .sorted(Comparator.comparingDouble(Foo::getNumber)) .forEach(foo -> { int val = map.getOrDefault(foo.getName(), 0); map.put(foo.getName(), val + 1); }); Is there any better way with Collectors.groupingBy()?