为了账号安全,请及时绑定邮箱和手机立即绑定

Java Stream用法总结(二)

标签:
Java

紧接上一篇《Java Stream 用法总结(一)

流的操作类型

流的操作类型主要分为两种

1.中间操作:
一个流可以后面跟随零个或多个中间操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的,仅仅调用到这类方法,并没有真正开始流的遍历,真正的遍历需等到终端操作时,常见的中间操作有下面即将介绍的filter、map等

2.终端操作:
一个流有且只能有一个终端操作,当这个操作执行后,流就被关闭了,无法再被操作,因此一个流只能被遍历一次,若想在遍历需要通过源数据在生成流。终端操作的执行,才会真正开始流的遍历。如下面即将介绍的count、collect等

Optional类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

流使用

filter筛选

 List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);  
 Stream<Integer> stream = integerList.stream().filter(i -> i > 3);

通过使用filter方法进行条件筛选,filter的方法参数为一个条件

distinct去除重复元素

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);  
Stream<Integer> stream = integerList.stream().distinct();  

通过distinct方法快速去除重复的元素

limit返回指定流个数

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);  
 Stream<Integer> stream = integerList.stream().limit(3);  

通过limit方法指定返回流的个数,limit的参数值必须>=0,否则将会抛出异常

forEach

Stream 提供了新的方法 ‘forEach’ 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数:

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

map

map 方法用于映射每个元素到对应的结果,以下代码片段使用 map 输出了元素对应的平方数

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter

filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");// 获取空字符串的数量
long count = strings.stream().filter(string -> string.isEmpty()).count();

limit

limit 方法用于获取指定数量的流。以下代码片段使用 limit 方法打印出 10 条数据

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

sorted

sorted 方法用于对流进行排序。以下代码片段使用 sorted 方法对输出的 10 个随机数进行排序

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

并行(parallel)程序

parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");// 获取空字符串的数量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

Collectors

Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

统计

另外,一些产生统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上,它们可以用来产生类似如下的统计结果。

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); 
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics(); 
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());

Stream Api用法

  1. sorted():它使用自然顺序对流中的元素进行排序。元素类必须实现Comparable接口。

  2. sorted(Comparator<? super T> comparator):这里我们使用lambda表达式创建一个Comparator实例。我们可以按升序和降序对流元素进行排序。

  3. 自然顺序对列表进行排序:

list.stream().sorted() 
//List:根据Student的name排序
List<Student> studentList = new ArrayList<>();
List<Student> stuList = studentList.stream().sorted().collect(Collectors.toList());
//List:根据Student的age排序
List<Student> studentList = new ArrayList<>();
List<Student> stuList2 = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
//Set: 根据Student的name排序
Set<Student> studentSet = new HashSet<>();
studentSet.stream().sorted().forEach(s -> System.out.println(s));
//Set: 根据Student的age排序
Set<Student> studentSet = new HashSet<>();
studentSet.stream().sorted(Comparator.comparing(Student::getAge)).forEach(s -> System.out.println(s));
//Map: 根据map的key进行排序
Map<Integer, String> stringMap = new HashMap<>();
stringMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
        .forEach(e -> System.out.println("key: " + e.getKey() +" ,value: " + e.getValue()));
//Map: 根据map的value进行排序
Map<Integer, String> stringMap = new HashMap<>();
stringMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
        .forEach(e -> System.out.println("key: " + e.getKey() + " ,value: " + e.getValue()));
//Map: 对map的Value的Student进行排序
Map<Integer, Student> studentMap = new HashMap<>();
studentMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(e -> {
        Integer key = e.getKey();
        Student stu = e.getValue();
        System.out.println("key: " + key + " ,value: (" + stu.getId() + ", " + stu.getName() + ", " + stu.getAge()+")");
});
//Map: 先对Map的Value的Student排序,然后在对Student里面的age排序
Map<Integer, Student> studentMap = new HashMap<>();
studentMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue, Comparator.comparing(Student::getAge))).forEach(e -> {
        Integer key = e.getKey();
        Student stu = e.getValue();
        System.out.println("key: " + key + " ,value: (" + stu.getId() + ", " + stu.getName() + ", " + stu.getAge()+")");
        });
  1. 反转自然顺序,Comparator提供reverseOrder()方法
list.stream().sorted(Comparator.reverseOrder()) 
//List:根据Student的name逆序排序
List<Student> studentList = new ArrayList<>();
List<Student> stuList1 = studentList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
//Set: 根据Student的name逆序排序
Set<Student> studentSet = new HashSet<>();
studentSet.stream().sorted(Comparator.reverseOrder()).forEach(s -> System.out.println(s));
//Map: 对map的Value的Student进行逆序排序
Set<Student> studentSet = new HashSet<>();
studentMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder())).forEach(e -> {
        Integer key = e.getKey();
        Student stu = e.getValue();
        System.out.println("key: " + key + " ,value: (" + stu.getId() + ", " + stu.getName() + ", " + stu.getAge()+")");
        });
//Map: 先对Map的Value的Student排序,然后在对Student里面的age逆序排序
Map<Integer, Student> studentMap = new HashMap<>();
studentMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue, Comparator.comparing(Student::getAge, Comparator.reverseOrder()))).forEach(e -> {
        Integer key = e.getKey();
        Student stu = e.getValue();
        System.out.println("key: " + key + " ,value: (" + stu.getId() + ", " + stu.getName() + ", " + stu.getAge()+")");
        });
  1. 使用Comparator对列表进行排序
