Java8 Stream詳解

測試實體類

public class User {
      private String id;
      private String name;
      private Integer age;
      private Integer sex;
       public User() {
    }
    public User(String id, String name, Integer age, Integer sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
      .....省略get set
}      
//測試數據
List<User> userList=new ArrayList<>();
        userList.add(new User("1","test-1",21,1));
        userList.add(new User("1","test-1",17,0));
        userList.add(new User("1","test-1",17,0));
        userList.add(new User("1","test-1",18,1));

1.filter 對元素進行過濾,當過濾條件爲true時返回對應元素

  • 過濾性別爲0的用戶
   List<User> userTmp = userList.stream().
                 filter(user -> user.getSex() == 0).
                     collect(Collectors.toList());
         System.out.println(userTmp.size());
  • 過濾性別爲0的用戶,並把年齡設置爲17
List<User> userTmp2 = userList.stream().
                filter(user -> user.getSex() == 0)
                .peek(user -> user.setAge(17))
                .collect(Collectors.toList());
 System.out.println(userTmp2.size());

2.sorted 對元素按指定規則進行排序

  • 按年齡升序排序
        //方法一
        List<User> newUserList2=userList.stream().sorted((user1,user2)->{
            return user1.getAge().compareTo(user2.getAge());
        }).collect(Collectors.toList());
        //方法二
        List<User> newUserList = userList.stream().
                 sorted(Comparator.comparing(User::getAge)).
                  collect(Collectors.toList());
        //遍歷集合
        newUserList2.forEach(System.out::println);
  • 按年齡降序排序
List<User> newUserList = userList.stream().
                 sorted(Comparator.comparing(User::getAge).reversed())
                  .collect(Collectors.toList());
        //遍歷集合
        newUserList2.forEach(System.out::println);

3.map

         // 從集合中提取id
        List<String> ids = userList.stream().map(user -> user.getId()).collect(Collectors.toList());
        ids.forEach(System.out::println);

4.mapToDouble、mapToInt、mapToLong

  • 求年齡平均數
        //方法一
        double asDouble = userList.stream().mapToLong(User::getAge).average().getAsDouble();
        System.out.println(asDouble);
        //方法二
        Double avgAge = userList.stream().collect(Collectors.averagingDouble(User::getAge));
        System.out.println(avgAge);
  • 年齡最大值
 int maxAge = userList.stream().mapToInt(User::getAge).max().getAsInt();
 System.out.println(maxAge);
  • 年齡最小值
int minAge = userList.stream().mapToInt(User::getAge).min().getAsInt();
System.out.println(minAge);
  • 年齡求和
 long sumAge = userList.stream().mapToLong(user -> user.getAge()).sum();
 System.out.println(sumAge);

4.count從Stream中獲取指定元素數量

// 獲取年齡爲0的用戶數量
long count = userList.stream().filter(user -> user.getSex() == 0).count();

5.limit獲取指定數量的元素

 // 獲取前兩條數據
 List<User> newUserList = userList.stream().limit(2).collect(Collectors.toList());
 newUserList.forEach(System.out::println);

6.skip 跳過指定個數的元素獲取後面的元素

 List<User> newUserList = userList.stream().skip(2).collect(Collectors.toList());
 newUserList.forEach(System.out::println);

7.map轉list

Map<String, User> collect = userList.stream().collect(Collectors.toMap(user -> user.getId(), user -> user));

8.去重

//根據年齡去重
 List<User> users = userList.stream().
                collect(collectingAndThen(
                toCollection(() -> new TreeSet<>(comparingLong(User::getAge))), ArrayList::new));
發佈了36 篇原創文章 · 獲贊 3 · 訪問量 6846
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章