使用流收集到 Map

Niz*_*ikh 4 java java-8 java-stream

我有以下几点TreeMap

TreeMap<Long,String> gasType = new TreeMap<>(); // Long, "Integer-Double"
gasType.put(1L, "7-1.50");
gasType.put(2L, "7-1.50");
gasType.put(3L, "7-3.00");
gasType.put(4L, "8-5.00");
gasType.put(5L, "8-7.00");
Map<Integer,TreeSet<Long>> capacities = new TreeMap<>);
Run Code Online (Sandbox Code Playgroud)

键的形式为1L(a Long),值的形式为"7-1.50"( Stringanint和 a的串联,由adouble分隔-)。

我需要TreeMap通过获取int原始值的一部分来创建一个新的键Map(例如,对于 value "7-1.50",新键将为7)。new 的值Map将是TreeSet包含Map与新键匹配的原始键的所有键。

因此,对于上面的输入,7键的值将是Set{1L,2L,3L}。

我可以在没有Streams 的情况下做到这一点,但我想用Streams来做到这一点。任何帮助表示赞赏。谢谢你。

Era*_*ran 5

这是一种方法:

Map<Integer,TreeSet<Long>> capacities = 
  gasType.entrySet()
         .stream ()
         .collect(Collectors.groupingBy (e -> Integer.parseInt(e.getValue().substring(0,e.getValue ().indexOf("-"))),
                                         TreeMap::new,
                                         Collectors.mapping (Map.Entry::getKey,
                                                             Collectors.toCollection(TreeSet::new))));
Run Code Online (Sandbox Code Playgroud)

我修改了原始代码以支持多位整数,因为看起来您想要这样。

这会产生Map

{7=[1, 2, 3], 8=[4, 5]}
Run Code Online (Sandbox Code Playgroud)

如果你不关心结果MapSets的顺序,你可以让 JDK 来决定实现,这会稍微简化代码:

Map<Integer,Set<Long>> capacities = 
  gasType.entrySet()
         .stream ()
         .collect(Collectors.groupingBy (e -> Integer.parseInt(e.getValue().substring(0,e.getValue ().indexOf("-"))),
                                         Collectors.mapping (Map.Entry::getKey,
                                                             Collectors.toSet())));
Run Code Online (Sandbox Code Playgroud)