假设有这么一个类:
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
使用stream流来将list转map
public void test(){
List<Student> list = Arrays.asList(
new Student(1, "张三" ),
new Student(2, "李四"),
new Student(3, "赵武" ),
new Student(4, "王六" )
);
/**
* key: id
*value : name
*/
Map<Integer, String> collect = list.stream()
.collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(collect);
/**
* key :id
* value: student
*/
Map<Integer, Student> collect1 = list.stream()
.collect(Collectors.toMap(Student::getId, v -> v));
System.out.println(collect1);
/**
* key :id
* value: student
* 但是这种情况是有重复的key 的情况下
*/
List<Student> list2 = Arrays.asList(
new Student(1, "张三" ),
new Student(2, "李四"),
new Student(3, "赵武" ),
new Student(1, "王六" )
);
// //这种会报错
// Map<Integer, String> collect2 = list2.stream()
// .collect(Collectors.toMap(Student::getId, Student::getName));
// System.out.println(collect2);
//稍微处理一下重复的key的问题
HashMap<Integer, String> collect3 = list2.stream()
.collect(Collectors.toMap(Student::getId, Student::getName, (n1, n2) -> n2, HashMap::new));
System.out.println(collect3);
}
运行结果如下:
{1=张三, 2=李四, 3=赵武, 4=王六}
{1=Student{id=1, name='张三'}, 2=Student{id=2, name='李四'}, 3=Student{id=3, name='赵武'}, 4=Student{id=4, name='王六'}}
{1=王六, 2=李四, 3=赵武}
源码:
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}
这种没有对key重复的时候做处理,在实际开发中肯定会考虑导key是否重复的场景;
下面这种方式可以将处理后的数据返回到一个新的map(指定的容器)之中
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier) {
BiConsumer<M, T> accumulator
= (map, element) -> map.merge(keyMapper.apply(element),
valueMapper.apply(element), mergeFunction);
return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
}
并行流: