如何在Java的字符串数组列表中执行流和映射?



下面是我的输入:

List<String[]> items = List.of(
new String[] {"Apple", "20"},
new String[] {"Orange", "15"},
new String[] {"Tomato", "25"} 
);

我期望的输出也应该在字符串数组列表中:

"fruits", "35"
"vegetables", "25"

我可以使用映射和流实现这一点吗?

我知道如何在字符串列表上做流和映射,但不能在字符串数组列表上做。

eg:
List<String> newItem = items.stream().map(item -> switch(item){
case "Apple", "Orange" -> "fruits" ;
case "Tomato" -> "vegetables" ;
default -> "other";
}).collect(Collectors.toList()) ;

你能帮我实现这个解决方案吗?

以下方案使用具有合并功能的Collectors::toMapSupplier<Map>:

List<String[]> items = List.of(
new String[] {"Apple", "20"},
new String[] {"Orange", "15"},
new String[] {"Potato", "25"} 
);
List<String[]> total = new ArrayList<>(items
.stream()
.map(arr -> new String[] {
switch(arr[0]) {
case "Apple", "Orange", "Tomato" -> "fruit";
case "Potato" -> "vegetable";
default -> "other";
},
arr[1]
}) // create new array with the category and amount
.collect(Collectors.toMap(
arr -> arr[0],
arr -> arr,
(a1, a2) -> { 
a1[1] = String.valueOf(
Integer.parseInt(a1[1]) + Integer.parseInt(a2[1])
);
return a1;  
},
LinkedHashMap::new
))
.values() // Collection<List<String[]>>
);
total.stream()
.map(Arrays::toString)
.forEach(System.out::println);

输出:

[fruit, 35]
[vegetable, 25]

注:因为西红柿是水果,营养学家认为是蔬菜,所以将输入中的Tomato替换为Potato:)

广场在线演示

你贴出的答案中有几点。

  • 在每个switch子句中,您需要返回一个包含食品类别和值的数组,以便您知道要求和的内容。有不同的方法可以做到这一点。这里有一个例子:
case "Apple", "Orange" -> new String[] {"fruit", s[1]};
  • 收集器的第一个参数现在需要是s -> s[0]作为映射的键。然后它看起来像这样:
.collect(Collectors.groupingBy(s -> s[0],
Collectors.summingInt(str -> Integer.parseInt(str[1]))));
  • 则需要将条目收集到List<String[]>中。您可以通过将此应用到收集器的末尾来实现。
.entrySet().stream()
.map(e -> new String[] {e.getKey(), Integer.toString(e.getValue()) })
.toList();

最新更新