How does one convert a HashMap to a List in Java?

后端 未结 7 1151
春和景丽
春和景丽 2020-12-08 01:35

In Java, how does one get the values of a HashMap returned as a List?

7条回答
  •  天命终不由人
    2020-12-08 02:30

    Solution using Java 8 and Stream Api:

    private static   List createListFromMapEntries (Map map){
            return map.values().stream().collect(Collectors.toList());
        }
    

    Usage:

      public static void main (String[] args)
        {
            Map map = new HashMap<>();
            map.put(1, "one");
            map.put(2, "two");
            map.put(3, "three");
    
            List result = createListFromMapEntries(map);
            result.forEach(System.out :: println);
        }
    

提交回复
热议问题