1、Stream 流
List<String> strings = Arrays.asList("a", "a", "", "b", "c","", "d");
List<String> filtered = strings.stream() //获取流
.filter(string -> !string.isEmpty()) //过滤为空的字符串
.distinct() //去重
.collect(Collectors.toList()); //流转集合
filtered.stream().forEach(System.out::println); // 遍历输出结果:a b c d
filtered.stream().map(str -> str.toUpperCase()) //转大写字母(map用于映射每个元素到对应的结果)
.limit(3) //限制只有3个数据
.forEach(System.out::println); //输出结果:A B C
String strResult = filtered.stream().collect(Collectors.joining(", ")); //拼接集合字符串
class Student {
String name;
int age;
}
List<Student> studentList = Arrays.asList(new Student("周一", 11), new Student("周五", 55),
new Student("周二", 22), new Student("周三", 33), new Student("周四", 44));
List<Student> studentList2 = studentList .stream()
.map(s -> new Student(s.getName(), s.getAge() * 2)) //映射对象年龄乘以2
.collect(Collectors.toList()); //返回学生对象数组
studentList.stream().map(s -> s.getAge() * 2) //映射结果为年龄乘以2
.forEach(System.out::println); //输出结果:22 110 44 66 88
studentList.stream().filter(s -> s.getAge() > 20)
.sorted((s1, s2) -> s1.getAge() - s2.getAge())
.forEach(System.out::println); /**输出结果:Student{name='周二', age=22}
Student{name='周三', age=33}
Student{name='周四', age=44}
Student{name='周五', age=55} */
Student student = studentList.stream().findFirst().orElse(null); //获取集合中第一个元素
int sumAge = studentList.stream().mapToInt(s -> s.getAge()).sum(); //映射整形累加结果:165
网友评论