如何按照集合的值流式传输地图?

时间:2016-10-20 10:06:02

标签: java collections java-8 java-stream

如何汇总Map<String, List<String>>以获取:

  1. List<String>中值String的所有ListMap长度超过5个字符?如何长期计算这些?

  2. Map<String, List<String>>,其中密钥保持不变,但List只包含长度大于5的String

  3. Map<String, Long>每个地图的密钥在String中的List s长度超过5?

  4. 我开始了一些事情,但我被困住了:

    long l = map.entrySet().stream()
                .filter(m -> m.getValue().stream().filter(s -> s.length() > 5)
    

    由于

1 个答案:

答案 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()));