先创建一个Person实体
@Data
public class Person{
private String name;
private Integer age;
}
List<Person> personList = new ArrayList<>();
1、将List转换为Map,以name作为key,age作为value。同时指定当键值重复时选取新的键值对。
Map map = personList.stream().collect(Collectors.toMap(Person::getName, Person::getAge,(oldValue, newValue) -> newValue));
2、将List转换为Map,以name作为key,本身作为value。同时指定当键值重复时选取新的键值对。
Map map = personList.stream().collect(Collectors.toMap(Person::getName, s->s,(oldValue, newValue) -> newValue));
3、将List转换为Map,以两个字段相加作为key,本身作为value。同时指定当键值重复时选取旧的键值对。
Map map = personList.stream().collect(Collectors.toMap((s) -> s.getName() + ";" + s.getAge(), (s) -> s, (oldValue, newValue) -> oldValue));
4、List根据属性name,age去重
List<Person> distinctList = personList.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(MyClass::getName)
.thenComparing(MyClass::getAge)) //按单个属性去重时,去掉thenComparing即可
)), ArrayList::new));
5、输出list中年龄等于5的第一个匹配到的对象,没有时返回null
Person person = personList.stream().filter(s -> s.getAge()==5).findFirst().orElse(null); //filter有多个属性时,用&&拼接
6、输出list中名字等于张三的第一个匹配到的对象,没有时返回null
Person person = personList.stream().filter(s -> s.getName().equals("张三")).findFirst().orElse(null);
7、收集list中名字等于张三的所有对象,并根据age去重
List<Person> person = personList.stream().filter(s -> s.getName().equals("张三")).collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getAge()))), ArrayList::new));
8、将list中的age组成新的list
List<Integer> list =personList.stream().map(Person::getAge).collect(Collectors.toList());
9、 将map中的value转为List
List distinct = new ArrayList<>(map.values());
862

被折叠的 条评论
为什么被折叠?



