通过例子展示 java8 中如何使用 limit 、 filter 和 distinct 。
数据实体类:
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer age;
private String name;
}
初始化数据
List<Student> studentList = Lists.newArrayList ();
studentList.add (new Student (28,"river"));
studentList.add (new Student (12,"lucy"));
studentList.add (new Student (22,"frank"));
studentList.add (new Student (33,"kity"));
filter 方法 , 返回符合过滤条件的值
List<Student> filterList = studentList.parallelStream ()
.filter (t-> t.getAge () > 22)
.collect(Collectors.toList());
System.out.println (filterList);
[Student(age=28, name=river), Student(age=33, name=kity)]
limit 方法 ,返回限定数量的值
List<Student> limitList = studentList.parallelStream ().limit(2).collect(Collectors.toList());
System.out.println (limitList);
[Student(age=28, name=river), Student(age=12, name=lucy)]
distinct 方法,返回不同的年龄值
List<Integer> distinctList = studentList.parallelStream ().map(student -> student.getAge()).distinct().collect(Collectors.toList());
[28, 12, 22, 33]
感谢你的阅读。
网友评论