java8日常使用筆記

public class Test {


    public static class Student {

        public Student(Integer id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        private Integer id;

        private String name;

        private Integer age;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    public static void main(String[] args) {

        //(1)中間操作:filter(Predicate<T>), map(Function(T, R), limit, sorted(Comparator<T>), distinct,flatMap;
        //(2)終端操作:只有終端操作才能產(chǎn)生輸出,包括:allMatch, anyMatch, noneMatch, findAny, findFirst, forEach, collect, reduce, count

        List<Integer> list = Arrays.asList(1,2,3,4,5,6,6,6);

        List<Student> studentList = Arrays.asList(new Student(1,"cheng1",21),
                new Student(2,"cheng2",22),
                new Student(3,"cheng3",23));

        //過濾filter
        List<Integer> collect = list.stream().filter(var -> var != 3).collect(Collectors.toList());
        System.out.println("過濾3的集合為:"+collect);

        //去重distinct
        List<Integer> distinctList = list.stream().distinct().collect(Collectors.toList());
        System.out.println("去重復(fù)list:"+distinctList);

        //跳過前n個(gè) skip
        List<Integer> skipList = list.stream().skip(3).collect(Collectors.toList());
        System.out.println("skipList = " + skipList);


        //匹配
        boolean anyMatch = list.stream().anyMatch(var -> var == 2);
        System.out.println("anyMatch = " + anyMatch);

        //獲取第一個(gè) findFirst
        Integer firstV = list.stream().findFirst().orElse(999);
        System.out.println("firstV = " + firstV);

        //使用findAny()是為了更高效的性能。如果是數(shù)據(jù)較少,串行地情況下,一般會返回第一個(gè)結(jié)果,如果是并行的情況,那就不能確保是第一個(gè)
        Integer anyV = list.stream().findAny().get();
        System.out.println("anyV = " + anyV);

        System.out.println("串行findAny"+IntStream.range(0, 100).findAny());
        System.out.println("并行findAny"+IntStream.range(0, 100).parallel().findAny());

        //排序
        list.sort(Comparator.reverseOrder());
        System.out.println("倒序"+list);

        //對象排序
        studentList.sort(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getId));
        System.out.println("根據(jù)年齡排序:"+studentList);


        //Collectors.toMap 轉(zhuǎn)換為Map格式 {k=id,v=student}
        Map<Integer, Student> studentIdMap = studentList.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (k1, k2) -> k1));

        //分組 Collectors.groupingBy 年齡分組 k=年齡 v=list(student)
        Map<Integer, List<Student>> ageGroupList = studentList.stream().collect(Collectors.groupingBy(Student::getAge));

        //自定義分組 以名字+年齡分組 k= 名字+年齡 v=list(student)
        Map<String, List<Student>> nameAndAgeGroupList = studentList.stream().collect(Collectors.groupingBy(var -> var.getName() + "" + var.getAge()));

        //分組后在 組裝value內(nèi)容 Collectors.mapping 對結(jié)果進(jìn)行映射操作
        Map<Integer, List<Student>> mappingMap = studentList.stream()
                .collect(Collectors.groupingBy(Student::getAge, Collectors.mapping(var -> new Student(var.getAge(), var.getName()+"我是組裝", var.getAge()+1), Collectors.toList())));

        //map
        List<Integer> studentIds = studentList.stream().map(Student::getId).collect(Collectors.toList());


        //list轉(zhuǎn)Map
        Map<String, Object> merged = lists.stream()
        .map(Map::entrySet)
        .flatMap(Set::stream)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        Map<String, Integer> benefitAmountMap = benefitAmountList.stream().flatMap(m -> m.entrySet().stream())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1));


        //求值
        //reduce歸約,將流中的值結(jié)合起來,得到一個(gè)值
        //求和
        Integer sum = list.stream().reduce(Integer::sum).get();
        System.out.println("sum = " + sum);
        Integer sum3 = list.stream().collect(Collectors.summingInt(var -> var));

        //年齡累加
        Integer ageSum = studentList.stream().collect(Collectors.reducing(0, Student::getAge, (a, b) -> a + b));
        System.out.println("ageSum = " + ageSum);


        //最大值
        Integer max = list.stream().max(Comparator.comparing(Function.identity())).get();
        System.out.println("max = " + max);

        //收集數(shù)據(jù)統(tǒng)計(jì)
        IntSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingInt(var -> var));
        //平均數(shù)
        double average = summaryStatistics.getAverage();
        System.out.println("average = " + average);
        //求和
        long sum1 = summaryStatistics.getSum();
        System.out.println("sum1 = " + sum1);
        //最大
        int max1 = summaryStatistics.getMax();
        System.out.println("max1 = " + max1);
        //最小
        int min = summaryStatistics.getMin();
        System.out.println("min = " + min);
        long count = summaryStatistics.getCount();
        System.out.println("count = " + count);

        //字符串join
        String joinStr = Stream.of("a", "b", "c").collect(Collectors.joining(",","[","]"));
        System.out.println("joinStr = " + joinStr);

        Map map = new HashMap();
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        StringJoiner joiner = new StringJoiner("&");
        map.forEach((k,v)->{
            String var = k+"="+v;
            joiner.add(var);
        });
        System.out.println("joiner = " + joiner.toString());

        //隨機(jī)數(shù)生成
        List<Integer> randomInt = Stream.generate(() -> {
            Random random = new Random();
            return random.nextInt(10);
        }).limit(10).collect(Collectors.toList());
        System.out.println("randomInt = " + randomInt);

        //函數(shù)接口使用
        Supplier<String> supplier = ()->"hahahah,我無入?yún)?;
        System.out.println(supplier.get());//hahahah,我無入?yún)?
        //接受入?yún)?無返回值
        Consumer<String> consumer = var-> System.out.println(var);
        consumer.accept("hello");//hello

        //接受類型參數(shù),返回boolean
        Predicate<String> predicate = var-> StringUtils.isBlank(var);
        System.out.println(predicate.test(""));//true

        //接受1個(gè)參數(shù),返回一個(gè)參數(shù)
        Function<String,Integer> function = var-> {
            if (var.equals("a")) {
                return 1;
            }
            return 0;
        };
        System.out.println(function.apply("a"));

    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容