list.stream().sorted(Comparator.comparing(Student::getAge)) 
  1. 使用Comparator提供reversed()方法实现逆序输出
list.stream().sorted(Comparator.comparing(Student::getAge).reversed()) 
//List:根据Student的age逆序排序
List<Student> studentList = new ArrayList<>();
List<Student> stuList3 = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
//Set: 根据Student的age逆序排序
Set<Student> studentSet = new HashSet<>();
studentSet.stream().sorted(Comparator.comparing(Student::getAge).reversed()).forEach(s -> System.out.println(s));
  1. 利用Stream将List转化为map,并根据User的属性分组
Map<String, List<User>> map = list.stream().collect(Collectors.groupingBy(User::getCity));
  1. 利用Stream将List转化为数组
// 将 List 元素存储到数组中
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
  1. 利用Stream将int arr[]数组转化为list
// 将数组元素 存储到 List 中
int[] arr = {1, 2, 3, 4, 5};
List<Integer> integerList = IntStream.of(arr).boxed().collect(Collectors.toList());
  1. 利用Stream遍历map
map.forEach((key, value) -> System.out.println(key + " : " + value));  //遍历map
  1. 利用Stream统计String[] arrStr数组中各个元素出现的次数,以Map形式返回
Map<String, Integer> map = Stream.of(arrStr).collect(Collectors.toMap(key -> key, key -> 1, Integer :: sum));
map.forEach((key , value) -> System.out.println(key + " : " + value));
  1. 利用Stream遍历数组numResult
Arrays.stream(numResult).forEach(s -> System.out.print(s + " "));
  1. 利用Stream实现排序
 /**
     * 使用stream实现排序
     * @param arr
     * @return
     */
    public static int[] arrSortByStream(int[] arr){
        arr = IntStream.of(arr)
                .boxed()
                .sorted(Comparator.naturalOrder())
                .mapToInt(Integer :: intValue)
                .toArray();
        return arr;
    }
  1. 利用Stream根据用户的手机号码去重
List<User> userList = new ArrayList<>();
List<User> userListNew = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User :: getMobile))), ArrayList::new));
  1. 利用Stream求List中的最大值,最小值,总和
List<Integer> integerList = new ArrayList<>();
//最大值
Integer maxValue = integerList.stream().reduce(integerList.get(0), Integer::max);
//最小值
Integer minValue = integerList.stream().reduce(integerList.get(0), Integer::min);
//总和
Integer sumValue = integerList.stream().reduce(integerList.get(0), Integer::sum);
  1. 利用Stream求List中的最大值,最小值,总和
List<Car> carList = new ArrayList<>();
carList.add(new Car("迈巴赫", "德国", 688.80, 655.00, 33.80));
carList.add(new Car("兰博基尼", "意大利", 1234.44, 1200.00, 34.44));
//总和
Double prePriceSUm = carList.stream().mapToDouble(Car::getPrePrice).sum();
//最大值
OptionalDouble prePriceMax = carList.stream().mapToDouble(Car::getPrePrice).max();
//最大值
OptionalDouble discountsMax = carList.stream().mapToDouble(Car::getDiscounts).max();
  1. collect:聚合,可以用于GroudBy按指定字段分类,也可以用于返回列表或者拼凑字符串
 //按成绩进行归集
Map<Double, List<UserPo>> groupByScoreMap = userPoList.stream().filter(u -> null != u.getScore()).collect(Collectors.groupingBy(UserPo::getScore));
for(Map.Entry<Double, List<UserPo>> entry : groupByScoreMap.entrySet()){
    System.out.println("成绩: " + entry.getKey() + " 人数: " + entry.getValue().size());
}
 //取出所有学生的成绩
List<Double> scoreList = userPoList.stream().map(u -> u.getScore()).collect(Collectors.toList());
//将学生姓名集合串成字符串,用逗号隔开
String nameString = userPoList.stream().map(u -> u.getName()).collect(Collectors.joining(","));
  1. filter:过滤,就是过滤器,符合条件的通过,不符合条件的过滤掉
//筛选出成绩不为空的学生人数
Long count = userPoList.stream().filter(p -> null != p.getScore()).count();
  1. statistics:统计,可以统计中位数,平均值,最大最小值
DoubleSummaryStatistics statistics = sortList.stream().mapToDouble(u -> u.getScore()).summaryStatistics();  //sortList 中不能有null值
System.out.println("列表中最大的数 : " + statistics.getMax());
System.out.println("列表中最小的数 : " + statistics.getMin());
System.out.println("所有数之和 : " + statistics.getSum());
System.out.println("平均数 : " + statistics.getAverage());
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
  1. 利用Stream创建List集合
 //利用Stream创建List集合
 List<String> colors = Stream.of("blue", "red", "yellow").collect(toList());
  1. 利用Stream去重
List<String> stringList = new ArrayList<>();
//去重
ArrayList<String> phoneNewList = stringList.stream().collect(Collectors.collectingAndThen(
     Collectors.toCollection(() -> new TreeSet<String>(Comparator.comparing(String::toString))), ArrayList::new));
  1. 获取实体类列表的某一列字段数据
//获取User实体类的id数据
List<User> list = new ArrayList<>();
List<String> jdk8Ids = list.stream().map(User::getId).collect(Collectors.toList());
  1. 使用filter过滤数据
