A little example, I had to develop as a teaching use case, of how to take a map
with Integer
keys and values with a List
as value and find a specific value in any List
in the whole map using Java Streams.
boolean b1
returns true
because the element exists
boolean b2
is the response to an element that doesn’t exist
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.company; import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Map<Integer, List<String>> hm = new HashMap<>(); hm.put(1, getRandomListValues(1)); hm.put(2, getRandomListValues(2)); hm.put(3, getRandomListValues(3)); hm.put(4, getRandomListValues(4)); hm.put(5, getRandomListValues(5)); boolean b1 = hm.values().stream().flatMap(l -> l.stream()).anyMatch(i -> i.equals("3-2")); boolean b2 = hm.values().stream().flatMap(l -> l.stream()).anyMatch(i -> i.equals("33-2")); System.out.println(b1); System.out.println(b2); } private static List<String> getRandomListValues(int v) { List<String> l = new ArrayList<>(); for(int i = 0; i < 10; i++) { l.add(v + "-" + i); } return l; } } |