美文网首页Java8 Lambda
Java8 Stream和Lambda函数式编程Demo

Java8 Stream和Lambda函数式编程Demo

作者: 依然慢节奏 | 来源:发表于2019-11-13 10:22 被阅读0次
    ///Java对象类
    package cn.missbe.random.demo.study;
    
    import com.xiaoleilu.hutool.util.RandomUtil;
    
    public class Dish {
        public enum Level{DIET,NORMAL,FAT}
        public enum Type{MEAT,FISH,OTHER}
        private final String name = RandomUtil.randomString(7);
        private final int calories;
        private final boolean vegetarian;
        private final Type type;
    
        public Dish(int calories, boolean vegetarian, Type type) {
            this.calories = calories;
            this.vegetarian = vegetarian;
            this.type = type;
        }
    
        public boolean isVegetarian() {
            return vegetarian;
        }
    
        public Type getType() {
            return type;
        }
    
        public int getCalories() {
            return calories;
        }
    
        public String getName() {
            return name;
        }
    
        @Override
        public String toString() {
            return "Dish{" +
                    "name='" + name + '\'' +
                    ", calories=" + calories +
                    ", vegetarian=" + vegetarian +
                    ", type=" + type +
                    '}';
        }
    }
    
    
    //JUnit测试
    package cn.missbe.random.demo.study;
    
    import com.sun.org.apache.xpath.internal.operations.Bool;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.util.*;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    import java.util.stream.Stream;
    
    public class DishTest {
        List<Dish> menu;
    
        @Before
        public void before(){
            menu = new ArrayList<>();
            menu.add(new Dish(24,true, Dish.Type.FISH ));
            menu.add(new Dish(34, true, Dish.Type.MEAT ));
            menu.add(new Dish(34, false, Dish.Type.OTHER ));
            menu.add(new Dish(22, true, Dish.Type.MEAT ));
            menu.add(new Dish(65, false, Dish.Type.FISH ));
            menu.add(new Dish(565,true, Dish.Type.OTHER  ));
            menu.add(new Dish(565, false, Dish.Type.FISH ));
            menu.add(new Dish(55, true, Dish.Type.FISH ));
            menu.add(new Dish(595, false, Dish.Type.MEAT ));
        }
        @Test
        public void oldMethod(){
            List<Dish> lowCaloricDisher = new ArrayList<>();
            for(Dish d : menu){
                if(d.getCalories() < 400){
                    lowCaloricDisher.add(d);
                }
            }
            System.out.println(lowCaloricDisher);
        }
        @Test
        public void optional(){
            Comparator<Dish> dishCaloriesComparator = Comparator.comparing(Dish::getCalories);
            Optional<Dish> mostCalorieDish = menu.stream().max(dishCaloriesComparator);
            mostCalorieDish.ifPresent(System.out::println);
        }
        @Test
        public void streamTest(){
            Predicate<Dish> predicate = d->d.getCalories() < 400;
            List<Integer> lowCaloricDisher = menu.stream().filter(predicate.negate())
                    .sorted(Comparator.comparing(Dish::getCalories))
                    .map(Dish::getCalories)
                    .collect(Collectors.toList());
            System.out.println(lowCaloricDisher);
            String names = menu.parallelStream().filter(predicate)
                    .map(Dish::getName)
                    .collect(Collectors.joining(","));
            System.out.println("name:" + names);
        }
        @Test
        public void parallelStreamTest(){
            Predicate<Dish> predicate = d->d.getCalories() < 400;
            List<Integer> lowCaloricDisher = menu.parallelStream().filter(predicate.negate())
                    .sorted(Comparator.comparing(Dish::getCalories))
                    .map(Dish::getCalories)
                    .distinct()
                    .skip(1)
                    .limit(2)
                    .collect(Collectors.toList());
            System.out.println(lowCaloricDisher);
            long count = menu.parallelStream().filter(d->d.getCalories() < 400)
                    .distinct()
                    .limit(3)
                    .count();
            System.out.println(count);
        }
        @Test
        public void consumer(){
            List<String> title = Arrays.asList("java8", "in", "action");
            Stream<String> s = title.stream();
            s.forEach(System.out::println);
            //流只能消费一次
            //stream has already been operated upon or closed
            s.forEach(System.out::println);
        }
        @Test
        public void map_reduce(){
            List<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian)
                    .collect(Collectors.toList());
            System.out.println(vegetarianMenu);
            int totalCalories = menu.stream().map(Dish::getCalories).reduce(0, (i, j) -> j + j);
            System.out.println(totalCalories);
        }
    
        private Dish.Level getLevel(Dish dish) {
            if(dish.getCalories() <= 400)
                return Dish.Level.DIET;
            else if(dish.getCalories() <= 500){
                return Dish.Level.NORMAL;
            }else{
                return Dish.Level.FAT;
            }
        }
        @Test
        public void group(){
            //一级分类
            Map<Dish.Type, List<Dish>> dishesByType = menu.stream().collect(Collectors.groupingBy(Dish::getType));
            System.out.println(dishesByType);
            Map<Dish.Level,List<Dish>> dishesByLevel = menu.stream().collect(Collectors.groupingBy(this::getLevel));
            System.out.println(dishesByLevel);
            ///二级分类
            Map<Dish.Type,Map<Dish.Level,List<Dish>>> dishesByTypeLevel = menu.stream().collect(Collectors.groupingBy(Dish::getType,Collectors.groupingBy(this::getLevel)));
            System.out.println(dishesByTypeLevel);
            ///按子组收集类别多少
            Map<Dish.Type, Long> typesLong = menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.counting()));
            System.out.println(typesLong);
        }
        @Test
        public void partitioned(){
            Map<Boolean, List<Dish>> partitionedMenu = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian));
            System.out.println(partitionedMenu);
            Map<Boolean, Long> partitionedCount = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian, Collectors.counting()));
            System.out.println(partitionedCount);
        }
        @Test
        public void primeTest(){
            Map<Boolean, List<Integer>> primeMap = partitionPrimes(100);
            System.out.println(primeMap);
        }
    
        private boolean isPrime(int candidate){
            return IntStream.range(2,candidate).noneMatch(i->candidate % i==0);
        }
        public Map<Boolean,List<Integer>> partitionPrimes(int n){
            return IntStream.rangeClosed(2, n).boxed()
                    .collect(Collectors.partitioningBy(this::isPrime));
        }
        @Test
        public void peek(){
            List<Integer> numbers = Arrays.asList(2, 3, 4, 5);
            List<Integer> result =
                    numbers.stream()
                            .peek(x -> System.out.println("from stream: " + x))
                            .map(x -> x + 17)
                            .peek(x -> System.out.println("after map: " + x))
                            .filter(x -> x % 2 == 0)
                            .peek(x -> System.out.println("after filter: " + x))
                            .limit(3)
                            .peek(x -> System.out.println("after limit: " + x))
                            .collect(Collectors.toList());
            System.out.println(result);
        }
    
    }
    
    image.gif image image.gif

    相关文章

      网友评论

        本文标题:Java8 Stream和Lambda函数式编程Demo

        本文链接:https://www.haomeiwen.com/subject/taqhictx.html