java8 - limit & filter & distinct

通過例子展示 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]

感謝你的閱讀。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章