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);
listOfMap.add(lMap1);
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);
listOfMap.add(lMap2);
Given 1
and 10
, it would return 100
.
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);
Could you provide an explanation of how this code solves the problem?
If multiple maps in the list contain the same key, the first map from the list will be picked by the
if
. Are you sure that is what OP wants?Updated my answer.