java8 Stream新特性
阅读原文时间:2023年07月08日阅读:4

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class Person {
private String name; // 姓名
private int salary; // 薪资
private int age; // 年龄
private String sex; //性别
private String area; // 地区

// 构造方法  
public Person(String name, int salary, int age,String sex,String area) {  
    this.name = name;  
    this.salary = salary;  
    this.age = age;  
    this.sex = sex;  
    this.area = area;  
}  

}

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class StreamTest {
public static void main(String[] args) {
List list = Arrays.asList(7, 6, 9, 3, 8, 2, 1,6,6,8);
List personList = new ArrayList();
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"));
personList.add(new Person("koukay", 9500, 26, "male", "New York"));
personList.add(new Person("houkay", 7800, 28, "male", "New York"));

    /\*maxLength();  
    more6Print(list, 6);  
    findFirst(list);  
    more6(list);  
    less6(list);  
    more7();  
    findPerson(personList);  
    maxValue();  
    maxSalary(personList);  
    more6Count(list);  
    upperCaseAdd3();  
    addSalary(personList);  
    splitList();  
    calculate();  
    sumAndMax(personList);  
    collectTo(list,personList);  
    operate(personList);  
    group(personList);  
    join(personList);  
    collectReducing(personList);  
    sort(personList);  
    \*/  
    distinctAndSkip();  

     listMapOrder();

}

/**
* mapList排序
*/
private static void listMapOrder(){
List> comments= new ArrayList<>();
for (int i = 0; i <10; i++) { Map map= new HashMap<>();
map.put("DateStr",Math.random());
comments.add(map);
}

    List<Map<String, Double>> collect = comments.stream().sorted(Comparator.comparing(StreamTest::comparingByData)).collect(Collectors.toList());  
    for (Map<String, Double> stringObjectMap : collect) {  
        System.out.println(stringObjectMap.get("DateStr"));  
    }  
}  
private static Double comparingByData(Map<String,Double> map){  
    return map.get("DateStr");  
}

/**
* 流合并、去重、限制、跳过等操作。
*/
private static void distinctAndSkip(){
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
Stream stream1 = Arrays.stream(arr1);
Stream stream2 = Arrays.stream(arr2);

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

    // limit:限制从流中获得前n个数据  
    List<Integer> collect2 = Stream.iterate(1, x -> x + 2).limit(5).collect(Collectors.toList());  
    // skip:跳过前n个数据  
    List<Integer> collect3 = Stream.iterate(1, x -> x + 2).skip(2).limit(5).collect(Collectors.toList());  
    System.out.println("合并去重的结果为: "+collect1);  
    System.out.println("取出前五个数据: "+collect2);  
    System.out.println("跳过前两个数据: "+collect3);  
}

/\*\*  
 \* sorted,中间操作。有两种排序:  
 \*  
 \* sorted():自然排序,流中元素需实现Comparable接口  
 \* sorted(Comparator com):Comparator排序器自定义排序  
 \*/  
private static void sort(List<Person> personList){  
    // 按工资增序排序  
    List<String> collect1 = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());  
    // 按工资倒序排序  
    List<String> collect2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());  
    // 先按工资再按年龄自然排序(从小到大)  
    List<String> collect3 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());  
    // 先按工资再按年龄自定义排序(从大到小)  
    List<String> collect4 = 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());  
    //先按工资再按年龄倒序  
    List<String> collect5 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());  
    // 先按工资再按年龄自定义排序(从大到小)  
    System.out.println("按工资增序排序: "+collect1);  
    System.out.println("按工资倒序排序: "+collect2);  
    System.out.println("先按工资再按年龄自然排序(从小到大): "+collect3);  
    System.out.println("先按工资再按年龄自定义排序(从大到小): "+collect4);  
    System.out.println("先按工资再按年龄倒序: "+collect5);

}

/\*\*  
 \* Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。  
 \*/  
private static void collectReducing(List<Person> personList){  
    // 每个员工减去起征点后的薪资之和  
    Optional<Integer> reduce = personList.stream().map(p -> p.getSalary() - 5000).reduce(Integer::sum);  
    Integer collect = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (x, y) -> (x + y - 5000)));  
    System.out.println("员工扣税薪资总和1:" + reduce.get());  
    System.out.println("员工扣税薪资总和2:" + collect);

}

/\*\*  
 \* joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。  
 \*/  
