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 + '\'' +
'}';
}
}
}
Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
@Override
public Long apply(User user) {
return user.getId();
}
});
//声明一个List集合
List<Person> list = new ArrayList();
list.add(new Person("1001", "小A"));
list.add(new Person("1002", "小B"));
list.add(new Person("1003", "小C"));
System.out.println(list);
//将list转换map
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId,Person::getName));
Map<String, ParamCalcrate> paramCalcrateMap = paramCalcrates.stream().collect(Collectors.toMap(paramCalcrate -> paramCalcrate.getTpId(), Function.identity()));
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key2 ));
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));
在转换流中加上判空,即便value为空,依旧输出
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
))