使用Stream api打印HashMap值

时间:2017-05-24 21:04:24

标签: java api stream hashmap

HashMap<String, Double> missions = new HashMap<>();
missions.put("name", 1.0);
missions.put("name1", 2.0);
missions.keySet().stream().forEach(el-> System.out.println(el));

仅打印关键字

3 个答案:

答案 0 :(得分:5)

使用entrySet()(或values(),如果您需要的话)而不是keySet()

Map<String, Double> missions = new HashMap<>();
missions.put("name", 1.0);
missions.put("name1", 2.0);
missions.entrySet().stream().forEach(e-> System.out.println(e));

答案 1 :(得分:0)

HashMap<String, Double> missions = new HashMap<>();
missions.put("name", 1.0);
missions.put("name1", 2.0);
missions.entrySet().forEach(System.out::println);

输出:

name=1.0
name1=2.0

答案 2 :(得分:-1)

// Stores the values in a list which can later used

missions.values().stream().collect(Collectors.toList());

//print it to standard op

missions.values().forEach(val -> System.out.println(val));