//获取List<User>中年龄大于21的人
List<User> list = new ArrayList<>();
List<User> userList = list.stream().filter(User->User.getAge() > 21).collect(Collectors.toList());
//去掉List<String>中的空字符串
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
//使用 filter 方法过滤出空字符串,并返回空字符串的个数
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");// 获取空字符串的数量
long count = strings.stream().filter(string -> string.isEmpty()).count();
//过滤出大于3的数据
 List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);  
 Stream<Integer> stream = integerList.stream().filter(i -> i > 3);
  1. 使用Collectors.groupingBy() 分组数据 - 按照部门返回不同部门下的人员的数据
List<User> list = new ArrayList<>();
Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getDeptName));
  1. limit用法
//forEach 输出了10个随机数
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);  
 Stream<Integer> stream = integerList.stream().limit(3);  
  1. 使用 map 输出了元素对应的平方数:
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
  1. Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
  1. stream().reduce()求最大最小值
List<BigDecimal> list = new ArrayList<>(Arrays.asList(new BigDecimal("1"), new BigDecimal("2")));
BigDecimal max = list.stream().reduce(list.get(0), BigDecimal::max);
BigDecimal min = list.stream().reduce(list.get(0), BigDecimal::min);
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
Integer max = list.stream().reduce(list.get(0), Integer::max);
Integer min = list.stream().reduce(list.get(0), Integer::min);
List<Double> list = new ArrayList<>(Arrays.asList(1d, 2d));
Double max = list.stream().reduce(list.get(0), Double::max);
Double min = list.stream().reduce(list.get(0), Double::min);
  1. Collectors.summarizingInt(), Collectors.summarizingLong(), Collectors.summarizingDouble()求最大值最小值
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
IntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(x -> x));
Integer max = intSummaryStatistics.getMax();
Integer min = intSummaryStatistics.getMin();
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L));
LongSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingLong(x -> x));
Long max = summaryStatistics.getMax();
Long min = summaryStatistics.getMin();
List<Double> list = new ArrayList<>(Arrays.asList(1d, 2d));
DoubleSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingDouble(x -> x));
Double max = summaryStatistics.getMax();
Double min = summaryStatistics.getMin();
  1. stream().max()或stream().min()实现求最大最小值
 List<BigDecimal> list = new ArrayList<>(Arrays.asList(new BigDecimal("1"), new BigDecimal("2")));
BigDecimal max = list.stream().max(Comparator.comparing(x -> x)).orElse(null);
BigDecimal min = list.stream().min(Comparator.comparing(x -> x)).orElse(null);
//Long, Double用法类似
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
Integer max = list.stream().max(Comparator.comparing(x -> x)).orElse(null);
Integer min = list.stream().min(Comparator.comparing(x -> x)).orElse(null);
  1. 使用stream().distinct()方法去除列表集合中的重复元素
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);  
Stream<Integer> stream = integerList.stream().distinct();  

用法示例1

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @ClassName UserListDemo
 * @Desc TODO
 * @Author diandian
 * @Date 2022/7/18 11:41
 **/
public class UserListDemo {
    private static List<User> getList() {
        User user = new User();
        user.setId(getUUID());
        user.setName("张三");
        user.setAge(20);
        user.setDeptName("开发部");
        List<User> list = new ArrayList();
        list.add(user);

        User user2 = new User();
        user2.setId(getUUID());
        user2.setName("李四");
        user2.setAge(21);
        user2.setDeptName("财务部");
        list.add(user2);

        User user3 = new User();
        user3.setId(getUUID());
        user3.setName("王五");
        user3.setAge(22);
        user3.setDeptName("运维部");
        list.add(user3);

        User user4 = new User();
        user4.setId(getUUID());
        user4.setName("赵六");
        user4.setAge(22);
        user4.setDeptName("运维部");
        list.add(user4);
        return list;
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return uuid;
    }

    public static void main(String[] args) {
        //TODO jdk1.7  获取User 实体的Id数据
        //给List赋值
        List<User> list = getList();
        //新的IdList
        List<String> Ids = new ArrayList<>();
        for (User user: list) {
            Ids.add(user.getId());
        }
        System.out.println(JSON.toJSON(Ids));

        //TODO jdk1.8  获取User 实体的Id数据
        List<String> jdk8Ids = list.stream().map(User::getId).collect(Collectors.toList());
        System.out.println("JDK8的获取数据==="+ JSON.toJSON(jdk8Ids));


        //TODO jdk1.7 获取List数据中年龄大于等于21的人
        //新的list
        List<User> newList= new ArrayList<>();
        for (User user: list) {
            if (user.getAge() >= 21){
                newList.add(user);
            }
        }
        System.out.println("JDK7的获取数据==="+JSON.toJSON(newList));

        //TODO jdk1.8 获取List数据中年龄大于等于21的人
        List<User> newListJdk8 = list.stream().filter(User->User.getAge() > 21).collect(Collectors.toList());
        System.out.println("JDK8的获取数据==="+JSON.toJSON(newListJdk8));

        //TODO jdk1.8 按照部门返回不同部门下的人员的数据
        Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getDeptName));
        System.out.println("JDK8的获取数据==="+JSON.toJSON(collect));
    }

}

用法示例2

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName StreamDeno2
 * @Desc TODO
 * @Author diandian
 * @Date 2022/7/18 14:40
 **/
public class StreamDemo2 {
    public static void main(String args[]){
        System.out.println("使用 Java 7: ");

        // 计算空字符串
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        System.out.println("列表: " +strings);
        long count = getCountEmptyStringUsingJava7(strings);
        System.out.println("空字符数量为: " + count);

        count = getCountLength3UsingJava7(strings);
        System.out.println("字符串长度为 3 的数量为: " + count);

        // 删除空字符串
        List<String> filtered = deleteEmptyStringsUsingJava7(strings);
        System.out.println("筛选后的列表: " + filtered);

        // 删除空字符串,并使用逗号把它们合并起来
        String mergedString = getMergedStringUsingJava7(strings,", ");
        System.out.println("合并字符串: " + mergedString);
        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

        // 获取列表元素平方数
        List<Integer> squaresList = getSquares(numbers);
        System.out.println("平方数列表: " + squaresList);
        List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);

