list转map
public class Stream1 {
public static void main(String[] args) {
List<User> nums = Arrays.asList(new User(1,"lisi","女"), new User(2,"tom","男"));
Map<Integer, String> map = nums.stream().collect(Collectors.toMap(User::getId, User::getName));
//因为需要的是Function型接口,所以我们可以成下面这种
Map<Integer, String> map2 = nums.stream()
.collect(Collectors.toMap(
(item)->{return item.getId();},
(item)->{return item.getName();}
));
}
}
class User{
private int id;
private String name;
private String age;
}
疑惑:Collectors.toMap(Function keyMapper,Function valueMapper)中两个参数类型都是函数型接口,而我们传入的却是消费性接口?看源码解惑。内部确实使用的消费型接口。
方法引用
public class Stream1 {
public static void main(String[] args) {
List<User> nums = Arrays.asList(new User(1,"lisi","男"), new User(2,"tom","男"));
nums.forEach(System.out::println);
//因为所需要的参数为消费型接口,所以可以改写为下面这种
nums.forEach((item)->{
System.out.println("item.toString() = " + item.toString());
});
}
}
class User{
private int id;
private String name;
private String age;
}