示例
import com.jiuqi.bi.util.StringUtils;
import java.util.*;
import java.util.stream.Collectors;
public class CollectorsToMap {
private String id;
private String code;
private String title;
private Integer age;
public static void main(String[] args) {
List<CollectorsToMap> list = new ArrayList<>(
Arrays.asList(
new CollectorsToMap("u1", null, "t1",2),
new CollectorsToMap("u2", "c2", null,2),
new CollectorsToMap("u2", "c1", "t1",2),
new CollectorsToMap("", "", "",0),
new CollectorsToMap(null, null, null,null),
null
)
);
Map<String, String> map = list.stream().filter(item -> item != null && StringUtils.isNotEmpty(item.getId())).collect(Collectors.toMap(item -> item.getId(), item -> Optional.ofNullable(item.getCode()).orElse("c"), (oldVal, currVal) -> oldVal, LinkedHashMap::new));
System.out.println(map.getClass());
System.out.println(map.toString());
Map<String, String> map0 = list.stream().filter(item -> item != null && StringUtils.isNotEmpty(item.getId())).collect(Collectors.toMap(item -> item.getId(), item -> Optional.ofNullable(item.getCode()).orElse("c"), (oldVal, currVal) -> currVal));
System.out.println(map0.getClass());
System.out.println(map0.toString());
Map<Integer, String> map1 = list.stream().filter(item -> item != null && item.getAge() != null).collect(Collectors.toMap(CollectorsToMap::getAge, item->Optional.ofNullable(item.getTitle()).orElse("t"), (oldVal, currVal) -> oldVal+","+currVal));
System.out.println(map0.getClass());
System.out.println(map1.toString());
}
@Override
public String toString() {
return "CollectorsToMap{" +
"id='" + id + '\'' +
", code='" + code + '\'' +
", title='" + title + '\'' +
", age=" + age +
'}';
}
public CollectorsToMap(String id, String code, String title, Integer age) {
this.id = id;
this.code = code;
this.title = title;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
源码
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);
}
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}
}