地图<long,list <string =“”>&gt;一些键的字符串Lambda列表

时间:2017-12-10 17:05:41

标签: java lambda java-8

我有一个HashMap,如Map<Long, List<String>> map = ....

我也有一个像List<Long> keyList = Arrays.asList(1L, 3L, 10L);

这样的密钥列表

我希望通过这些List<String>提取keyList's并使用lambda表达式生成单个List<String>

3 个答案:

答案 0 :(得分:5)

试试这个:

List<String> values = keyList.stream()    // for each key
    .map(map::get)                        // convert keys to their values
    .flatMap(List::stream)                // stream the lists as one stream
    .collect(Collectors.toList());        // as a single list of String

答案 1 :(得分:3)

另一种方法是使用reduce代替flatMap, collect

import java.util.*;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;

class Main {

  public static void main(String[] args) {
    final Map<Long, List<String>> map = createTestMap();
    final List<Long> keyList = asList(1L, 3L, 10L);
    final List<String> resultList = keyList.stream()
        .map(map::get)
        .map(ArrayList::new)  // need to create new lists not to corrupt the existing ones
        .reduce((left, right) -> { left.addAll(right); return left;})  // accumulate the list
        .orElse(new ArrayList<>());  // empty list if nothing was found
    System.out.println(resultList);
  }

  private static Map<Long, List<String>> createTestMap() {
    final Map<Long, List<String>> map = new HashMap<>();
    final List<String> oneList = asList("1 love", "1 peace");
    final List<String> threeList = singletonList("3 words");
    final List<String> tenList = emptyList();
    final List<String> ninetyList = singletonList("99 problems");
    map.put(1L, oneList);
    map.put(3L, threeList);
    map.put(10L, tenList);
    map.put(90L, ninetyList);
    return map;
  }
}

答案 2 :(得分:0)

试试这个

  List<String> strings = map.entrySet().stream()
            .filter(m->keyList.contains(m.getKey()))
            .flatMap(m->m.getValue().stream())
            .collect(Collectors.toList());