Created
April 8, 2022 09:49
-
-
Save kabutz/b0bacc040faad357bbf0aeeaf87498d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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