Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 | Parallel Stream for a HashMap

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

like image 734
John S. Avatar asked May 02 '16 19:05

John S.


2 Answers

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()));
like image 138
rgettman Avatar answered Sep 28 '22 07:09

rgettman


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()));
like image 39
AJ Jwair Avatar answered Sep 28 '22 08:09

AJ Jwair