Warm tip: This article is reproduced from stackoverflow.com, please click
java java-8 java-stream

How to look up value in a list of map?

发布于 2020-03-27 10:29:51

I have List<Map<Integer, Map<Integer, Long>>>. Given two keys, how to return the Long value using streams?

For example

    List<Map<Integer, Map<Integer, Long>>> listOfMap = new ArrayList<>();

    Map<Integer, Map<Integer, Long>> lMap1 = new HashMap<>();
    Map<Integer, Long> map1 = new HashMap<>();
    map1.put(10, 100L);
    map1.put(20, 200L);
    lMap1.put(1, map1);

    Map<Integer, Map<Integer, Long>> lMap2 = new HashMap<>();
    Map<Integer, Long> map2 = new HashMap<>();
    map2.put(30, 300L);
    map2.put(40, 400L);
    lMap2.put(2, map2);

Given 1 and 10, it would return 100.

Sagar Veeram
Dhruvil Vaghela 2019-07-03 23:59

Assuming you want to look into each Map in List and check for both keys in nested maps, you can do something like below -

OptionalLong optional = listOfMap.stream().filter(x -> x.containsKey(1) && x.get(1).containsKey(10)).mapToLong(x -> x.get(1).get(10)).findFirst();
if (optional.isPresent()) {
  return optional.getAsLong();

Use stream to iterate over list and filter elements containing maps with required values and return first element matching out criteria.

For aggregating, instead of findFirst(), you can reduce by adding starting with 0 as identity.

long l = listOfMap.stream().filter(x -> x.containsKey(1) && x.get(1).containsKey(10)).mapToLong(x -> x.get(1).get(10)).reduce(0L, (left, right) -> left + right);