Three ways to convert List to Map

1. for loop

import com.google.common.base.Function;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListToMap {
    
    
    public static void main(String[] args) {
    
    
        List<User> userList = new ArrayList<>();
        User user1 = new User();
        user1.setId(1L);
        user1.setAge("12");

        User user2 = new User();
        user2.setId(2L);
        user2.setAge("13");

        userList.add(user1);
        userList.add(user2);

        Map<Long, User> maps = new HashMap<>();
        for (User user : userList) {
    
    
            maps.put(user.getId(), user);
        }

        System.out.println(maps);

    }

    public static class User {
    
    
        private Long id;
        private String age;

        public Long getId() {
    
    
            return id;
        }

        public void setId(Long id) {
    
    
            this.id = id;
        }

        public String getAge() {
    
    
            return age;
        }

        public void setAge(String age) {
    
    
            this.age = age;
        }

        @Override
        public String toString() {
    
    
            return "User{" +
                    "id=" + id +
                    ", age='" + age + '\'' +
                    '}';
        }
    }
}



2. Use guava

Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
    
    
        @Override
        public Long apply(User user) {
    
    
            return user.getId();
        }
});
    

3. Use JDK1.8

Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));

It seems more convenient to use JDK 1.8. In addition, when converting to a map, the same key may occur. If you do not specify an overwriting rule, the above code will report an error. When converting to map, it is best to use the following method:

Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));

Sometimes, the desired map value is not an object, but an attribute of the object, then you can use the following method:

Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));

Guess you like

Origin blog.csdn.net/weixin_43088443/article/details/112799556