首先看下代码
import lombok.AllArgsConstructor;
import lombok.Data;
import org.assertj.core.util.Lists;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TestMap {
public static void main(String[] args) {
List<Person> list = Lists.newArrayList();
list.add(new Person(1, "tom", "北京"));
list.add(new Person(2, "tom2", "北京1s"));
list.add(new Person(3, "tom4", null));
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getName, Person::getAddress));
System.out.println(map);
}
@Data
@AllArgsConstructor
public static class Person {
private Integer id;
private String name;
private String address;
}
}
看似没有问题,但是执行报错,
?查看源码?才知道?toMap底层调用的map.merge有非空判断
替代方案:
Map<String, String> map =list.stream().collect(HashMap :: new,(m, v)-> m.put(v.getName(), v.getAddress()), HashMap :: putAll);
?
|