list集合转化为map

1,user.java

public class User implements java.io.Serializable {


	private Long id;
	private String Name;

	public UserSource(Long id) {
		this.id = id;
	}

	public Long getId() {
		return this.id;
	}

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

	public String getName() {
		return this.Name;
	}

	public void setName(String Name) {
		this.Name = Name;
	}

}

2,test.java

List userlist=new ArrayList<>();
userlist.add(new User(1,"qiao"));
Map<Long, String> userMap = userList.stream().collect(
						Collectors.toMap(User::getId, User::getName));

如果id未key,实体类为value,

/**
 * List -> Map
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key .... *  apple1,apple12的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1));

你可能感兴趣的:(java,map)