In java 8 I know that they added the parallel stream which takes advantage of multicore processors, and I know that you can use it with something like this:
List<String> list = new ArrayList<String>();
list.parallelStream().forEach(str -> System.out.println(str));
But how would I achieve something like this with a HashMap?
Map<String, Integer> map = new HashMap<String, Integer>();
// won't work, because the Map class doesn't have the .parallelStream()
map.parallelStream().forEach((str, num) -> System.out.println(str + ":" + num));
Does anyone know how to do something like this? Thanks
You can't stream a Map
directly, but you can stream its entry set, given with the entrySet()
method. Extract the key and value from the entry object.
map.entrySet()
.parallelStream()
.forEach(entry -> System.out.println(entry.getKey() + ":" + entry.getValue()));
You can get the 'entry set' from the hash map by calling map.entrySet(), you can call parallelStream() on the returned entry set.
Please note that the returned object is a set of Map.Entry. You can get the key and value from an entry set item by calling getKey() and getValue() on it respectively. As follows:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.entrySet().parallelStream().forEach((e) -> System.out.println(e.getKey() + ":" + e.getValue()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With