private static void join(List<Person> personList){  
    String collect = personList.stream().map(Person::getName).collect(Collectors.joining("--"));  
    System.out.println("所有成员姓名为: "+collect);  
    List<String> list = Arrays.asList("A", "B", "C");  
    String collect1 = list.stream().collect(Collectors.joining("\*"));  
    System.out.println("拼接后的字符串为: "+collect1);  
}

/\*\*  
 \* 将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组  
 \*/  
private static void group(List<Person> personList){  
    // 将员工按薪资是否高于8000分组  
    Map<Boolean, List<Person>> collect = personList.stream().collect(Collectors.partitioningBy(p -> p.getSalary() > 8000));  
    Map<Boolean, List<Person>> collect3 = personList.stream().collect(Collectors.groupingBy(p -> p.getSalary() > 8000));  
    // 将员工按性别分组  
    Map<String, List<Person>> collect1 = personList.stream().collect(Collectors.groupingBy(Person::getSex));  
    // 将员工先按性别分组,再按地区分组  
    Map<String, Map<String, List<Person>>> collect2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));  
    System.out.println("员工按薪资是否大于8000分组情况:" + collect);  
    System.out.println("员工按薪资是否大于8000分组情况:" + collect3);  
    System.out.println("员工按性别分组情况:" + collect1);  
    System.out.println("员工按性别、地区:" + collect2);  
}

/\*\*  
 \* 统计员工人数、平均工资、工资总额、最高工资。  
 \*/  
private static void operate(List<Person> personList){  
    //员工人数  
    Long collect = personList.stream().collect(Collectors.counting());  
    //平均工资  
    Double collect1 = personList.stream().collect(Collectors.averagingDouble(p -> p.getSalary()));  
    //工资总额  
    Double collect2 = personList.stream().collect(Collectors.summingDouble(Person::getSalary));  
    //最高工资  
    Optional<Integer> collect3 = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));  
    DoubleSummaryStatistics collect4 = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));  
    log.info("员工人数为: {}, 平均工资为: {}, 工资总额为: {}, 最高工资为: {}, 查询工资所有为: {}",collect,collect1,collect2,collect3,collect4);

}  
private static void collectTo(List<Integer> list, List<Person> personList){  
    List<Integer> collect1 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());  
    Set<Integer> collect2 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());  
    Map<String, Person> collect = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p));  
    System.out.println(collect1);  
    System.out.println(collect2);  
    System.out.println(collect);  
}

/\*\*  
 \* 求所有员工的工资之和和最高工资。  
 \*/  
private static void sumAndMax(List<Person> personList){  
    //员工工资之和方式一  
    Optional<Integer> reduce = personList.stream().map(Person::getSalary).reduce((p1, p2) -> p1 + p2);  
    //员工工资之和方式二  
    Integer reduce1 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);  
    //员工工资之和方式三  
    Optional<Integer> reduce2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);  
    //员工工资之和方式四  
    Integer reduce3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);

    //员工工资最高值一  
    Optional<Integer> reducemax1 = personList.stream().map(Person::getSalary).reduce(Integer::max);  
    //员工工资最高值二  
    Optional<Integer> reducemax2 = personList.stream().map(Person::getSalary).reduce((s1,s2)->s1>s2?s1:s2);  
    //员工工资最高值三  
    Integer reduce4 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max);  
    Integer reduce5 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary() ,(max1,max2)->max1>max2?max1:max2);  
    log.info("员工工资之和1为: {},员工工资之和2为: {},员工工资之和3为: {},员工工资之和4为: {}",reduce.get(),reduce1,reduce2.get(),reduce3);  
    log.info("员工工资最高值1: {},员工工资最高值2: {},员工工资最高值3: {},员工工资最高值4: {}",reducemax1.get(),reducemax2.get(),reduce4,reduce5);  
}

/\*\*  
 \* 求Integer集合的元素之和、乘积和最大值。  
 \*/  
private static void calculate(){  
    List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);  
    // 求和方式1  
    Optional<Integer> reduce = list.stream().reduce((x, y) -> x + y);  
    // 求和方式2  
    Optional<Integer> reduce1 = list.stream().reduce(Integer::sum);  
    // 求和方式3  
    Integer reduce2 = list.stream().reduce(0, Integer::sum);  
    log.info("求和方式1: {},  方式2: {},  方式3: {}",reduce.get(),reduce1.get(),reduce2);  
    // 求乘积  
    Optional<Integer> reduce3 = list.stream().reduce((x, y) -> x \* y);  
    log.info("求乘积为: {}",reduce3.get());  
    // 求最大值方式1  
    Optional<Integer> reduce4 = list.stream().reduce((x, y) -> x > y ? x : y);  
    // 求最大值方式1  
    Optional<Integer> reduce5 = list.stream().reduce(Integer::max);  
    log.info("求最大值方法1: {},方式2: {}",reduce4.get(),reduce5.get());  
}

