java lambda 表达式,stream的常用接口练习

2019/03/27 11:01
阅读数 23
package com.sjdf.erp.web.test;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

import org.junit.Test;

import com.sjdf.erp.common.utils.PlatformUtils;

/**
 * @category lambda 练习
 * @author lijun
 * create in 2019年3月27日
 */
public class Steamtest {
    private static final Object Person = null;
    @Test
    public  void test3(){
        Instant start = Instant.now();
        long reduce = LongStream.rangeClosed(0, 1)
                .parallel()
                .reduce(0, Long::sum);
        Instant end = Instant.now();
        System.out.println(reduce);
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }

    @Test
    public void test4() throws InterruptedException, ExecutionException {
        List<String> valueList = new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            valueList.add("sku_" + i);
        }
        for (int i = 0; i < 10; i++) {
            valueList.add("meiNv_" + i);
        }
        Instant start1 = Instant.now();
        mutiThreadhandleList(valueList);
        Instant end1 = Instant.now();
        System.out.println("耗时为:" + Duration.between(start1, end1).toMillis());
    } 
    
    /**多线程处理大量list
     * @param valueList
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public void mutiThreadhandleList(List<String> valueList) throws InterruptedException, ExecutionException {
        // 获取核心数
        int num = Runtime.getRuntime().availableProcessors();
        int size = valueList.size();
        // 实际用这个数拆分
        int sizeSplit = size/num + num;
        List<List<String>> spiltList = PlatformUtils.spiltList(valueList, sizeSplit);
        ExecutorService executorService = Executors.newFixedThreadPool(num);
        List<Future<List<String>>> futures = new ArrayList<Future<List<String>>>(num);
        for (List<String> list : spiltList) {
            Callable<List<String>> call = new Callable<List<String>>() {
                @Override
                public List<String> call() throws Exception {
                    // do something
                    List<String> rsList = new ArrayList<String>(list.size());
                    for (String string : list) {
                        Thread.sleep(2);
                        System.out.println(string);
                        rsList.add(string + "sku");
                    }
                    return rsList;
                }
            };
            futures.add(executorService.submit(call));
        }
        List<String> rsList = new ArrayList<String>();
        for (Future<List<String>> future : futures) {
            List<String> list = future.get();
            rsList.addAll(list);
        }
        executorService.shutdown();
        System.out.println(rsList.size());
    }
    
    private List<Person> getListPerson() {
        List<Person> strList = new ArrayList<Person>();
        for (int i = 0; i < 1000; i++) {
            strList.add(new Person("aa" + i, i));
        }
        return strList;
    }

    /**
     * 有返回 的接口
     * 将List<Person> -> List<Student>
     */
    @Test
    public void mapTest() {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        // 根据源码,第一个为参数类型,第二个为返回对象类型
        Function<Person, Student> mapper = p ->{
           // do something
            try {
                Thread.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Student stu = new Student(p.getName(), p.getAge());
            return stu;
        };
        List<Student> rs = listPerson.parallelStream().map(mapper).collect(Collectors.toList());
        System.out.println(rs.size());
        Instant end = Instant.now();
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }
    /**普通写法,,当大量数据操作时,才能体现性能更高
     * 也就是 do something 耗时比较长
     * @throws InterruptedException
     */
    @Test
    public void change() throws InterruptedException {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        List<Student> rs = new ArrayList<>(listPerson.size());
        for (Person person : listPerson) {
            // do something
            Thread.sleep(2);
            rs.add(new Student(person.getName(), person.getAge()));
        }
        System.out.println(rs.size());
        Instant end = Instant.now();
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }
    
    /**
     * 无需返回
     * 将List<Person> 中的人名都加上 sir 串
     */
    @Test
    public void peekTest() {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        Consumer<Person> action = p->{
            p.setName(p.getName() + "sir");
        };
        listPerson.parallelStream().peek(action).count();
        System.out.println(listPerson);
        Instant end = Instant.now();
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }

    /**
     * distinct接口,去重
     */
    @Test
    public void distinctTest() {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,1,2,3,4);
        List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
        // 并行流的写法
        List<Integer> collect2 = list.parallelStream().distinct().collect(Collectors.toList());
        collect.forEach(c-> System.out.println(c));
        collect2.forEach(c-> System.out.println(c));
    }

    /**
     * sorted 接口 排序
     */
    @Test
    public void sortedTest() {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,1,2,3,4);
        List<Integer> collect = list.stream().sorted().collect(Collectors.toList());
        collect.forEach(c-> System.out.println(c));
        
        List<Person> persons = new ArrayList<Steamtest.Person>();
        Random rand = new Random();
        for (int i = 0; i < 10; i++) {
            Person p = new Person("同学 ——" + i, rand.nextInt(100) + 1);
            persons.add(p);
        }
        // 对象排序
        Comparator<Person> comparator = new Comparator<Steamtest.Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                if (o1.getAge() > o2.getAge()) {
                    return 1;
                }
                if (o1.getAge() < o2.getAge()) {
                    return -1;
                }
                return 0;
            }
        };
        List<com.sjdf.erp.web.test.Steamtest.Person> collect2 = persons.stream().sorted(comparator).collect(Collectors.toList());
        collect2.forEach(c-> System.out.println(c.getName() + "--------" + c.getAge()));
    }

    /**
     * limit 接口 : 截取前参数个元素
     * skip 接口 :跳过参数个元素
     */
    @Test
    public void limitTest() {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,1,2,3,4);
        List<Integer> collect = list.stream().limit(3L).collect(Collectors.toList());
        List<Integer> collect2 = list.stream().skip(3L).collect(Collectors.toList());
        collect.forEach(c-> System.out.print(c));
        System.out.println();
        collect2.forEach(c-> System.out.print(c));
    }

    /**
     * max 和min 接口
     * 最大 最小
     */
    @Test
    public void maxMinTest() {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,1,2,3,4);
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 > o2) {
                    return 1;
                }
                if (o2 > o1) {
                    return -1;
                }
                return 0;
            }
        };
        Optional<Integer> min = list.stream().min(comparator);
        Optional<Integer> max = list.stream().max(comparator);
        Integer minrs = min.get();
        Integer maxrs = max.get();
        System.out.println(minrs);
        System.out.println(maxrs);
    }

    /**
     * boolean anyMatch(Predicate<? super T> predicate);
     *  boolean allMatch(Predicate<? super T> predicate);
     *  boolean noneMatch(Predicate<? super T> predicate);
     */
    @Test
    public void testAnyMatch(){
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,1,2,3,4);
        Predicate<Integer> predicate = new Predicate<Integer>() {
            @Override
            public boolean test(Integer t) {
                if (t%2 == 0) {
                    return true;
                }
                return false;
            }
        };
        boolean anyMatch = list.stream().anyMatch(predicate);
        System.out.println(anyMatch);
    }
    
    /**过滤
     * Stream<T> filter(Predicate<? super T> predicate);
     */
    @Test
    public void testName() throws Exception {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,1,2,3,4);
        Predicate<Integer> predicate = new Predicate<Integer>() {
            @Override
            public boolean test(Integer t) {
                if (t%2 == 0) {
                    return true;
                }
                return false;
            }
        };
        List<Integer> collect = list.stream().filter(t->{
            if(t%2==0) {
                return true;
            }
            return false;
        } ).collect(Collectors.toList());
        collect.forEach(e->System.out.println(e));
    }
 
    @Test
    public void test6() {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        List<Person> list = new ArrayList<Steamtest.Person>();
        listPerson.parallelStream().peek(new Consumer<Person>() {

            Object lock = new Object();
            @Override
            public void accept(Person t) {
                t.setName("---");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    list.add(t);
                }
            }
        }).count();
        System.out.println(list.size());
        Instant end = Instant.now();
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }
    @Test
    public void test8() {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        List<Person> list = new ArrayList<Steamtest.Person>();
        listPerson.parallelStream().peek(t -> {
            Object lock = new Object();
            t.setName("---");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock) {
                list.add(t);
            }
        }).count();
        System.out.println(list.size());
        Instant end = Instant.now();
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }
    @Test
    public void test7() {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        List<Person> list = new ArrayList<Steamtest.Person>();
        for (Person person : listPerson) {
            person.setName("----");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            list.add(person);
        }
        System.out.println(list.size());
        Instant end = Instant.now();
        System.out.println("耗时为:" + Duration.between(start, end).toMillis());
    }
    @Test
    public void test9() {
        Instant start = Instant.now();
        List<Person> listPerson = getListPerson();
        Function<Person, Person> func = new Function<Steamtest.Person, Steamtest.Person>() {
            @Override
            public Person apply(Person t) {
                t.setName("----");
                return t;
            }
        };
        List<com.sjdf.erp.web.test.Steamtest.Person> list2 = listPerson.parallelStream().map(func).collect(Collectors.toList());
        System.out.println(list2.size());
        System.out.println(list2);
    }

    public class Person{
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name= name;
            this.age=age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return this.name;
        }
      
    }
    public class Student{
        private String name;
        private int age;
        public Student(String name, int age) {
            this.name= name;
            this.age=age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return this.name;
        }
    }
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部