集合 Collection.stream()
静态方法 Stream of
数组 Arrays.stream
//1.集合
Stream<Student> stream = basketballClub.stream();
//2.静态方法
Stream<String> stream2 = Stream.of("a", "b", "c");
//3.数组
String[] arr = {"a","b","c"};
Stream<String> stream3 = Arrays.stream(arr);
/**
* filter - 筛选
*/
public static void filter(List<Student> studentList){
List<Student> collect = studentList.stream().filter(student -> student.getAge() > 2).collect(Collectors.toList());
collect.forEach(e-> System.out.println(e));
}
public static void filter02(List<Student> studentList){
List<Student> zishu = studentList.stream().filter(student -> student.getName().equals("zishu")).collect(Collectors.toList());
zishu.forEach(e-> System.out.println(e));
}
map(Function f) 接收流中元素,并且将其映射成为新元素,例如从student对象中取name属性
/**
* 将两个字段组成map
* 其中key必须是唯一的
*/
public static void toMap(List<Student> studentList){
Map<Integer, String> collect = studentList.stream().collect(Collectors.toMap(Student::getId, Student::getName));
collect.forEach((key,value)->{
System.out.println("key==="+key);
System.out.println("value==="+value);
});
}
/**
* 将某个字段提取生成一个新的list
*
**/
List<Object> newList = objectList.stream().map(Object::getVar).collect(Collectors.toList());
/**
* groupBy - 分组 - 根据一个字段进行分组
*/
public static void groupBy(List<Student> studentList){
Map<Integer, List<Student>> collect = studentList.stream().collect(Collectors.groupingBy(Student::getId));
collect.forEach((key,value)->{
System.out.println("key==="+key);
System.out.println("value==="+value);
});
}
/**
* groupBy - 分组 - 根据多个字段进行分组
*/
public static void groupBy02(List<Student> studentList){
Map<String, List<Student>> collect = studentList.stream().collect(Collectors.groupingBy(student ->
student.getId() +","+ student.getName()
));
collect.forEach((key,value)->{
System.out.println("key==="+key);
System.out.println("value==="+value);
});
}
list.stream().mapToDouble(User::getHeight).sum()//和
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值
Double示例:
public class HelloWorld {
private static final DecimalFormat df = new DecimalFormat("0.00");//保留两位小数点
public static void main(String[] args) {
Random random = new Random();
List<User> list = new ArrayList<>();
for(int i=1;i<=5;i++) {
double weight = random.nextDouble() * 100 + 100;//随机身高:100-200
User u = new User(i, "用户-" + i, weight);
list.add(u);
}
System.out.println("用户:" + list);
double sum = list.stream().mapToDouble(User::getHeight).sum();
System.out.println("身高 总和:" + df.format(sum));
double max = list.stream().mapToDouble(User::getHeight).max().getAsDouble();
System.out.println("身高 最大:" + df.format(max));
double min = list.stream().mapToDouble(User::getHeight).min().getAsDouble();
System.out.println("身高 最小:" + df.format(min));
double average = list.stream().mapToDouble(User::getHeight).average().getAsDouble();
System.out.println("身高 平均:" + df.format(average));
}
BigDecimal示例:
public class HelloWorld {
private static final DecimalFormat df = new DecimalFormat("0.00");//保留两位小数点
public static void main(String[] args) {
Random random = new Random();
List<User> list = new ArrayList<>();
for(int i=1;i<=5;i++) {
double weight = random.nextDouble() * 100 + 100;//随机身高:100-200
list.add(new User(i, new BigDecimal(weight).setScale(BigDecimal.ROUND_HALF_UP, 2)));
}
System.out.println("list:" + list);
BigDecimal add = list.stream().map(User::getHeight).reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println("身高 总和:" + df.format(add));
Optional<User> max = list.stream().max((u1, u2) -> u1.getHeight().compareTo(u2.getHeight()));
System.out.println("身高 最大:" + df.format(max.get().getHeight()));
Optional<User> min = list.stream().min((u1, u2) -> u1.getHeight().compareTo(u2.getHeight()));
System.out.println("身高 最小:" + df.format(min.get().getHeight()));
}
交集(listA ∩ ListB):
List<Person> listC = listA.stream().filter(item -> listB.contains(item)).collect(Collectors.toList());
listC中的元素有:属性name值为 aa, bb, cc 的对象。
并集(listA ∪ listB):
//先合体
listA.addAll(listB);
//再去重
List<Person> listC = listA.stream().distinct().collect(Collectors.toList());
listC中的元素有:属性name值为 aa, bb, cc ,dd的对象。
差集(listA - listB):
List<Person> listC = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());
flatMap(Function f) 将所有流中的元素并到一起连接成一个流
/**
* 将三个集合组合,然后进行筛选
*/
public static void collectThree(List<Student> list1,List<Student> list2,List<Student> list3){
Stream<List<Student>> listStream = Stream.of(list1, list2, list3);
List<Student> collect = listStream.flatMap(e -> e.stream().filter(student -> student.getAge() > 50)).collect(Collectors.toList());
collect.forEach(e-> System.out.println(e));
}
peek(Consumer c) 获取流中元素,操作流中元素,与foreach不同的是不会截断流,可继续操作流
/**
* peek
*/
public static void peek(List<Student> list){
list.stream().peek(student -> student.setName(student.getName()+"88888"))
.collect(Collectors.toList())
.forEach(e-> System.out.println(e));
}
distinct() 通过流所生成元素的equals和hashCode去重
/**
* 去重
*/
public static void distinct(List<String> list){
List<String> collect = list.stream().distinct().collect(Collectors.toList());
collect.forEach(e-> System.out.println(e));
}
limit(long val) 截断流,取流中前val个元素
/**
* 截取
*/
public static void limit(List<String> list){
List<String> collect = list.stream().limit(2).collect(Collectors.toList());
collect.forEach(e-> System.out.println(e));
}
sorted(Comparator) 产生一个新流,按照比较器规则排序
/**
* 排序
* 从小到大
* list.sort(((o1, o2) -> o1-o2));
* 从大到小
* list.sort(((o1, o2) -> o2-o1));
*/
public static void sort(List<Integer> list){
List<Integer> collect = list.stream().sorted(((o1, o2) -> o2 - o1)).collect(Collectors.toList());
collect.forEach(e-> System.out.println(e));
}
// 升序
employDOList.stream().sorted(Comparator.comparing(EmployDO::getAge)).collect(Collectors.toList())
.forEach(s -> System.out.print(s.getName() + " "));
System.out.println(" ");
// 降序
employDOList.stream().sorted(Comparator.comparing(EmployDO::getAge).reversed())
.forEach(s -> System.out.print(s.getName() + " "));
Optional<Student> first = basketballClub.stream().findFirst();
if (first.isPresent()) {
Student student = first.get();
System.out.println(student);
}
Optional<Student> any = basketballClub.stream().findAny();
if (any.isPresent()) {
Student student2 = any.get();
System.out.println(student2);
}
Optional<Student> any1 = basketballClub.stream().parallel().findAny();
System.out.println(any1);
long count = basketballClub.stream().count();
Optional<Student> max = basketballClub.stream().max(Comparator.comparing(Student::getAge));
if (max.isPresent()) {
Student student = max.get();
}
Optional<Student> min = basketballClub.stream().min(Comparator.comparingInt(Student::getAge));
if (min.isPresent()) {
Student student = min.get();
}
~~~java
Optional<Student> max = basketballClub.stream().max(Comparator.comparing(Student::getAge));
if (max.isPresent()) {
Student student = max.get();
}
Optional<Student> min = basketballClub.stream().min(Comparator.comparingInt(Student::getAge));
if (min.isPresent()) {
Student student = min.get();
}