我正在尝试弄清楚如何在以下情况下使用Java8 streams:
假设我有以下Map:
Map<String,String[]> map = { { "01": {"H01","H02","H03"}, {"11": {"B11","B12","B13"}} };
所需的输出将是:
map = { {"01": {"H02"}, {"11": {"B11"}};
我的尝试是:
map.entrySet().stream() //
.flatMap(entry -> Arrays.stream(entry.getValue()) //
.filter(channel -> Channel.isValid(channel))
.collect(Collectors.toMap()));
发布于 2018-09-16 01:21:24
这是另一种解决问题的方法:
public static void stack2() {
Map<String, String[]> map = new HashMap<>();
map.put("01", new String[]{"H01", "H02", "H03"});
map.put("11", new String[]{"B11", "B12", "B13"});
Map<String, String[]> newMap = map.entrySet()
.stream()
.peek(e -> e.setValue(
Arrays.stream(e.getValue())
.filter(Main::stack2Filter)
.toArray(String[]::new)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
newMap.forEach((key, value) ->
System.out.println("key: " + key + " value " + Arrays.toString(value)));
}
public static boolean stack2Filter(String entry) {
return entry.equals("H02") || entry.equals("B11");
}
https://stackoverflow.com/questions/49804367
复制相似问题