package com.baifan.collecting;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author: baifan
* @date: 2021/2/5
*/
public class CollectingIntoMaps {
public static class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
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 "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
public static Stream<Person> people() {
return Stream.of(new Person(1001, "张三"), new Person(1002, "李四"), new Person(1003, "王五"));
}
public static void main(String[] args) {
Map<Integer, String> idToName = people().collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println("idToName:" + idToName);
Map<Integer, Person> idToPerson = people().collect(Collectors.toMap(Person::getId, Function.identity()));
System.out.println("idToPerson:" + idToPerson.getClass().getName() + idToPerson);
idToPerson = people().collect(Collectors.toMap(Person::getId, Function.identity(), (existingValue, newValue) -> {
throw new IllegalStateException();
}, TreeMap::new));
System.out.println("idToPerson:" + idToPerson.getClass().getName() + idToPerson);
Stream<Locale> locales = Stream.of(Locale.getAvailableLocales());
Map<String, String> languageNames = locales.collect(Collectors.toMap(
Locale::getDisplayName,
locale -> locale.getDisplayLanguage(locale),
(existingValue, newValue) -> existingValue
));
System.out.println("languageNames:" + languageNames);
locales = Stream.of(Locale.getAvailableLocales());
Map<String, Set<String>> countryLanguageSets = locales.collect(
Collectors.toMap(Locale::getDisplayCountry, locale -> Collections.singleton(locale.getDisplayLanguage()),
(a, b) -> {// union of a and b
Set<String> union = new HashSet<>(a);
union.addAll(b);
return union;
}));
System.out.println("countryLanguageSets:" + countryLanguageSets);
}
}
Stream流的collect转化到Map映射
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Stream API 上篇内容我们学习了Stream的大部分终端操作,我们这篇着重了解下Stream中重要的终端操...
- 一、Stream类中的collect方法 概述 collect方法为java.util.Stream类的内部方法,...
- 参考书籍:《Java 8函数式编程》 上篇Java8之Stream类[https://www.jianshu.co...
- 1.collect(Collectors.toList()) Stream language = Stream....