private final static String YELLOW = "1";
private final static String WHITE = "2";
private final static String BLACK = "3";
@Data
@AllArgsConstructor
class Person{
private String name;
private Integer age;
private String color;
}
@Test
public void streamTestMethod(){
List<Person> personList = new ArrayList<>();
personList.add(new Person("周星驰",55,YELLOW));
personList.add(new Person("维塔斯",48,WHITE));
personList.add(new Person("路德金",97,BLACK));
personList.add(new Person("陈奕迅",65,YELLOW));
personList.add(new Person("伍佰",56,YELLOW));
//按照年龄排序
//第一种写法
//想要降序排列可以在comparing后加上.reversed()
List<Person> orderByAge = personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
//第二种写法
List<Person> orderByAgeSecond = personList.stream().sorted(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
//其他属性亦是如此操作,且如果要升序排序的话,将减号两边调换位置即可
return o1.getAge() - o2.getAge();
}
}).collect(Collectors.toList());
//按照肤色分组,分组后即为肤色A->对应肤色为A的Person的list
Map<String, List<Person>> colorMap = personList.stream().collect(Collectors.groupingBy(Person::getColor));
//Map的遍历
colorMap.forEach(
(col,colList) -> {
log.info("颜色{}对应person列表为{}",col,colList);
}
);
//过滤出列表中年龄大于60的人
List<Person> gtList = personList.stream().filter(person -> person.getAge() > 65).collect(Collectors.toList());
//获取列表中所有人的名字并转为新的list
List<String> nameList = personList.stream().map(person -> person.getName()).collect(Collectors.toList());
//去重
List<Person> collect = personList.stream().distinct().collect(Collectors.toList());
//分页
Integer current = 1; //当前页码
Integer size = 10; //每页数量
List<Person> pageList = personList.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList());
//构建对象中某两种属性的映射关系Map
//构建person的名字和肤色的映射关系
Map<String, String> nameColorMap = personList.stream().collect(Collectors.toMap(Person::getName, Person::getColor));
}
Java中Stream流的常见应用
最新推荐文章于 2024-07-04 09:24:51 发布