首页 > 其他分享 >stream流学习笔记

stream流学习笔记

时间:2022-11-18 17:16:06浏览次数:44  
标签:Collectors stream System 笔记 学习 collect println out

List<Student> students = new ArrayList<>();
students.add(new Student(1, 19, "张三", "M", true));
students.add(new Student(1, 18, "张三1", "M", false));
students.add(new Student(1, 21, "张三2", "F", true));
students.add(new Student(1, 20, "李四", "M", false));
students.add(new Student(1, 20, "王五", "F", true));
students.add(new Student(1,20,"赵六","F",false));
// stream流的一些操作:
// 1、用filter实现数据过滤
// List<Student> studentStream = students.stream().filter(t -> t.getAge() < 20).collect(Collectors.toList());
//// System.out.println(studentStream);
// 2、用distinct实现数据去重
// List<Integer> list = Arrays.asList(1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 2, 2, 2, 2);
// List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
// System.out.println(collect);
// 3、映射 获取指定的字段属性
// List<String> collect = students.parallelStream().map(Student::getUsername).collect(Collectors.toList());
// System.out.println(collect);
//// 4、匹配 基于anyMatch()判断条件至少匹配一个元素
// if (students.stream().anyMatch(student -> student.getAge() < 20)) {
// System.out.println("集合中有");
// } else {
// System.out.println("没有");
// }
// 5、基于findAny()查找元素
// Optional<Student> f = students.parallelStream().filter(student -> student.getSex().equals("F")).findAny();
// System.out.println(f);
// 6、分组 groupingBy分组处理
// Map<String, List<Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getSex));
// System.out.println(collect);
// 7、多级分组
// Map<String, Map<Boolean, List<Student>>> collect1 = students.stream().collect(Collectors.groupingBy(Student::getSex, Collectors.groupingBy(Student::getIsNo)));
// System.out.println(collect1);
// 8、多级分组变形 在开发中不需要返回一个集合 还是返回一个数据的汇总
// Map<Integer, Long> collect = students.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.counting()));
// System.out.println(collect);
// 9、要根据年龄是否及格进行分组,并获取每组中年龄的学生
Map<Integer, Map<Boolean, Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(Student::getIsNo, Collectors
.collectingAndThen(Collectors.maxBy(Comparator.comparing(Student::getAge)), Optional::get))));
System.out.println(collect);

 

public class StreamTest {

public static List<Person> personList = new ArrayList<Person>();

public static void init() {
personList.add(new Person("Tom", 8900, 23, "male", "New York"));
personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
personList.add(new Person("Anni", 8200, 24, "female", "New York"));
personList.add(new Person("Owen", 9500, 25, "male", "New York"));
personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
}


public static void main(String[] args) {
init();
}

/**
* 提取/组合
* 流也可以进行合并、去重、限制、跳过等操作。
*/
public static void test13(){
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };

Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);

// concat:合并两个流 distinct:去重
List<String> collect = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
System.out.println("collect = " + collect);

// limit:限制从流中获得前n个数据
List<Integer> collect1 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
System.out.println("collect1 = " + collect1);

// skip:跳过前n个数据
List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(4).collect(Collectors.toList());
System.out.println("collect2 = " + collect2);
}


/**
* 排序(sorted)
* sorted,中间操作。有两种排序:
* sorted():自然排序,流中元素需实现Comparable接口
* sorted(Comparator com):Comparator排序器自定义排序
*/
public static void test12() {
// 案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序
// 按照工资进行排序,自然排序
List<String> collect = personList.stream()
.sorted(Comparator.comparing(Person::getSalary))
.map(Person::getName)
.collect(Collectors.toList());
System.out.println("collect = " + collect);

// 按照工资进行倒序
List<Integer> collect1 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getSalary)
.collect(Collectors.toList());
System.out.println("collect1 = " + collect1);

// 先按照工资再按照年龄进行升序排序
List<String> collect2 = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge))
.map(Person::getName)
.collect(Collectors.toList());
System.out.println("collect2 = " + collect2);

// 先按工资再按照年龄倒序
List<String> collect3 = personList.stream().sorted((p1, p2) -> {
if (p1.getSalary() == p2.getSalary()) {
return p2.getAge() - p1.getAge();
} else {
return p2.getSalary() - p1.getSalary();
}
}).map(Person::getName).collect(Collectors.toList());
System.out.println("collect3 = " + collect3);
}


/**
* 归约(reducing)
* Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。
*/
public static void test11() {
// 每个员工减去起征点后的薪资之和(这个例子并不严谨,但一时没想到好的例子)
Integer collect = personList.stream()
.collect(Collectors.reducing(0,
Person::getSalary,
(i, j) -> (i + j - 5000)));
System.out.println("collect = " + collect);

// stream的reduce
Optional<Integer> sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
System.out.println("员工薪资总和:" + sum2.get());
}


/**
* 接合(joining)
* joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
*/
public static void test10() {
String joinStr = personList.stream()
.map(person -> person.getName())
.collect(Collectors.joining(", "));
System.out.println("joinStr = " + joinStr);

List<String> list = Arrays.asList("A", "B", "C");
String str = list.stream().collect(Collectors.joining("-"));
System.out.println("str = " + str);
}


/**
* 分组(partitioningBy/groupingBy)
* 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
* 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
*/
public static void test09() {
// 案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组
Map<Boolean, List<Person>> part =
personList.stream().collect(Collectors.partitioningBy(person -> person.getSalary() > 8000));
System.out.println("part = " + part);

// 将员工按照性别进行分组
Map<String, List<Person>> sexMap = personList.stream().collect(Collectors.groupingBy(Person::getSex));
System.out.println("sexPart = " + sexMap);

// 将员工先按照性别进行分组,再按照地区进行分组
Map<String, Map<String, List<Person>>> sexAndAreaGroup =
personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getAddress)));
System.out.println("sexAndAreaGroup = " + sexAndAreaGroup);
}


/**
* 统计(count/averaging)
* Collectors提供了一系列用于数据统计的静态方法:
* 计数:count
* 平均值:averagingInt、averagingLong、averagingDouble
* 最值:maxBy、minBy
* 求和:summingInt、summingLong、summingDouble
* 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
*/
public static void test08() {
// 案例:统计员工人数、平均工资、工资总额、最高工资。
long count = personList.stream().count();
System.out.println("count = " + count);

// 平均工资
Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
System.out.println("average = " + average);

// 工资总和
Double sum = personList.stream().collect(Collectors.summingDouble(Person::getSalary));
System.out.println("sum = " + sum);

// 最高工资
Optional<Person> maxSalary = personList.stream().max(Comparator.comparing(Person::getSalary));
System.out.println("maxSalary.get() = " + maxSalary.get().getSalary());
}


/**
* 收集(collect)
* collect,收集,可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,
* 最终可以是收集成一个值也可以收集成一个新的集合。
* collect主要依赖java.util.stream.Collectors类内置的静态方法。
*/

/**
* 归集(toList/toSet/toMap)
* 因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。
* toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。
*/
public static void test07() {

List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
// 取出所有的奇数
List<Integer> list1 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
System.out.println("list1 = " + list1);
Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
System.out.println("set = " + set);

// 找出薪资大于8000的人员
Map<String, Person> map = personList.stream().filter(p -> p.getSalary() > 8000)
.collect(Collectors.toMap(Person::getName, p -> p));
System.out.println("map = " + map);


}


/**
* 归约(reduce)
* 归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。
*/
public static void test06() {
// 案例一:求Integer集合的元素之和、乘积和最大值。
List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
// 方法1
Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
// 方法2
Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
// 方法3
Integer sum3 = list.stream().reduce(0, Integer::sum);
System.out.println("列表求和 = " + sum.get());
System.out.println("sum2.get() = " + sum2.get());
System.out.println("sum3 = " + sum3);


// 列表的乘积
Optional<Integer> product = list.stream().reduce((x, y) -> x * y);
System.out.println("product.get() = " + product.get());

// 返回最大值
Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
System.out.println("max.get() = " + max.get());
// 直接使用max函数求最大值
Optional<Integer> max1 = list.stream().max(Integer::compareTo);
System.out.println("max1.get() = " + max1.get());
// 使用reduce求解最大值
Integer max2 = list.stream().reduce(1, Integer::max);
System.out.println("max2 = " + max2);


// 案例二:求所有员工的工资之和、最高工资。
Optional<Integer> salarySum = personList.stream().map(Person::getSalary) // 取出所有的工资
.reduce(Integer::sum);
System.out.println("salarySum.get() = " + salarySum.get());
// 方法2:
// Integer salarySum2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);
// System.out.println("salarySum2 = " + salarySum2);
// 方法3:
// 求工资之和方式3:
// Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);


// 求出工资的最大值
Optional<Integer> max3 = personList.stream().map(Person::getSalary).max(Integer::compareTo);
System.out.println("max3.get() = " + max3.get());


// 使用reduce求解最大值
// 求最高工资方式1:
// Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
// Integer::max);
// // 求最高工资方式2:
// Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
// (max11, max22) -> max11 > max22 ? max11 : max22);
//
// System.out.println("最高工资:" + maxSalary + "," + maxSalary2);
}


/**
* 映射(map/flatMap)
* 映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap:
* map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
* flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
*/
public static void test05() {
// 案例一:英文字符串数组的元素全部改为大写。
String[] strArr = {"abcd", "bcdd", "defde", "fTr"};
List<String> stringList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
System.out.println("stringList = " + stringList);

// 整数数组每个元素+3。
List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
List<Integer> integerList = intList.stream().map(x -> x + 3).collect(Collectors.toList());
System.out.println("integerList = " + integerList);


// 案例二:将员工的薪资全部增加1000
List<Integer> newPersonList = personList.stream().map(person -> person.getSalary() + 1000)
.collect(Collectors.toList());
System.out.println("newPersonList = " + newPersonList);


// 不改变原来员工集合的方式
List<Person> personListNew = personList.stream().map(person -> {
Person personNew = new Person(person.getName(), 0, 0, null, null);
personNew.setSalary(person.getSalary() + 10000);
return personNew;
}).collect(Collectors.toList());
System.out.println("一次改动前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary());
System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());


// 改变原来员工集合的方式
List<Person> personListNew2 = personList.stream().map(person -> {
person.setSalary(person.getSalary() + 10000);
return person;
}).collect(Collectors.toList());
System.out.println("二次改动前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary());
System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary());

// 案例三:将两个字符数组合并成一个新的字符数组
List<String> list4 = Arrays.asList("m,k,l,a", "1,3,5,7");
List<String> listNew = list4.stream().flatMap(s -> {
String[] split = s.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
System.out.println("处理前的集合: " + list4);
System.out.println("处理后的集合: " + listNew);
}


/**
* 3.聚合(max/min/count)
* max、min、count这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。
* Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。
*/
public static void test04() {
// 案例一:获取String集合中最长的元素。
List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
Optional<String> max = list.stream().max(Comparator.comparing(String::length));
System.out.println("max.get() = " + max.get());


// 案例二:获取Integer集合中的最大值。
List<Integer> list1 = Arrays.asList(7, 6, 9, 4, 11, 6);
// 自然排序(大到小)
Optional<Integer> max1 = list1.stream().max(Integer::compareTo);
// 自定义排序(大到小)
Optional<Integer> max2 = list1.stream().max(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
// 自然排序。自定义排序的最大值
System.out.println("max1.get() = " + max1.get());
System.out.println("max2.get() = " + max2.get());

// 案例三:获取员工工资最高的人。
// 方法1:
// Optional<Person> person = personList.stream().max(new Comparator<Person>() {
// @Override
// public int compare(Person o1, Person o2) {
// return o1.getSalary() - o2.getSalary();
// }
// });
// 方法2
Optional<Person> person = personList.stream().max(Comparator.comparing(Person::getSalary));
System.out.println("工资的最大值 = " + person.get().getSalary());

// 案例四:计算Integer集合中大于6的元素的个数。
List<Integer> list2 = Arrays.asList(7, 6, 4, 8, 2, 11, 9);
long count = list2.stream().filter(x -> x > 6).count();
System.out.println("count = " + count);
}


/**
* 2.筛选(filter)
* 筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作。
*/
public static void test03() {
List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
// 筛选出Integer集合中大于7的元素,并打印出来
list.stream().filter(x -> x > 7).forEach(System.out::println);

// 案例二: 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集)
List<String> newList = personList.stream()
.filter(person -> person.getSalary() > 8000) // 过滤出工资大于8000的
.map(person -> person.getName()) // 取出所有person的name属性
.collect(Collectors.toList()); // 将新的流转为list集合
System.out.println("工资大于8000的员工姓名: " + newList);
}


/**
* 1.遍历/匹配(foreach/find/match)
* Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常简单。
*/
public static void test02() {
List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
// 输出符合条件的元素
// 1.输出所有大于6的元素
list.stream().filter(x -> x > 6).forEach(System.out::println);
// 2.获取第一个大于6的元素
Optional<Integer> first = list.stream().filter(x -> x > 6).findFirst();
System.out.println("first.get() = " + first.get());
// 3.获取任意一个大于6的元素
Optional<Integer> any = list.stream().filter(x -> x > 6).findAny();
System.out.println("any.get() = " + any.get());
// 4.判断list中是否存在大于6的元素
boolean isMatch = list.stream().anyMatch(x -> x > 6);
System.out.println("isMatch = " + isMatch);
}


// 集合创建Stream
// 使用数组创建流
public static void test01() {
List<String> list = Arrays.asList("a", "b", "c");
// 创建一个顺序流
Stream<String> stream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();

// 数组创建
int[] arr = {1, 2, 3, 4, 5};
IntStream stream1 = Arrays.stream(arr);

// 使用Stream的静态方法:of,iterate,generate
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream3 = Stream.iterate(0, x -> x + 3).limit(4);
stream3.forEach(System.out::println);

//
Stream<Double> stream4 = Stream.generate(Math::random).limit(3);
stream4.forEach(System.out::println);
}


}

 

比如现在有个Student对象,需要使用Student的name字段构造user对象,那么一般的写法就是

public User xxxFunction(Student student){ User user = new User(); if(student!=null){ user.setUsername(student.getName()); } return user; } 使用Optional的写法

public User xxxFunction(Student student){ User user = new User(); Optional.ofNullable(student).ifPresent(a->user.setUsername(a.getName())); return user; }

简单说明下上述用到Optional的方法。 ofNullable(T value)会构造返回一个Optional<T>的对象,该方法允许value为null时,Optional类封装的value值为null。 ifPresent(Consumer<? super T> consumer) ,它接受一个有入参但无返回值的函数,此时该函数的入参对象即Optional中封装的value值。查看ifPresent源码可知,如下:

public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }

从上述可以知道,只有当value不为null时,才执行ifPresent里面的函数。那么上述Optional的操作就可以解释通了,如果student不为null,设置user的名称为student的name值。

如果需要给user在student为null时抛出异常,通常如下

public User xxxFunction(Student student){ User user = new User(); if(student==null) { //可以为其他用户封装的异常类 throw new NullPointerException("student不允许为空"); } user.setUserName(student.getName());

return user;

} Optional写法

 

public User xxxFunction(Student student){ User user = new User(); user.setUserName(Optional.ofNullable(student).orElseThrow(()->new NullPointerException("student类不能为空")).getName()); return user; }

在实际的业务中,我觉得Optional实际的作用场景,对于某两个值二选一的时候就很适合,比如如下

还是拿User的username举例,如果A有值,取A,A没值取B。

public void say(String A,String B){
  User user = new User();
   user.setUserName(Optional.ofNullable(A).orElse(B));
}
如果在途中需要对A,B进行操作,比如加密等,可如下(这里拿字符串拼接举例)
public void say(String A,String B){
  User user = new User();
   user.setUserName(Optional.ofNullable(A).map(a->a+"end").orElseGet(()->B+"end"));
}
此处需要注意map的用法,map会遍历Optional的value,此处只有个A的String类型对象,会返回该A对象,然后我在此拼接字符串,特别注意,如果A为null,此处不会进行map里面的操作。理由是查看map源码可知
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
   Objects.requireNonNull(mapper);
   if (!isPresent())
       return empty();
   else {
       return Optional.ofNullable(mapper.apply(value));
  }
}

其实Otional就跟大多数lamda表达式一样,在某些程度上简化了代码,但是会提高一点代码的学习成本,实际上是否使用Optional还是得根据业务而定。

标签:Collectors,stream,System,笔记,学习,collect,println,out
From: https://www.cnblogs.com/ssy0113/p/16903851.html

相关文章