/\*\*  
 \* 将两个字符数组合并成一个新的字符数组。  
 \*/  
private static void splitList(){  
    List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");  
    List<String> collect = list.stream().flatMap(str -> {  
        String\[\] split = str.split(",");  
        return Arrays.stream(split);  
    }).collect(Collectors.toList());  
    System.out.println(list);  
    System.out.println(collect);  
}

/\*\*  
 \* 将员工的薪资全部增加1000。  
 \* @param personList  
 \*/  
private static void addSalary(List<Person> personList){  
    List<Person> collect = personList.stream().map((person) -> {  
        person.setSalary(person.getSalary() + 1000);  
        return person;  
    }).collect(Collectors.toList());  
    collect.forEach(person -> {  
        log.info("{}调薪后的工资为{}",person.getName(),person.getSalary());  
    });  
}

/\*\*  
 \* 英文字符串数组的元素全部改为大写。整数数组每个元素+3。  
 \*/  
private static void upperCaseAdd3(){  
    String\[\] strArr = { "abcd", "bcdd", "defde", "fTr" };  
    List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);  
    List<String> collect1 = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());  
    List<Integer> collect = intList.stream().map(x -> x + 3).collect(Collectors.toList());

    collect1.forEach(a->{  
        log.info("每个元素大写-> "+a);  
    });  
    collect.forEach(a->{  
        log.info("每个元素+3-> "+a);  
    });

}  
private static void more6Count(List<Integer> list){  
    long count = list.stream().filter(x -> x > 6).count();  
    log.info("大于6的元素有{}个",count);  
}  
private static void maxSalary( List<Person> personList ){  
    Optional<Person> max = personList.stream().max(Comparator.comparing(Person::getSalary));  
    System.out.println("姓名: "+max.get().getName()+"--------工资 "+max.get().getSalary());  
}  
private static void maxValue(){  
    List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6);

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

}  
/\*\*  
 \* 获取String集合中最长的元素  
 \*/  
private static void maxLength(){  
    List<String> list = Arrays.asList("adnm", "admmt", "potjhgfdsatfd", "xbangd", "weoujgsd");  
    Optional<String> max = list.stream().max(Comparator.comparing(String::length));  
    System.out.println(max.get());

}  
/\*\*  
 \* 遍历输出符合条件的元素 大于6  
 \* @param list  
 \* @param i  
 \*/  
private static void more6Print(List<Integer> list, int i) {  
    list.stream().filter(x -> x > i).forEach(System.out::println);  
}

/\*\*  
 \*  匹配第一个  
 \* @param list  
 \*/  
private static void findFirst(List<Integer> list) {  
    Optional<Integer> first = list.stream().filter(x -> x > 6).findFirst();  
    System.out.println("匹配第一个大于6的数-> "+first.get());  
}

/\*\*  
 \* // 匹配任意(适用于并行流)大于6  
 \* @param list  
 \*/  
private static void more6(List<Integer> list) {  
    Optional<Integer> any = list.parallelStream().filter(x -> x > 6).findAny();  
    System.out.println("匹配任意(适用于并行流)大于6-> "+any.get());  
}

/\*\*  
 \* // 是否包含符合特定条件的元素  小于6  
 \* @param list  
 \*/  
private static void less6(List<Integer> list) {  
    boolean b = list.stream().anyMatch(x -> x < 6);  
    System.out.println("是否包含小于6的元素-> "+b);  
}  
/\*\*  
 \* //筛选出Integer集合中大于7的元素,并打印出来  
 \*/  
private static void more7() {  
    List<Integer> list2 = Arrays.asList(6, 7, 3, 8, 1, 2, 9);  
    more6Print(list2, 7);  
}

/\*\*  
 \* 筛选员工中工资高于8000的人,并形成新的集合  
 \*/  
public static void findPerson(List<Person> personList){

    personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toList()).forEach((t)->{  
        System.out.println("姓名: "+t.getName()+"--------工资 "+t.getSalary());  
    });  
}  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器