        System.out.println("列表: " +integers);
        System.out.println("列表中最大的数 : " + getMax(integers));
        System.out.println("列表中最小的数 : " + getMin(integers));
        System.out.println("所有数之和 : " + getSum(integers));
        System.out.println("平均数 : " + getAverage(integers));
        System.out.println("随机数: ");

        // 输出10个随机数
        Random random = new Random();
        for(int i=0; i < 10; i++){
            System.out.println(random.nextInt());
        }


        System.out.println("使用 Java 8: ");
        System.out.println("列表: " +strings);

        count = strings.stream().filter(string->string.isEmpty()).count();
        System.out.println("空字符串数量为: " + count);

        count = strings.stream().filter(string -> string.length() == 3).count();
        System.out.println("字符串长度为 3 的数量为: " + count);

        filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());
        System.out.println("筛选后的列表: " + filtered);

        mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
        System.out.println("合并字符串: " + mergedString);

        squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());
        System.out.println("Squares List: " + squaresList);
        System.out.println("列表: " +integers);

        IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();
        System.out.println("列表中最大的数 : " + stats.getMax());
        System.out.println("列表中最小的数 : " + stats.getMin());
        System.out.println("所有数之和 : " + stats.getSum());
        System.out.println("平均数 : " + stats.getAverage());
        System.out.println("随机数: ");

        random.ints().limit(10).sorted().forEach(System.out::println);

        // 并行处理
        count = strings.parallelStream().filter(string -> string.isEmpty()).count();
        System.out.println("空字符串的数量为: " + count);
    }

    private static int getCountEmptyStringUsingJava7(List<String> strings){
        int count = 0;

        for(String string: strings){

            if(string.isEmpty()){
                count++;
            }
        }
        return count;
    }

    private static int getCountLength3UsingJava7(List<String> strings){
        int count = 0;

        for(String string: strings){

            if(string.length() == 3){
                count++;
            }
        }
        return count;
    }

    private static List<String> deleteEmptyStringsUsingJava7(List<String> strings){
        List<String> filteredList = new ArrayList<String>();

        for(String string: strings){

            if(!string.isEmpty()){
                filteredList.add(string);
            }
        }
        return filteredList;
    }

    private static String getMergedStringUsingJava7(List<String> strings, String separator){
        StringBuilder stringBuilder = new StringBuilder();

        for(String string: strings){

            if(!string.isEmpty()){
                stringBuilder.append(string);
                stringBuilder.append(separator);
            }
        }
        String mergedString = stringBuilder.toString();
        return mergedString.substring(0, mergedString.length()-2);
    }

    private static List<Integer> getSquares(List<Integer> numbers){
        List<Integer> squaresList = new ArrayList<Integer>();

        for(Integer number: numbers){
            Integer square = new Integer(number.intValue() * number.intValue());

            if(!squaresList.contains(square)){
                squaresList.add(square);
            }
        }
        return squaresList;
    }

    private static int getMax(List<Integer> numbers){
        int max = numbers.get(0);

        for(int i=1;i < numbers.size();i++){

            Integer number = numbers.get(i);

            if(number.intValue() > max){
                max = number.intValue();
            }
        }
        return max;
    }

    private static int getMin(List<Integer> numbers){
        int min = numbers.get(0);

        for(int i=1;i < numbers.size();i++){
            Integer number = numbers.get(i);

            if(number.intValue() < min){
                min = number.intValue();
            }
        }
        return min;
    }

    private static int getSum(List numbers){
        int sum = (int)(numbers.get(0));

        for(int i=1;i < numbers.size();i++){
            sum += (int)numbers.get(i);
        }
        return sum;
    }

    private static int getAverage(List<Integer> numbers){
        return getSum(numbers) / numbers.size();
    }
}

用法示例3

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName FilterTest
 * @Desc filter:过滤,就是过滤器,符合条件的通过,不符合条件的过滤掉
 * @Author diandian
 * @Date 2022/6/27 10:05
 **/
public class FilterTest {

