简体   繁体   中英

How to get value from hashmap in java 8

I am trying to achieve to refactor the below code into java8 using stream. How I can get the value of for any particular key in the hashmap Please suggest.

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapUtility {

public static void main(String[] args) {
    Map<String, List<Integer>> map = new HashMap<>();
    map.put("key1", Arrays.asList(1, 2, 3, 4));
    map.put("key2", Arrays.asList(4, 5, 6, 7));
    map.put("key3", Arrays.asList(8, 9, 10, 11));
    map.put("key4", Arrays.asList(12, 13, 14, 15));

    /*how to write it in JAVA8*/
    for (Map.Entry<String, List<Integer>> mapIter : map.entrySet()) {
        List<Integer> li = mapIter.getValue();
        for (Integer num : li) {
            if (num % 2 == 0) {
                System.out.println(num);
            }
        }
    }
}

}

You need to convert the nested Lists into a flat List by using flatMap . Afterwards you can perform the usual stream operations like filter and forEach .

public static void main(String[] args) {
  Map<String, List<Integer>> map = new HashMap<>();
  map.put("key1", Arrays.asList(1, 2, 3, 4));
  map.put("key2", Arrays.asList(4, 5, 6, 7));
  map.put("key3", Arrays.asList(8, 9, 10, 11));
  map.put("key4", Arrays.asList(12, 13, 14, 15));    

  map.values().stream()
    .flatMap(List::stream)
    .filter(num -> num % 2 == 0)
    .forEach(System.out::println);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM