好的,这是我提到的三种可能性。执行以下操作:
- 提供不同的方法来处理重复项。
- 将值放入
LinkedHashMap
以保持遭遇顺序。
- 非列表版本按分数对它们进行排序,但将相同的分数保持相同的顺序。如果您不希望对它们进行排序,可以轻松将其删除,或者可以按团队名称进行排序。
List<String> teams = Arrays.asList("Dortmund 8", "Bayern 10",
"Dortmund 7", "Madrid 10", "Madrid 9");
该条目保留重复团队遇到的第一个条目。
Map<String, Integer> map1 =
teams.stream().map(str -> str.split("\\s+"))
.sorted(Comparator.comparing(
arr -> Integer.parseInt(arr[1])))
.collect(Collectors.toMap(arr -> arr[0],
arr -> Integer.parseInt(arr[1]),
(a, b) -> a, // <-- the 'a' indicates the first one
LinkedHashMap::new));
System.out.println("Keep the first score encountered");
map1.entrySet().forEach(System.out::println);
System.out.println();
这保留了重复团队遇到的最后一个条目。
Map<String, Integer> map2 =
teams.stream().map(str -> str.split("\\s+"))
.sorted(Comparator.comparing(
arr -> Integer.parseInt(arr[1])))
.collect(Collectors.toMap(arr -> arr[0],
arr -> Integer.parseInt(arr[1]),
(a, b) -> b,// <-- the 'b' indicates the last one
LinkedHashMap::new));
System.out.println("Keep the last score encountered");
map2.entrySet().forEach(System.out::println);
System.out.println();
这个将每个团队的得分存储在一个列表中。
Map<String, List<Integer>> map3 =
teams.stream().map(str -> str.split("\\s+"))
.collect(Collectors.groupingBy(arr -> arr[0],
LinkedHashMap::new,
Collectors.mapping(
a -> Integer.parseInt(a[1]),
Collectors.toList())));
System.out.println("Put the scores in a list");
map3.entrySet().forEach(System.out::println);
他们打印
Keep the first score encountered
Dortmund=7
Madrid=9
Bayern=10
Keep the last score encountered
Dortmund=8
Madrid=10
Bayern=10
Put the scores in a list
Dortmund=[8, 7]
Bayern=[10]
Madrid=[10, 9]