list.stream().forEach(s-> System.out.println(s));
//Integer类型求和
System.out.println("===========Integer类型求和==================");
Integer sum = list.stream().reduce(Integer::sum).orElse(0);
Integer sum1 = list.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum+","+sum1);
//Integer类型求最大值
System.out.println("===========Integer类型求最大值==================");
Integer max = list.stream().reduce(Integer::max).orElse(0);
int max1 = list.stream().mapToInt(Integer::intValue).max().getAsInt();
System.out.println(max+","+max1);
//Integer类型求平均值
double average = list.stream().mapToDouble(Integer::intValue).average().getAsDouble();
System.out.println(average);
//list集合过滤(也就是选出符合条件的元素)
List<Integer> filter = list.stream().filter(s -> s > 20 && s < 40).collect(Collectors.toList());
System.out.println(filter);
//对集合元素进行从小到大排序
List<Integer> sort = list.stream().sorted().collect(Collectors.toList());
sort.stream().forEach(s-> System.out.println(s));
//对集合元素进行从大到小排序
List<Integer> upSort = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
upSort.stream().forEach(s-> System.out.println(upSort));
这里我们根据自己自定义的用户类来做笔记
//用户年龄总值
int sumAge = list.stream().mapToInt(User::getAge).sum();
//用户年龄最大值
int maxAge = list.stream().mapToInt(User::getAge).max().getAsInt();
//用户年龄最小值
int minAge = list.stream().mapToInt(User::getAge).min().getAsInt();
//用户年龄平均值
double averageAge= list.stream().mapToInt(User::getAge).average().getAsDouble();
//根据年龄条件过滤用户
List<User> filterAsAge = list.stream().filter(user -> user.getAge() > 15 && user.getAge() < 15).collect(Collectors.toList());
//根据年龄从小到大排序
list.sort(Comparator.comparing(User::getAge));
list.stream().forEach(s-> System.out.println(s));
//根据年龄从大到小排序
list.sort(Comparator.comparing(User::getAge).reversed());
list.stream().forEach(s-> System.out.println(s));
//对集合元素先根据年龄进行从大到小排序,如果年龄相同,再根据id进行从大到小排序
list.sort(Comparator.comparing(User::getAge,((o1, o2) -> o2-o1)).thenComparing(User::getId,((o1, o2) -> o2-o1)));
list.stream().forEach(s-> System.out.println(s));
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
facultyRetList = facultyList.stream().filter(distinctByKey(Faculty::getId)).collect(Collectors.toList());