JDK8 Stream LocalDate LocalDateTime 测试

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class LambdaTest {

    @Test
    public void buildStream(){
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        Integer[] ints = {1, 2, 3, 4};
        Stream<Integer> stream4 = Arrays.asList(ints).stream();

        int[] ints1 = {1, 2, 3, 4};
        Stream<int[]> stream5 = Arrays.asList(ints1).stream();

        Stream<String> stream1 = Stream.of("a", "b");

        String[] strings = {"a", "B"};
        Stream<String> strings1 = Stream.of(strings);

        Stream<String> stream2 = Arrays.stream(strings);

        Stream<String> stream3 = Arrays.asList(strings).stream();
    }

    @Test
    public void converStream(){
//        注意: 一个 Stream 流只可以使用一次,这段代码为了简洁而重复使用了数次,因此会抛出 stream has already been operated upon or closed 异常。
        Stream<String> stream1 = Stream.of("a", "b");
        String[] strings = stream1.toArray(String[]::new);

        List<String> list = stream1.collect(Collectors.toList());
        list = stream1.collect(Collectors.toCollection(ArrayList::new));

        Set<String> sets = stream1.collect(Collectors.toSet());

        Stack<String> stack = stream1.collect(Collectors.toCollection(Stack::new));

        String string = stream1.collect(Collectors.joining()).toString();
    }

    class Abc{
        public void addStr(Object o){
            System.out.println(o+"dddd");
        }
    }

    @Test
    public void forEach(){
        ArrayList<Integer> ints = new ArrayList<Integer>();
        for(int i = 0; i < 5; i++) ints.add(i);
        ints.stream().forEach(System.out::println);
        ints.stream().forEach(new Abc()::addStr);

        HashMap<Integer, String> hashMap = new HashMap<>();
        for (int i = 0; i < 5; i++) {
            hashMap.put(i, "v"+i);
        }
        hashMap.forEach((k, v) -> System.out.println(k+"---"+v));
    }

    @Test
    public void map(){
        List<String> list = Arrays.asList("张三", "李四", "xuwujing", "WANGER", "1234");
        list.stream().map(String::toUpperCase).collect(Collectors.toList())
                .forEach(System.out::println);
        List<String> numStrings = Arrays.asList("1", "2", "3");
        numStrings.stream().map(Integer::parseInt).collect(Collectors.toList()).forEach(System.out::println);
        numStrings.stream().map(Integer::parseInt).map(n -> n * n).collect(Collectors.toList()).forEach(System.out::println);
    }

    @Test
    public void filter(){
        List<String> list = Arrays.asList("张三", "李四", "王五", "xuwujing");
        List<String> collect = list.stream().filter(s -> !"李四".equals(s)).collect(Collectors.toList());
        System.out.println(collect);

        String s1 = list.stream().filter(s -> "李四".equals(s)).findAny().orElse("没找到");
        String s2 = list.stream().filter(s -> "李er".equals(s)).findAny().orElse("没找到");
        System.out.println(s1);
        System.out.println(s2);

        int sum = list.stream().filter(s -> "李四".equals(s)).mapToInt(s -> s.length()).sum();
        System.out.println(sum);
    }

    @Test
    public void flatMap() {
        String words = "I come from China and I love China";
        List<String> list = Stream.of(words).flatMap(s -> Stream.of(s.split(" "))).collect(Collectors.toList());
        list.forEach(System.out::println);
    }

    @Test
    public void limit() {
        String words = "I come from China and I love China";
        List<String> list = Stream.of(words).flatMap(s -> Stream.of(s.split(" ")))
                .limit(4)
                .collect(Collectors.toList());
        list.forEach(System.out::println);
    }

    @Test
    public void skip() {
        String words = "I come from China and I love China";
        List<String> list = Stream.of(words).flatMap(s -> Stream.of(s.split(" ")))
                .skip(4)
                .collect(Collectors.toList());
        list.forEach(System.out::println);
    }

    @Test
    public void sort() {
        String[] words = {"I", "come", "from", "China"};
        List<String> col = Stream.of(words).collect(Collectors.toList());
        System.out.println(col);
        col = Stream.of(words).sorted(String::compareTo).collect(Collectors.toList());
        System.out.println(col);
        col = Stream.of(words).sorted((o1, o2) -> o1.compareTo(o2) * -1).collect(Collectors.toList());
        System.out.println(col);
        //先获取在排序效率回更高
        col = Stream.of(words).limit(words.length).sorted(String::compareTo).collect(Collectors.toList());
        System.out.println(col);

        col = Stream.of(words).sorted(Comparator.comparing(String::length).thenComparing(String::hashCode)).collect(Collectors.toList());
        col = Stream.of(words).sorted(Comparator.comparing(String::hashCode).thenComparing(s->s.length()).thenComparing(s -> s.hashCode())).collect(Collectors.toList());
        col = Stream.of(words).sorted(Comparator.comparing((String s) -> s.hashCode()).thenComparing(String::hashCode)).collect(Collectors.toList());
        System.out.println(col);
    }

    @Test
    public void peek() {
        Stream.of("one", "two", "three", "four")
                .filter(e -> e.length() > 3)
                .peek(e -> System.out.println("Filtered value: " + e))
                .map(String::toUpperCase)
                .peek(e -> System.out.println("Mapped value: " + e))
                .collect(Collectors.toList());
    }

    @Test
    public void parallel() {
        List<String> list = Arrays.asList("one", "two", "three", "four");
        long count = list.parallelStream().filter(s -> s.length() > 3).count();
        System.out.println(count);
//        并行执行
        list.parallelStream().peek(s -> System.out.println(Thread.currentThread().getName()+"  --> "+s)).collect(Collectors.toList());
//        单线程执行
        list.stream().peek(s -> System.out.println(Thread.currentThread().getName()+"  ----------  "+s)).collect(Collectors.toList());
    }

    @Test
    public void cal() {
        String[] words = {"I", "come", "from", "China", "and", "I", "love", "China"};
//        max
        int max = Arrays.stream(words).mapToInt(s -> s.length()).max().getAsInt();
        System.out.println("max = " + max);
//        min
        int min = Arrays.stream(words).mapToInt(s -> s.length()).min().getAsInt();
        System.out.println("min = " + min);
//        distinct
        List<String> collect = Arrays.stream(words).map(String::toUpperCase).distinct().collect(Collectors.toList());
        System.out.println("collect = " + collect);
    }

    @Test
    public void match() {
        String[] words = {"I", "come", "from", "China", "and", "I", "love", "China"};
        boolean allMatch = Arrays.asList(words).parallelStream().allMatch(w -> w.length() > 2);
        System.out.println("allMatch = " + allMatch);
        boolean anyMatch = Arrays.asList(words).parallelStream().anyMatch(w -> w.length() > 2);
        System.out.println("anyMatch = " + anyMatch);
        boolean noneMatch = Arrays.asList(words).parallelStream().noneMatch(w -> w.length() > 2);
        System.out.println("noneMatch = " + noneMatch);
    }

    @Test
    public void reduce() {
        Integer reduce = Stream.of(78, 9, 33, 1, 2, 3, 4, 105).reduce(Integer::min).get();
        System.out.println(reduce);

        reduce = Stream.of(78, 9, 33, 1, 2, 3, 4, 5).reduce((a, b)-> {
//            System.out.println(a +" -- "+b);
            return a - b;
        }).get();
        System.out.println(reduce);

        reduce = Stream.of(78, 9, 33, 1, 2, 3, 4, 105).reduce(55, (a, b) -> {
//            System.out.println(a +" -- "+b);
            return Integer.min(a, b);
        });
        System.out.println(reduce);


        reduce = Stream.of(Integer.MAX_VALUE, 1, 3, 5).reduce((a, b) -> {
//            System.out.println(a +" -- "+b);
            return a + b;
        }).get();
        System.out.println(reduce);

        long reduce1 = Stream.of(Integer.MAX_VALUE, 2, 3, 5).reduce(0L, (a, b) -> {
            System.out.println(a +" + "+b);
            return a + b;
        }, (a, b) -> 0L);
        System.out.println(reduce1);
    }


    @Test
    public void iterate() {
        List<Integer> collect = Stream.iterate(2, n -> n + 3).limit(5).collect(Collectors.toList());
        System.out.println("collect = " + collect);
    }

    class User{
        private int id;
        private int index;
        private String name;

        public int getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

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

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

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

    class SupplierTest implements Supplier<User>{

        private int index = 1;
        private Random ran = new Random();

        @Override
        public User get() {
            User user = new User();
            user.setId(ran.nextInt(10));
            user.setIndex(ran.nextInt(20));
            user.setName("name"+ran.nextInt());
            return user;
        }
    }

    @Test
    public void supplier() {
//        必须有limit
        Stream.generate(new SupplierTest()).limit(3)
                .peek(s -> System.out.println(s.getId()+" -- "+s.getName())).collect(Collectors.toList());
    }

    @Test
    public void groupBy() {
        Map<Integer, List<User>> collect = Stream.generate(SupplierTest::new).limit(6)
                .map(SupplierTest::get).collect(Collectors.groupingBy(User::getId));
        collect.forEach((k, v) -> {
            System.out.println(k+":");
            v.forEach(System.out::println);
        });

        Map<Integer, Map<Integer, List<User>>> collect1 = Stream.generate(SupplierTest::new).limit(6)
                .map(SupplierTest::get).collect(Collectors.groupingBy(User::getId, Collectors.groupingBy(User::getIndex)));
        collect1.forEach((k, v) -> {
            System.out.println(k+"----"+v);
        });
    }

    @Test
    public void partitioningBy() {
        Map<Boolean, List<User>> collect = Stream.generate(SupplierTest::new).limit(6)
                .map(SupplierTest::get).collect(Collectors.partitioningBy(u -> u.getId() > 5));
        collect.forEach((k, v) -> {
            System.out.println(k+":");
            v.forEach(System.out::println);
        });

    }

    @Test
    public void summaryStatistics() {
        Integer collect = Stream.generate(SupplierTest::new).limit(4).map(SupplierTest::get)
                .peek(System.out::println).collect(Collectors.summingInt(User::getId));
        System.out.println(collect);

        System.out.println("-----------------------");
        IntSummaryStatistics statistics = Stream.generate(SupplierTest::new).limit(4).mapToInt(s -> s.get().getId())
                .peek(System.out::println).summaryStatistics();
        System.out.println("statistics.getSum() = " + statistics.getSum());
        System.out.println("statistics.getMax() = " + statistics.getMax());
        System.out.println("statistics.getMin() = " + statistics.getMin());
        System.out.println("statistics.getAverage() = " + statistics.getAverage());
        System.out.println("statistics.getCount() = " + statistics.getCount());
    }

    @Test
    public void orElseGet() {
        Integer integer = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0).filter(n -> n > 15).findAny().orElseGet(()-> 56);
        System.out.println(integer);
    }

    @Test
    public void localDate() {
        LocalDate date = LocalDate.now();
        System.out.println("LocalDate.now() = " + date);

        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("LocalDateTime.now() = " + dateTime);
        System.out.println("format = " + dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        System.out.println("plusDays = " + dateTime.plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println("minusHours = " + dateTime.minusHours(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        LocalDateTime of = LocalDateTime.of(2021, 10, 1, 22, 5, 46);

        LocalDate date1 =LocalDate.parse("2021-11-17");
        LocalDate date2 =LocalDate.parse("2022-01-05");
        Period between = Period.between(date1, date2);
        System.out.println(String.format("相差的年:%d, 月: %d, 日:%d", between.getYears(), between.getMonths(), between.getDays()));
        System.out.println("total.YEARS = " + ChronoUnit.YEARS.between(date1, date2));
        System.out.println("total.MONTHS = " + ChronoUnit.MONTHS.between(date1, date2));
        System.out.println("total.DAYS = " + ChronoUnit.DAYS.between(date1, date2));

        LocalDateTime dateTime1 = LocalDateTime.parse("2022-01-17T01:01:00");
        LocalDateTime dateTime2 = LocalDateTime.parse("2022-02-17T23:02:00");
        System.out.println("total.MINUTES = " + ChronoUnit.MINUTES.between(dateTime1, dateTime2));
        System.out.println(31 * 24 * 60 + 22 * 60 + 1);

        Instant inst1 = Instant.now();
        System.out.println("当前时间戳 : " + inst1);
        Instant inst2 = inst1.plus(Duration.ofSeconds(10));
        System.out.println("增加之后的时间 : " + inst2);
        System.out.println("相差毫秒 : " + Duration.between(inst1, inst2).toMillis());
        System.out.println("相毫秒 : " + Duration.between(inst1, inst2).getSeconds());


        Clock clock = Clock.systemUTC();
        System.out.println("当前时间戳:" + clock.millis());
        Clock clock2 = Clock.system(ZoneId.of("Asia/Shanghai"));
        System.out.println("上海此时的时间戳:"+clock2.millis());
        Clock clock3 = Clock.system(ZoneId.of("America/New_York"));
        System.out.println("纽约此时的时间戳:"+clock3.millis());

        ZoneId zoneId= ZoneId.of("America/New_York");
        ZonedDateTime zoneDateTime=ZonedDateTime.now(zoneId);
        System.out.println("纽约此时的时间 : " + zoneDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
        System.out.println("纽约此时的时间和时区: " + zoneDateTime);
    }

}

posted @ 2022-01-26 14:53  一个小学僧  阅读(98)  评论(0编辑  收藏  举报