    public static void main(String[] args) {
        List<UserPo> userPoList = new ArrayList<>();
        userPoList.add(new UserPo("xiaoming", 90.0));
        userPoList.add(new UserPo("xiaoliu", 80.0));
        userPoList.add(new UserPo("xiaohua", 71.0));
        userPoList.add(new UserPo("huahua", null));
        userPoList.add(new UserPo("mengmeng", 98.0));
        userPoList.add(new UserPo("lanlan", 98.0));
        userPoList.add(new UserPo("shanshan", null));
        userPoList.add(new UserPo("beibei", 50.0));
        userPoList.add(new UserPo("duoduo", 62.0));
        userPoList.add(new UserPo("xiaozhang", 62.0));
        userPoList.add(new UserPo("niuniu", 42.0));
        userPoList.add(new UserPo("fangfang", 72.0));
        userPoList.add(new UserPo("tingting", 68.0));


        //筛选出成绩不为空的学生人数
        Long count = userPoList.stream().filter(p -> null != p.getScore()).count();
        System.out.println("成绩不为空的人数:" + count);

        //TODO map:映射,他将原集合映射成为新的集合,在VO、PO处理的过程中较常见。
        //取出所有学生的成绩
        List<Double> scoreList = userPoList.stream().map(u -> u.getScore()).collect(Collectors.toList());
        scoreList.stream().forEach(s -> System.out.println(s));

        //将学生姓名集合串成字符串,用逗号隔开
        String nameString = userPoList.stream().map(u -> u.getName()).collect(Collectors.joining(","));
        System.out.println("\n学生姓名集合:" + nameString);

        //TODO sorted:排序,可以根据指定的字段进行排序
        //按学生成绩逆序排序,正序则不需要加.reversed()
        List<UserPo> sortList = userPoList.stream().filter(u -> null != u.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());
        System.out.println("\n按学生成绩排序后:");
        sortList.stream().forEach(u -> System.out.println(u));


        //TODO forEach:这个应该是最常用的,也就是为每一个元素进行自定义操作
        // 学生成绩太差了,及格率太低,给每个学生加10分,放个水
        System.out.println("\n每个学生成绩加10分:");
        sortList.stream().forEach(u -> u.setScore(u.getScore() + 10));


        //TODO collect:聚合,可以用于GroudBy按指定字段分类,也可以用于返回列表或者拼凑字符串
        //按成绩进行归集
        Map<Double, List<UserPo>> groupByScoreMap = userPoList.stream().filter(u -> null != u.getScore()).collect(Collectors.groupingBy(UserPo::getScore));
        for(Map.Entry<Double, List<UserPo>> entry : groupByScoreMap.entrySet()){
            System.out.println("成绩: " + entry.getKey() + " 人数: " + entry.getValue().size());
        }
        System.out.println("\n--------------------------------\n");

        //TODO statistics:统计,可以统计中位数,平均值,最大最小值
        DoubleSummaryStatistics statistics = sortList.stream().mapToDouble(u -> u.getScore()).summaryStatistics();
        System.out.println("列表中最大的数 : " + statistics.getMax());
        System.out.println("列表中最小的数 : " + statistics.getMin());
        System.out.println("所有数之和 : " + statistics.getSum());
        System.out.println("平均数 : " + statistics.getAverage());


        //TODO parallelStream:并行流,可以利用多线程进行流的操作,提升效率。但是其不具备线程传播性,因此使用时需要充分评估是否需要用并行流操作
        // 并行流 使用
        count = userPoList.parallelStream().filter(p -> null != p.getScore()).count();
        System.out.println("并行流处理参加考试的学生人数:" + count);

    }
}

用法示例4

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.*;

/**
 * @ClassName UseStream
 * @Desc TODO
 * @Author diandian
 * @Date 2022/11/11 21:38
 **/
public class UseStream {

    /**
     * 流的用法
     * 1.filter筛选:通过使用filter方法进行条件筛选,filter的方法参数为一个条件
     * 2.distinct去除重复元素:通过distinct方法快速去除重复的元素
     * 3.limit返回指定流个数: 通过limit方法指定返回流的个数,limit的参数值必须>=0,否则将会抛出异常
     * 4.skip跳过流中的元素:通过skip方法跳过流中的元素,本例子跳过前两个元素,所以打印结果为2,3,4,5,skip的参数值必须>=0,否则将会抛出异常
     * 5.5.map流映射:所谓流映射就是将接受的元素映射成另外一个元素
     * 6.flatMap流转换:将一个流中的每个值都转换为另一个流
     */
    private void UserStream(){
        List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
        //1.通过使用filter方法进行条件筛选,filter的方法参数为一个条件
        Stream<Integer> stream = integerList.stream().filter(i -> i > 3);

        //2.distinct去除重复元素:通过distinct方法快速去除重复的元素
        Stream<Integer> stream1 = integerList.stream().distinct();

        //3.limit返回指定流个数:通过limit方法指定返回流的个数,limit的参数值必须>=0,否则将会抛出异常
        Stream<Integer> stream2 = integerList.stream().limit(3);

        //4.skip跳过流中的元素:通过skip方法跳过流中的元素,本例子跳过前两个元素,所以打印结果为2,3,4,5,skip的参数值必须>=0,否则将会抛出异常
        Stream<Integer> stream3 = integerList.stream().skip(2);

        //5.map流映射:所谓流映射就是将接受的元素映射成另外一个元素,本例通过map方法可以完成映射,该例子完成中String -> Integer的映射
        List<String> stringList = Arrays.asList("Java 8", "Lambdas",  "In", "Action");
        Stream<Integer> stream4 = stringList.stream().map(String::length);

        //6.flatMap流转换:将一个流中的每个值都转换为另一个流,本例中:map(w -> w.split(" "))的返回值为Stream<String[]>,我们想获取Stream<String>,可以通过flatMap方法完成Stream ->Stream的转换
        List<String> wordList = Arrays.asList("Hello", "World");
        List<String> strList = wordList.stream()
                .map(w -> w.split(" "))
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toList());
    }


    /**
     * 元素匹配: 提供了三种匹配方式
     * 1.allMatch匹配所有:通过allMatch方法实现
     * 2.anyMatch匹配其中一个
     * 3.noneMatch全部不匹配:通过noneMatch方法实现
     */
    private void streamMatch(){
        //1.allMatch匹配所有:通过allMatch方法实现
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6);
        if(integerList.stream().allMatch(i -> i > 3)){
            System.out.println("值都大于3");
        }

        //2.anyMatch匹配其中一个
        if(integerList.stream().anyMatch(i -> i > 3)){
            System.out.println("存在大于3的值");
        }
        //等同于,存在大于3的值则打印,java8中通过anyMatch方法实现这个功能
        for(Integer i : integerList){
            if(i > 3){
                System.out.println("存在大于3的值");
                break;
            }
        }

        //3.noneMatch全部不匹配:通过noneMatch方法实现
        if(integerList.stream().noneMatch(i -> i > 3)){
            System.out.println("值都小于3");
        }
    }

    /**
     * 终端操作
     * 1.统计流中元素个数
     * (1) 通过count
     * (2) 通过counting
     * 2.查找
     * (1) findFirst查找第一个
     * (2) findAny随机查找一个
     * 3.reduce将流中的元素组合起来: reduce接受两个参数,一个初始值这里是0,一个BinaryOperator<T> accumulator来将两个元素结合起来产生一个新值,另外reduce方法还有一个没有初始化值的重载方法
     * 4.获取流中最小最大值
     * (1)通过min/max获取最小最大值:min获取流中最小值,max获取流中最大值,方法参数为Comparator<? super T> comparator
     * (2)通过minBy/maxBy获取最小最大值:minBy获取流中最小值,maxBy获取流中最大值,方法参数为Comparator<? super T> comparator
     * (3)通过reduce获取最小最大值
     * 5.求和
     * (1) 通过summingInt: 如果数据类型为double、long,则通过summingDouble、summingLong方法进行求和
     * (2)通过reduce
     * (3)通过sum
     * 6.通过averagingInt求平均值:如果数据类型为double、long,则通过averagingDouble、averagingLong方法进行求平均
     * 7.通过summarizingInt同时求总和、平均值、最大值、最小值: 如果数据类型为double、long,则通过summarizingDouble、summarizingLong方法
     * 8.通过foreach进行元素遍历
     * 9.返回集合
     * 10.通过joining拼接流中的元素
     * 11.通过groupingBy进行分组:在collect方法中传入groupingBy进行分组,其中groupingBy的方法参数为分类函数。还可以通过嵌套使用groupingBy进行多级分类
     * 12.通过partitioningBy进行分区:分区是特殊的分组,它分类依据是true和false,所以返回的结果最多可以分为两组
     */
    private void UserStream2(){
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
        //1.统计流中元素个数
        //(1)通过count:通过使用count方法统计出流中元素个数
        Long count = integerList.stream().count();
        //(2)通过counting:这种统计元素个数的方法在与collect联合使用的时候特别有用
        Long count1 = integerList.stream().collect(counting());

        //2.查找
        //(1) findFirst查找第一个:通过findFirst方法查找到第一个大于三的元素并打印
        Optional<Integer> result = integerList.stream().filter(i -> i > 3).findFirst();
        //(2)findAny随机查找一个
        //通过findAny方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和findFirst方法结果一样。提供findAny方法是为了更好的利用并行流,findFirst方法在并行上限制更多
        Optional<Integer> result1 = integerList.stream().filter(i -> i > 3).findAny();

        //3.reduce将流中的元素组合起来: reduce接受两个参数,一个初始值这里是0,一个BinaryOperator<T> accumulator来将两个元素结合起来产生一个新值,另外reduce方法还有一个没有初始化值的重载方法
        //jdk8之前
        int sum = 0;
        for(int i : integerList){
            sum += i;
        }
        //jdk8之后通过reduce进行处理
        int sum1 = integerList.stream().reduce(0, (a, b) -> (a+b));
        //或者
        int sum2 = integerList.stream().reduce(0, Integer::sum);

        //4.获取流中最小最大值
        //(1)通过min/max获取最小最大值:min获取流中最小值,max获取流中最大值,方法参数为Comparator<? super T> comparator
        Optional<Integer> min = integerList.stream().min(Integer::compareTo);
        Optional<Integer> max = integerList.stream().max(Integer::compareTo);
        //或者
        List<Dish> menu = new ArrayList<>();
        Optional<Integer> min1 = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
        Optional<Integer> max1 = menu.stream().map(Dish::getCalories).max(Integer::compareTo);
        //或者
        OptionalInt min2 = menu.stream().mapToInt(Dish::getCalories).min();
        OptionalInt max2 = menu.stream().mapToInt(Dish::getCalories).max();
        //(2)通过minBy/maxBy获取最小最大值:minBy获取流中最小值,maxBy获取流中最大值,方法参数为Comparator<? super T> comparator
        Optional<Integer> min3 = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
        Optional<Integer> max3 = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
        //(3)通过reduce获取最小最大值
        Optional<Integer> min4 = menu.stream().map(Dish::getCalories).reduce(Integer::min);
        Optional<Integer> max4 = menu.stream().map(Dish::getCalories).reduce(Integer::max);

        //5.求和
        //(1) 通过summingInt: 如果数据类型为double、long,则通过summingDouble、summingLong方法进行求和
        int sum3 = menu.stream().collect(summingInt(Dish::getCalories));
        //(2)通过reduce
        int sum4 = menu.stream().map(Dish::getCalories).reduce(0, Integer::sum);
        //(3)通过sum
        int sum5 = menu.stream().mapToInt(Dish::getCalories).sum();

        //6.通过averagingInt求平均值:如果数据类型为double、long,则通过averagingDouble、averagingLong方法进行求平均
        double average = menu.stream().collect(averagingInt(Dish::getCalories));
        double average1 = menu.stream().collect(averagingDouble(Dish::getCalories));

        //7.通过summarizingInt同时求总和、平均值、最大值、最小值: 如果数据类型为double、long,则通过summarizingDouble、summarizingLong方法
        IntSummaryStatistics intSummaryStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
        double average11 = intSummaryStatistics.getAverage();  //获取平均值
        int min11 = intSummaryStatistics.getMin();  //获取最小值
        int max11 = intSummaryStatistics.getMax();  //获取最大值
        long sum11 = intSummaryStatistics.getSum();  //获取总和

        //8.通过foreach进行元素遍历
        integerList.stream().forEach(System.out::println);
        integerList.stream().forEach(s -> System.out.println(s));

        //9.返回集合:通过遍历和返回集合的使用发现流只是把原来的外部迭代放到了内部进行,这也是流的主要特点之一。内部迭代可以减少好多代码量
        List<String> strings = menu.stream().map(Dish::getName).collect(toList());
        Set<String> sets = menu.stream().map(Dish::getName).collect(toSet());

        //10.通过joining拼接流中的元素:默认如果不通过map方法进行映射处理拼接的toString方法返回的字符串,joining的方法参数为元素的分界符,如果不指定生成的字符串将是一串的,可读性不强
        String result2 = menu.stream().map(Dish::getName).collect(Collectors.joining(", "));

        //11.通过groupingBy进行分组:在collect方法中传入groupingBy进行分组,其中groupingBy的方法参数为分类函数。还可以通过嵌套使用groupingBy进行多级分类
        List<Dish> dishList = new ArrayList<>();
        //dishList.add();  //add添加数据
        Map<Dish.Type, List<Dish>> result3 = dishList.stream().collect(groupingBy(Dish::getType));
        Map<Dish.Type, Map<Object, List<Dish>>> result4 = menu.stream().collect(groupingBy(Dish::getType, groupingBy(dish -> {
            if(dish.getCalories() <= 400){
                return  "低于400的卡路里";
            }else if(dish.getCalories() <= 700){
                return "低于700的卡路里";
            }else {
                return "其他";
            }
        })));

        //12.通过partitioningBy进行分区:分区是特殊的分组,它分类依据是true和false,所以返回的结果最多可以分为两组
        Map<Boolean, List<Dish>> result5 = menu.stream().collect(partitioningBy(Dish::isVegetarian));
        //等同于
        Map<Boolean, List<Dish>> result6 = menu.stream().collect(groupingBy(Dish::isVegetarian));
        //返回值的键仍然是布尔类型,但是它的分类是根据范围进行分类的,分区比较适合处理根据范围进行分类
        Map<Boolean, List<Integer>> result7 = integerList.stream().collect(partitioningBy(i -> i < 3));


    }
}

用法示例5

 public static void main(String[] args) {
        List<Integer> list = Arrays.asList(8, 9, 2, 1, 0, 4, 6, 3, 7);
        //遍历输出符合条件的元素
        list.stream().filter(x -> x > 6).forEach(System.out::println);

        //匹配第一个
        Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
        //匹配任意(适用于并行流)
        Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
        //是否包含符合特定条件的元素
        boolean anyMatch = list.stream().anyMatch(x -> x < 6);
        System.out.println("匹配第一个值:" + findFirst.get());
        System.out.println("匹配任意一个值:" + findAny.get());
        System.out.println("是否存在大于6的值:" + anyMatch);

        //筛选出Integer集合中大于7的元素,并打印出来
        Stream<Integer> stream = list.stream();
        stream.filter(x -> x > 7).forEach(System.out::println);

    }

用法示例6

public static void main(String[] args) {
        List<Person> personList = new ArrayList<Person>();
        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"));

        //筛选员工中工资高于8000的人,并形成新的集合。形成新集合依赖collect(收集)
        List<String> filterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName).collect(Collectors.toList());
        System.out.println("高于8000的员工姓名:" + filterList);

        //获取员工工资最高的人
        Optional<Person> max = personList.stream().max(Comparator.comparing(Person::getSalary));
        System.out.println("员工工资最大值:" + max.get().getSalary());


        //将员工的薪资全部增加10000
        //不改变原来员工集合的方式
        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());

        //求所有员工的工资之和和最高工资。
        //方法1:求工资之和
        Optional<Integer> sumSalary1 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
        //方法2:求工资之和
        Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2)-> sum1+sum2);
        //方法3:求工资之和
        Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);

        //方法1:求最高工资
        Integer maxSalary = personList.stream().reduce(0, (max1, p) -> max1 > p.getSalary() ? max1 : p.getSalary(), Integer::max);
        //方法2:求最高工资
        Integer maxSalary1 = personList.stream().reduce(0, (max1, p) -> max1 > p.getSalary() ? max1 : p.getSalary(), (max1, max2) -> max1 > max2 ? max1 : max2);
        System.out.println("工资之和:" + sumSalary1.get() + "," + sumSalary2 + "," + sumSalary3);
        System.out.println("最高工资:" + maxSalary + "," + maxSalary1);

        //归集(toList/toSet/toMap)
        Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p->p));
        System.out.println("toMap = " + map);

        /**
         * Collectors提供了一系列用于数据统计的静态方法:
         * 计数:count
         * 平均值:averagingInt、averagingLong、averagingDouble
         * 最值:maxBy、minBy
         * 求和:summingInt、summingLong、summingDouble
         * 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
         */
        //求总数
        Long count = personList.stream().collect(Collectors.counting());
        //求平均工资
        Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
        //求工资之和
        Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
        //一次性统计所有信息
        DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
        System.out.println("员工总数:" + count);
        System.out.println("员工平均工资:" + average);
        System.out.println("员工工资总和:" + sum);
        System.out.println("员工工资所有统计:" + collect);

        /**
         * 分组(partitioningBy/groupingBy)
         *
         * 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
         * 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
         */
        //将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组
        //将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
        //将员工按性别分组
        Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        //将员工先按性别分组,在按地区分组
        Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        System.out.println("员工按薪资是否大于8000分组情况:" + part);
        System.out.println("员工按性别分组情况:" + group);
        System.out.println("员工按性别、地区:" + group2);

        //接合(joining): joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
        String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
        System.out.println("所有员工的姓名:" + names);

        //Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。
        //每个员工减去起征点后的薪资之和
        Integer sum11 = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));
        System.out.println("员工扣税薪资总和:" + sum11);

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

        /**
         * 排序(sorted)
         * sorted,中间操作。有两种排序:
         *
         * sorted():自然排序,流中元素需实现Comparable接口
         * sorted(Comparator com):Comparator排序器自定义排序
         */
        //按工资升序排序(自然排序)
        List<String> sortList1 = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
        //按工资倒序排序
        List<String> sortList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());
        //先按工资再按年龄升序排序
        List<String> sortList3 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());
        //先按工资再按年龄自定义排序(降序)
        List<String> sortList4 = 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("按工资升序排序:" + sortList1);
        System.out.println("按工资降序排序:" + sortList2);
        System.out.println("先按工资再按年龄升序排序:" + sortList3);
        System.out.println("先按工资再按年龄自定义降序排序:" + sortList4);



    }

