Java 8 List into Map

前端 未结 22 2484
半阙折子戏
半阙折子戏 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:34

    If you don't mind using 3rd party libraries, AOL's cyclops-react lib (disclosure I am a contributor) has extensions for all JDK Collection types, including List and Map.

    ListX<Choices> choices;
    Map<String, Choice> map = choices.toMap(c-> c.getName(),c->c);
    
    0 讨论(0)
  • 2020-11-22 04:34

    You can create a Stream of the indices using an IntStream and then convert them to a Map :

    Map<Integer,Item> map = 
    IntStream.range(0,items.size())
             .boxed()
             .collect(Collectors.toMap (i -> i, i -> items.get(i)));
    
    0 讨论(0)
  • 2020-11-22 04:36

    Based on Collectors documentation it's as simple as:

    Map<String, Choice> result =
        choices.stream().collect(Collectors.toMap(Choice::getName,
                                                  Function.identity()));
    
    0 讨论(0)
  • 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<Integer,List<Person>> mapPersons = new HashMap<>();
    persons.forEach(p->mapPersons.put(p.getAge(),p));
    

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

     Map<Integer,List<Person>> mapPersons = 
               persons.stream().collect(Collectors.groupingBy(Person::getAge));
    
    0 讨论(0)
提交回复
热议问题