Skip to content

Instantly share code, notes, and snippets.

@kabutz
Created April 8, 2022 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kabutz/b0bacc040faad357bbf0aeeaf87498d1 to your computer and use it in GitHub Desktop.
Save kabutz/b0bacc040faad357bbf0aeeaf87498d1 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class StreamMapInvertingCompilerBug {
public static void main(String... args) {
Map<Integer, Long> numberCount =
Stream.of(1, 4, 2, 5, 3, 5, 1, 3, 5, 3, 2, 1, 4, 5)
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
// This compiles fine
SortedMap<Long, List<Integer>> invertedMapAscending =
numberCount.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
TreeMap::new,
Collectors.mapping(
Map.Entry::getKey,
Collectors.toList()
)));
System.out.println("invertedMapAscending = " +
invertedMapAscending);
// this does not compile, but IntelliJ says it is OK
/*
SortedMap<Long, List<Integer>> invertedMapDescending1 =
numberCount.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
() -> new TreeMap<>(Comparator.reverseOrder()),
Collectors.mapping(
Map.Entry::getKey,
Collectors.toList()
)));
System.out.println("invertedMapDescending1 = " +
invertedMapDescending1);
//*/
// this compiles, but needs the explicit generic type for
// TreeMap, but IntelliJ marks that as unnecessary
SortedMap<Long, List<Integer>> invertedMapDescending2 =
numberCount.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
() -> new TreeMap<Long, List<Integer>>(Comparator.reverseOrder()),
Collectors.mapping(
Map.Entry::getKey,
Collectors.toList()
)));
System.out.println("invertedMapDescending2 = " +
invertedMapDescending2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment