Java 8 List into Map

前端 未结 22 2748
半阙折子戏
半阙折子戏 2020-11-22 03:38

I want to translate a List of objects into a Map using Java 8\'s streams and lambdas.

This is how I would write it in Java 7 and below.

private Map&l         


        
22条回答
  •  日久生厌
    2020-11-22 04:27

    For example, if you want convert object fields to map:

    Example object:

    class Item{
            private String code;
            private String name;
    
            public Item(String code, String name) {
                this.code = code;
                this.name = name;
            }
    
            //getters and setters
        }
    

    And operation convert List To Map:

    List list = new ArrayList<>();
    list.add(new Item("code1", "name1"));
    list.add(new Item("code2", "name2"));
    
    Map map = list.stream()
         .collect(Collectors.toMap(Item::getCode, Item::getName));
    

提交回复
热议问题