用法示例7

 public static void main(String[] args) {
        //英文字符串数组的元素全部改为大写。整数数组每个元素+3。
        String[] strArr = {"dghdg", "bgwe", "uieytw", "opqiqza", "okjgqtr"};
        List<String> stringList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("每个元素大写:" + stringList);

        List<Integer> integerList = Arrays.asList(1, 9, 3, 2, 4, 0, 5, 6);
        List<Integer> intListNew = integerList.stream().map(x -> x + 3).collect(Collectors.toList());
        System.out.println("每个元素加3:" + intListNew);


        //获取String集合中最长的元素
        List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
        Optional<String> length = list.stream().max(Comparator.comparing(String::length));
        System.out.println("最长的字符串:" + length.get());

        //获取Integer集合中的最大值。
        //自然排序
        Optional<Integer> max1 = integerList.stream().max(Integer::compareTo);
        //自定义排序
        Optional<Integer> max2 = integerList.stream().max(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        System.out.println("自然排序最大值:" + max1.get());
        System.out.println("自定义排序最大值:" + max2.get());

        //计算Integer集合中大于6的元素的个数。
        long count = integerList.stream().filter(x -> x > 6).count();
        System.out.println("integerList中大于6的元素个数:" + count);

        //将两个字符数组合并成一个新的字符数组。
        List<String> listStr = Arrays.asList("a, b, c, d, e", "1, 2, 3, 4, 5, 6");
        List<String> listNew = listStr.stream().flatMap(s -> {
            //将每个元素转换成一个stream
            String[] split = s.split(",");
            Stream<String> s2 = Arrays.stream(split);
            return s2;
        }).collect(Collectors.toList());
        System.out.println("处理前的集合:" + listStr);
        System.out.println("处理后的集合:" + listNew);

        //joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
        String pjStr = listStr.stream().collect(Collectors.joining("-"));
        System.out.println("拼接后的字符串:" + pjStr);

        //提取/组合:流也可以进行合并、去重、限制、跳过等操作。
        String[] arr1 = {"a", "b", "c", "d", "e", "f"};
        String[] arr2 = {"g", "h", "k", "m", "n", "w"};
        Stream<String> stream1 = Stream.of(arr1);
        Stream<String> stream2 = Stream.of(arr2);
        // concat:合并两个流 distinct:去重
        List<String> distinct = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
        // limit:限制从流中获得前n个数据
        List<Integer> limit = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
        // skip:跳过前n个数据
        List<Integer> skip = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());
        System.out.println("流合并:" + distinct);
        System.out.println("limit:" + limit);
        System.out.println("skip:" + skip);

        List<String> stringList1 = Arrays.asList("a","b","c","a","c","d");
        List<String> stringList2 = stringList1.stream().distinct().collect(Collectors.toList());
        System.out.println("去重后:"+stringList2);
        Integer size =  stringList1.stream().distinct().collect(Collectors.toList()).size();
        System.out.println("去重后长度:" + size);


    }

用法示例8

 public static void main(String[] args) {
        //归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。
        List<Integer> integerList = Arrays.asList(1, 7, 9, 0, 3, 5, 6, 4);
        //方法1:求和
        Optional<Integer> sum = integerList.stream().reduce((x, y) -> x+y);
        //方法2:求和
        Optional<Integer> sum1 = integerList.stream().reduce(Integer::sum);
        //方法3:求和
        Integer sum2 = integerList.stream().reduce(0, Integer::sum);

        //求乘积
        Optional<Integer> cj = integerList.stream().reduce((x, y) -> x*y);

        //方法1:求最大值
        Optional<Integer> max = integerList.stream().reduce((x, y) -> x > y ? x : y);
        //方法2:求最大值
        Integer max1 = integerList.stream().reduce(1, Integer::max);

        System.out.println("integerList求和:" + sum.get() + "," + sum1.get() + "," + sum2);
        System.out.println("integerList求积:" + cj.get());
        System.out.println("integerList求和:" + max.get() + "," + max1);



    }

今日分享就到这里了,编写不易,请多多支持一下!

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1.5万
获赞与收藏
8507

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消