JAVA1.8stream demo

package com.hj.test.stream;

import com.alibaba.fastjson.JSONObject;
import com.hj.test.bean.Person;

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

public class DistinctPerson {
    public static void main(String[] args) {

        List<Person> persons = new ArrayList();
        Person person1 = new Person("黃傑1", 19);
        Person person2 = new Person("黃傑1", 18);
        Person person3 = new Person("黃傑2", 12);
        Person person4 = new Person("黃傑3", 12);
        Person person5 = new Person("黃傑3", 13);
        Person person6 = new Person("黃傑4", 25);
        Person person7 = new Person("黃傑4", 17);
        persons.add(person1);
        persons.add(person2);
        persons.add(person3);
        persons.add(person4);
        persons.add(person5);
        persons.add(person6);
        persons.add(person7);
        List<Person> studentDistinctList = persons.stream().sorted(Comparator.comparing(Person::getAge).reversed())
                .collect(Collectors.collectingAndThen
                        (Collectors.toCollection(() ->
                                        new TreeSet<>(Comparator.comparing(Person::getName))),
                                ArrayList::new
                        )
                );
        System.out.println(JSONObject.toJSON(studentDistinctList).toString());

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

        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);

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        // 奇偶數分組:奇數分一組,偶數分一組
        // groupingBy(Function<? super T, ? extends K> classifier) 參數是Function類型,Function返回值可以是要分組的條件,也可以是要分組的字段
        // 返回的結果是Map,其中key的數據類型爲Function體中計算類型,value是List<T>類型,爲分組的結果
        Map<Boolean, List<Integer>> result = list.stream().collect(Collectors.groupingBy(item -> item % 2 == 0));
        // {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]}
        System.out.println(result);


        // partitioningBy 用於分成兩組的情況
        Map<Boolean, List<Integer>> twoPartiton = list.stream().collect(Collectors.partitioningBy(item -> item % 2 == 0));
        System.out.println(twoPartiton);


        User user = new User(100, "zhangsan", 1);
        User user2 = new User(200, "lisi", 2);
        User user3 = new User(300, "wangwu", 3);
        User user4 = new User(400, "fengliu", 1);
        User user5 = new User(700, "fengliu1", 2);
        User user6 = new User(60, "fengliu2", 3);
        List<User> users = Arrays.asList(user, user2, user3, user4,user5, user6);
        // 根據某個字段進行分組
        Map<Integer, List<User>> userGroup = users.stream().collect(Collectors.groupingBy(item -> item.type));

        List<Integer> result1 = users.stream().collect(Collectors.groupingBy(User::getType,
                Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(User::getId)), optional->optional.get().getId())))
                .values().stream().collect(Collectors.toList());
        System.out.println(result1);
        List<User> list1 = new ArrayList<>(users.stream().collect(Collectors.toMap(User::getType, Function.identity(), BinaryOperator.maxBy(Comparator.comparingInt(User::getId)))).values());
       // users.stream().collect(Collectors.partitioningBy())
        System.out.println(JSONObject.toJSON(result1).toString());
        System.out.println(JSONObject.toJSON(list1).toString());
        /**
         * key 爲要分組的字段
         * value 分組的結果
         * {
         *  1=[User{id=1, username='zhangsan', type=1}, User{id=4, username='fengliu', type=1}],
         *  2=[User{id=2, username='lisi', type=2}],
         *  3=[User{id=3, username='wangwu', type=3}]
         * }
         */
      //  System.out.println(JSONObject.toJSON(userGroup).toString());

    }

    public static class User {
        private Integer id;
        private String username;
        private Integer type;

        // Getter & Setter & toString


        public Integer getId() {
            return id;
        }

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

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public Integer getType() {
            return type;
        }

        public void setType(Integer type) {
            this.type = type;
        }

        public User(Integer id, String username, Integer type) {
            this.id = id;
            this.username = username;
            this.type = type;
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章