javascript学习指南|Java三种方法将List转换为Map的实例

时间:2024-06-02  来源:Google  阅读:

1.for循环

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 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 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.使用guava

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

3.使用JDK1.8

Map maps = userList.stream().collect(Collectors.toMap(User::getId, user -> user));

看来还是使用JDK 1.8方便一些。

javascript学习指南|Java三种方法将List转换为Map的实例

http://m.bbyears.com/seo/157831.html

推荐访问:java学习路线
相关阅读 猜你喜欢
本类排行 本类最新