如何汇总Map<String, List<String>>
以获取:
List<String>
中值String
的所有List
个Map
长度超过5个字符?如何长期计算这些?
Map<String, List<String>>
,其中密钥保持不变,但List
只包含长度大于5的String
?
Map<String, Long>
每个地图的密钥在String
中的List
s长度超过5?
我开始了一些事情,但我被困住了:
long l = map.entrySet().stream()
.filter(m -> m.getValue().stream().filter(s -> s.length() > 5)
由于
答案 0 :(得分:5)
对于第一个问题,您可以使用List
合并flatMap
,然后过滤掉短String
:
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()));