測試實體類
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時返回對應元素
List<User> userTmp = userList.stream().
filter(user -> user.getSex() == 0).
collect(Collectors.toList());
System.out.println(userTmp.size());
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
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中獲取指定元素數量
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));