stream01

package com.ayan.cc.mystream;

import com.ayan.cc.aspect.AttLog;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class StreamMe {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    public static List<Student> list = initData();
    public static HashMap map = new HashMap();

    private static List<Student> initData() {
        ArrayList<Student> list = new ArrayList<>(100);
        for (int i = 0; i < 20; i++) {
            Student student = new Student();
            student.setAge(i % 5);
            student.setGrade((int) (Math.random() * 100));
            student.setName(UUID.randomUUID().toString().substring(0, 7).replace("-", ""));
            list.add(student);
        }
        return list;
    }

    @Test
    public void map() {
        //maptoInt
        int sum = list.stream().mapToInt(Student::getAge).sum();
        //map
        Integer reduce = list.stream().map(Student::getAge).reduce(10, (a, b) -> a + b);//10为迭代初始值
        Optional<Integer> reduce1 = list.stream().map(Student::getAge).reduce((a, b) -> a + b);//
        String reduce2 = list.stream().map(Student::getName).reduce("", (a, b) -> a + b + ",");//
        log.debug("result_1 -> {},result_2 -> {},result_3 -> {},result_4 -> {} ", sum, reduce, reduce1, reduce2);
    }

    @Test
    public void peek() {
        //peek没有返回值,适合对流中的对象做修改
        List<Student> collect = list.stream().peek(e -> e.setName("aaa")).collect(Collectors.toList());
        //map适合做对象转化
        List<String> collect1 = list.stream().map(Student::getName).collect(Collectors.toList());
        System.out.println(collect);
        // log.debug("result_1 -> {},result_2 -> {},result_3 -> {},result_4 -> {} ",sum,reduce,reduce1,reduce2);
    }

    @Test
    public void Sort() {
        list.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);//简单排序建议
        System.out.println("---------------------------------------");
        list.stream().sorted((e1, e2) -> e2.getAge() - e1.getAge()).forEach(System.out::println);//复杂排序建议
        System.out.println("多字段 多次排序---------------------------------------");
        // 多字段排序 age,grage
        //使用sort排序2次  grage放在前面
        list.stream()
                .sorted((e1, e2) -> e1.getGrade() - e2.getGrade())
                .sorted((e1, e2) -> e1.getAge() - e2.getAge())
                .forEach(System.out::println);
        // 多字段排序 age,grage 使用thenCompare  :不太灵活 如果要反向排序的话
        System.out.println("---------------------------------------");
        list.stream().sorted(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getGrade)).forEach(System.out::println);
        // 多字段排序 age,grage
        System.out.println("Stream Lambda多字段排序---------------------------------------");
        list.stream()
                .sorted((e1, e2) -> {
                    if (e1.getAge() != e2.getAge()) {
                        return e1.getAge() - e2.getAge();
                    } else {
                        return e1.getGrade() - e2.getGrade();
                    }
                })
                .forEach(System.out::println);
        System.out.println("treeSet排序---------------------------------------");
        list = initData();
        TreeSet<Student> students = new TreeSet<>((e1, e2) -> {
            if (e1.getAge() != e2.getAge()) {
                return e1.getAge() - e2.getAge();
            } else {
                return e1.getGrade() - e2.getGrade();
            }
        });
        Iterator<Student> iterator = students.iterator();

        students.addAll(list);
        for (Student student : students) {
            System.out.println(student);
        }
        System.out.println("集合工具排序---------------------------------------");
        list = initData();
        Collections.sort(list, (e1, e2) -> {
            if (e1.getAge() != e2.getAge()) {
                return e2.getAge() - e1.getAge();
            } else {
                return e2.getGrade() - e1.getGrade();
            }
        });
        for (Student student : list) {
            System.out.println(student);
        }
    }

    @Test
    public void filter() {
        ArrayList<String> strings = Lists.newArrayList("张三", "aBC001", "AVC002", "Aa", "李四三", "三塔拉");
        strings.stream().filter(e -> StringUtils.containsIgnoreCase(e, "a")).forEach(System.out::println);
    }

    /**属性分组*/
    @Test
    public void Collecgtors_groupingBy() {
        Map<Integer, List<Student>> map = list.stream().collect(Collectors.groupingBy(Student::getAge));
        System.out.println(map);
    }
    /**字符处理*/
    @Test
    public void Collectors_Jioning() {
        String name = list.stream().map(Student::getName).collect(Collectors.joining("/"));
        String name2 = list.stream().map(Student::getName).collect(Collectors.joining("-", "[", "]"));
        System.out.println(name);
        System.out.println(name2);
    }

    @Test
    public void Collectors_tomap() {
        /**(k1, k2) -> k2,去重取第二个*/
        Map<Integer, String> map = list.stream()
                .collect(Collectors.toMap(Student::getAge, Student::getName, (k1, k2) -> k2));
        Map<Integer, Student> map2 = list.stream()
                .collect(Collectors.toMap(Student::getAge, e -> e, (k1, k2) -> k2));
        Map<Integer, Student> map3 = list.stream()
                .collect(Collectors.toMap(Student::getAge, Function.identity(), (k1, k2) -> k2));// Function.identity() 内部就是e->e
        log.debug("show map2 >>> {}", map2);
    }

    @Test
    public void t() {
        Map<Integer, List<Student>> map = list.stream().collect(Collectors.groupingBy(Student::getAge));
        map.forEach((k,v)->{
            System.out.println(k);
            System.out.println(v);
        });

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值