자바 8 복잡 사례

11146 단어 Java
package stream;

import com.xrz.entity.Car;
import com.xrz.entity.House;
import com.xrz.entity.Worker;
import org.junit.Before;
import org.junit.Test;

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

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

/**
 * @Author XRZ
 * @Date 2020/7/31 11:17
 * @Version :
 * @Description :
 */
public class S {

    private List list;

    @Before
    public void before() {
        list = new ArrayList<>();
        list.add(new Worker("  ", " ", Boolean.FALSE, 10000, Arrays.asList(new Car("  "), new Car("  ")), Arrays.asList(new House("   "))));
        list.add(new Worker("  ", " ", Boolean.FALSE, 8000, Arrays.asList(new Car("  ")), null));
        list.add(new Worker("  ", " ", Boolean.FALSE, 6000, null, null));
        list.add(new Worker("  ", " ", Boolean.FALSE, 5000, Arrays.asList(new Car("  ")), Arrays.asList(new House("   "))));
        list.add(new Worker("  ", " ", Boolean.TRUE, 10000, null, Arrays.asList(new House("   "))));
        list.add(new Worker("  ", " ", Boolean.TRUE, 13000, Arrays.asList(new Car("  ")), Arrays.asList(new House("   "), new House("   "))));
    }

    @Test // flatMap      :            
    public void test01() {
        //         
        list.stream()
                .map(Worker::getCarList)
                .filter(Objects::nonNull)
                // Stream> -> Stream
                .flatMap(Collection::stream)
                .map(Car::getBrand)
                .collect(toList())
                .forEach(brand -> {
                    System.out.println(brand);
                });
    }

    @Test // allMatch、anyMatch、noneMatch             
    public void test02() {
        //          2500        true
        boolean allMatch = list.stream().allMatch(v -> v.getSalary() > 2500);
        //          10000       true
        boolean anyMatch = list.stream().anyMatch(v -> v.getSalary() > 10000);
        //            2500     false
        boolean noneMatch = list.stream().noneMatch(v -> v.getSalary() > 2500);
    }

    @Test // findFirst、findAny        
    public void test03() {
        Predicate isMan = (v) -> v.getSex().equals(" ");
        //               
        Optional findFifst = list.parallelStream().filter(isMan).findFirst();
        //               ||                       
        Optional findAny = list.parallelStream().filter(isMan).findAny();
    }

    @Test // sorted   
    public void test04() {
        //          ASE
        list.stream()
                // reversed    DESC
                .sorted(Comparator.comparing(Worker::getSalary)/*.reversed()*/)
                .forEach(System.out::println);

        //        ,       
        Comparator byName = Comparator.comparing(Worker::getSalary);
        Comparator bySex = Comparator.comparing(Worker::getSex);
        Comparator comparator = bySex.thenComparing(byName);
        list.stream()
                .sorted(comparator)
                .forEach(System.out::println);
    }

//===================================================[Collectors]==================================================================

    @Test // Collectors.toList()     
    public void test05() {
        //          
        List list1 = list.stream().map(Worker::getName)
                .collect(
                        //               
                        () -> new ArrayList(),
                        //        ,                
                        (z, t) -> z.add(t),
                        //               
                        (r, z) -> r.addAll(z)
                );
        List list2 = list.stream().map(Worker::getName)
                .collect(
                        ArrayList::new,
                        ArrayList::add,
                        ArrayList::addAll
                );
        List list3 = list.stream().map(Worker::getName)
                .collect(
                        LinkedList::new,
                        LinkedList::add,
                        LinkedList::addAll
                );
        List list4 = list.stream().map(Worker::getName).collect(toList());
        List list5 = list.stream().map(Worker::getName).collect(toCollection(LinkedList::new));
    }

