以下工作使用 Java 9 或更高版本:
@Test
void invertMap()
{
Map<DayOfWeek, Integer> map = Map.of(
DayOfWeek.MONDAY, 52,
DayOfWeek.TUESDAY, 52,
DayOfWeek.WEDNESDAY, 53,
DayOfWeek.THURSDAY, 53,
DayOfWeek.FRIDAY, 52,
DayOfWeek.SATURDAY, 52,
DayOfWeek.SUNDAY, 52
);
Map<Integer, Set<DayOfWeek>> flipped = new TreeMap<>();
map.forEach((dow, count) ->
flipped.computeIfAbsent(count, (key) ->
EnumSet.noneOf(DayOfWeek.class)).add(dow));
Map<Integer, Set<DayOfWeek>> flippedStream = map.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
TreeMap::new,
Collectors.mapping(
Map.Entry::getKey,
Collectors.toCollection(
() -> EnumSet.noneOf(DayOfWeek.class)))));
Map<Integer, Set<DayOfWeek>> expected = Map.of(
53, EnumSet.of(
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY),
52, EnumSet.of(
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.FRIDAY,
DayOfWeek.SATURDAY,
DayOfWeek.SUNDAY)
);
Assert.assertEquals(expected, flipped);
Assert.assertEquals(expected, flippedStream);
}
如果您愿意使用第三方库,则以下代码将与Eclipse Collections一起使用:
@Test
void invertEclipseCollectionsMap()
{
MutableMap<DayOfWeek, Integer> map =
Maps.mutable.<DayOfWeek, Integer>empty()
.withKeyValue(DayOfWeek.MONDAY, 52)
.withKeyValue(DayOfWeek.TUESDAY, 52)
.withKeyValue(DayOfWeek.WEDNESDAY, 53)
.withKeyValue(DayOfWeek.THURSDAY, 53)
.withKeyValue(DayOfWeek.FRIDAY, 52)
.withKeyValue(DayOfWeek.SATURDAY, 52)
.withKeyValue(DayOfWeek.SUNDAY, 52);
SetMultimap<Integer, DayOfWeek> flipped = map.flip();
Assert.assertEquals(flipped.get(52), Set.of(
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.FRIDAY,
DayOfWeek.SATURDAY,
DayOfWeek.SUNDAY));
Assert.assertEquals(flipped.get(53), Set.of(
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY));
}
注意:我是 Eclipse Collections 的提交者。