Java 8 List into Map

前端 未结 22 2494
半阙折子戏
半阙折子戏 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条回答
  •  旧时难觅i
    2020-11-22 04:36

    This can be done in 2 ways. Let person be the class we are going to use to demonstrate it.

    public class Person {
    
        private String name;
        private int age;
    
        public String getAge() {
            return age;
        }
    }
    

    Let persons be the list of Persons to be converted to the map

    1.Using Simple foreach and a Lambda Expression on the List

    Map> mapPersons = new HashMap<>();
    persons.forEach(p->mapPersons.put(p.getAge(),p));
    

    2.Using Collectors on Stream defined on the given List.

     Map> mapPersons = 
               persons.stream().collect(Collectors.groupingBy(Person::getAge));
    

提交回复
热议问题