对于第一个问题,您可以使用flatMap 合并Lists,然后过滤掉短的Strings:
List<String> longStrings =
map.values()
.stream()
.flatMap(Collection::stream)
.filter(s->s.length() > 5)
.collect(Collectors.toList());
对于第二个问题,您似乎想从源 Map 创建一个新的 Map,其中键保持不变,值被过滤:
示例输入:
Map<String, List<String>> map = new HashMap<> ();
map.put ("one", Arrays.asList (new String[]{"1","2","12345","123456"}));
map.put ("two", Arrays.asList (new String[]{"1","123456","12345","12"}));
map.put ("three", Arrays.asList (new String[]{"1","2","12","34"}));
map.put ("four", Arrays.asList (new String[]{"12345","123456","1234567","123"}));
处理:
Map<String, List<String>> output =
map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e->e.getValue()
.stream()
.filter(s -> s.length() > 5)
.collect(Collectors.toList())));
输出:
{four=[123456, 1234567], one=[123456], three=[], two=[123456]}
第三个问题是第二个问题的微小变化:
Map<String, Long> output =
map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e->e.getValue()
.stream()
.filter(s -> s.length() > 5)
.count()));