源: java中的stream的Map收集器操作
package test9;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectorsTest {
public static void main(String[] args) {
Map<String, Person> map = Stream
.of(Person.valueOf("小明", '男', 18), Person.valueOf("小麗", '女', 16), Person.valueOf("小王", '男', 19))
.collect(Collectors.toMap(Person::getName, Function.identity()));
System.out.println("map:" + map);
Map<String, Person> map2 = Stream
.of(Person.valueOf("小明", '男', 18), Person.valueOf("小麗", '女', 16), Person.valueOf("小明", '男', 19))
.collect(Collectors.toMap(Person::getName, Function.identity(), (x, y) -> y));
System.out.println("如果有2個key重復了就用新的,‘y’,想用舊的代替就用'x',自己選擇,map2:" + map2);
/*
* 需求:要求將已有的國家名為key, 人名為value(當然也可以是對象)集合。
*/
Map<String, Set<String>> map3 = Stream
.of(Person.valueOf("China", "小明"), Person.valueOf("China", "小麗"), Person.valueOf("us", "Jack"),
Person.valueOf("us", "Alice"))
.collect(Collectors.toMap(Person::getCountry, p -> Collections.singleton(p.getName()), (x, y) -> {
Set<String> set = new HashSet<>(x);
set.addAll(y);
return set;
}));
System.out.println("map3:" + map3);
// 將所有元素檢查key不重復且最終包裝成一個TreeMap對象
Map<String, String> map4 = Stream.of(Person.valueOf("China", "小明"), Person.valueOf("Chinsa", "小麗"), Person.valueOf("us", "Jack"),
Person.valueOf("uss", "Alice"))
.collect(Collectors.toMap(
Person::getCountry,
Person::getName, (x, y) ->
{
throw new IllegalStateException();
},TreeMap::new));
System.out.println(map4);
}
}
class Person {
private String country;
private String name;
private Character sex;
private Integer age;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Character getSex() {
return sex;
}
public void setSex(Character sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "name:" + name + "sex:" + sex + "age" + age;
}
public static Person valueOf(String country, String name) {
Person person = new Person();
person.country = country;
person.name = name;
return person;
}
public static Person valueOf(String name, Character sex, Integer age) {
Person person = new Person();
person.name = name;
person.sex = sex;
person.age = age;
return person;
}
}
打印結果:
map:{小明=name:小明sex:男age18, 小麗=name:小麗sex:女age16, 小王=name:小王sex:男age19}
如果有2個key重復了就用新的,‘y’,想用舊的代替就用'x',自己選擇,map2:{小明=name:小明sex:男age19, 小麗=name:小麗sex:女age16}
map3:{China=[小明, 小麗], us=[Alice, Jack]}
{China=小明, Chinsa=小麗, us=Jack, uss=Alice}