    @Test //   、  
    public void test06() {
        // Collectors.counting()    
//        Long workerCount = list.stream().count();
        Long workerCount = list.stream().collect(Collectors.counting());
        // Collectors.maxBy()    
//        Optional maxBy = list.stream().max(Comparator.comparing(Worker::getSalary));
        Optional maxBy = list.stream().collect(Collectors.maxBy(Comparator.comparing(Worker::getSalary)));
        // Collectors.minBy()    
//        Optional minBy = list.stream().min(Comparator.comparing(Worker::getSalary));
        Optional minBy = list.stream().collect(Collectors.minBy(Comparator.comparing(Worker::getSalary)));
        // Collectors.averagingInt()    
//        Double average = list.stream().mapToInt(Worker::getSalary).average().getAsDouble();
        Double average = list.stream().collect(Collectors.averagingInt(Worker::getSalary));
        // Collectors.summing()   
//        Integer sum = list.stream().mapToInt(Worker::getSalary).sum();
        Integer sum = list.stream().collect(Collectors.summingInt(Worker::getSalary));
        // Collectors.summarizingInt()            
        IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Worker::getSalary));
        collect.getMax();
        collect.getMin();
        collect.getAverage();
        collect.getCount();
        collect.getSum();
    }

    @Test // Collectors.joining   
    public void test07() {
        // Collectors.joining("   ","  ","  ")
        String join = list.stream().map(Worker::getName).collect(joining());
        //    
        list.stream().collect(reducing("", Worker::getName, (n1, n2) -> n1 + n2));
        list.stream().map(Worker::getName).collect(reducing("", Function.identity(), (n1, n2) -> n1 + n2));
        //      
        String join1 = list.stream().map(Worker::getName)
                .collect(
                        () -> new StringBuilder(),
                        (builder, name) -> builder.append(name),
                        (res, builder) -> res.append(builder)
                ).toString();
        String join2 = list.stream().map(Worker::getName)
                .collect(
                        StringBuilder::new,
                        StringBuilder::append,
                        StringBuilder::append
                ).toString();
        System.out.println(join);   //            
        System.out.println(join1);  //            
        System.out.println(join2);  //            
    }

    @Test // Collectors.groupingBy()   
    public void test08() {
        //           
        Map> map1 = list.stream().collect(groupingBy(Worker::getSex));
        //              
        Map> map2 = list.stream().collect(groupingBy(Worker::getSex, mapping(Worker::getName, toList())));
        //             
        Map map3 = list.stream().collect(groupingBy(Worker::getSex, counting()));
        //               
        Map map4 = list.stream().collect(groupingBy(Worker::getSex, averagingInt(Worker::getSalary)));

        //    
        /*
                           
            {
              " ":{
                "true": [{"name": "  "}],
                "false": [{"name": "  "}]
              },
              " ":{
                "true": [{"name": "  "}],
                "false": [{"name": "  "}]
              }
            }
         */
        Map>> map5 = list.stream()
                .collect(groupingBy(Worker::getSex, groupingBy(Worker::getMarried)));
        /*
                            
            {
              " ":{"name":"  "},
              " ":{"name":"  "}
            }
         */
        Map map6 = list.stream()
                .collect(groupingBy(
                                Worker::getSex,
                                //   collect
                                collectingAndThen(
                                        //   collect   
                                        maxBy(Comparator.comparing(Worker::getSalary)),
                                        //          
                                        Optional::get
                                ))
                        );
        /*
                  ,               
            {
              " ":{
                "  ":"  ",
                "  ":"  、  ",
                "  ":""
              },
              " ":{
                "  ":"  ",
                "  ":"  ",
                "  ":"",
              }
            }
         */
        Map> map7 = list.stream()
                .collect(groupingBy(Worker::getSex,
                        groupingBy(Worker::getName,
                                collectingAndThen(
                                        mapping(Worker::getCarList, toList()),
                                        v -> v.stream()
                                                .filter(Objects::nonNull)
                                                .flatMap(Collection::stream)
                                                .map(Car::getBrand)
                                                .collect(joining("、"))
                                )
                        )
                ));
    }

    @Test // Collectors.partitioningBy()   
    public void test09(){
        //        
        Map> par1 = list.stream().collect(partitioningBy(Worker::getMarried));
        //       1w     {false=[  ,   ,   ,   ,   ], true=[  ]}
        Map> par2 = list.stream()
                .collect(partitioningBy(
                            worker -> worker.getSalary() > 10000,
                            mapping(Worker::getName, toList())
                        )
                );
    }


}

좋은 웹페이지 즐겨찾기