java8 array、list操作 匯【4】)- Java8 Lambda表達式 函數式編程【思想】


    int tmp1 = 1;           //包圍類的成員變量
    static int tmp2 = 2;    //包圍類的靜態成員變量

    //https://blog.csdn.net/chengwangbaiko/article/details/73477551   https://www.cnblogs.com/newflydd/p/4948575.html
    public static void main(String[] args) throws Exception {
        List<Integer> list = Arrays.asList(100, 200, 300, 400, 500);

        list.forEach(o -> {System.out.println(o);}); //forEach函數實現內部迭代

        System.out.println("1、給出一個String類型的數組,找出其中所有不重復的素數:");
        distinctPrimary("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9");

        System.out.println("2、給出一個String類型的數組,找出其中各個素數,並統計其出現次數:");
        primaryOccurrence("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9");

        System.out.println("3、給出一個String類型的數組,求其中所有不重復素數的和(預定義的reduce操作: 如sum(),max(),min()等。):");
        distinctPrimarySum("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9");
        distinctPrimarySum2("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9");

        System.out.println("4、生成器函數(Generator function):");
        Stream.generate(Math::random).limit(5).forEach(System.out::println);

        System.out.println("5、//3.1、λ表達式的更多用法:");
        // 嵌套的λ表達式
        Callable<Runnable> c1 = () -> () -> { System.out.println("Nested lambda"); };
        c1.call().run();

        // 用在條件表達式中
        Callable<Integer> c2 = true ? (() -> 42) : (() -> 24);
        System.out.println(c2.call());

        // 定義一個遞歸函數
//        private UnaryOperator<Integer> factorial = i -> { return i == 0 ? 1 : i * factorial.apply( i - 1 ); };
//        //...
//        System.out.println(factorial.apply(3));
        System.out.println("6、方法引用(Method reference):");
        /*
        Integer::parseInt //靜態方法引用
        System.out::print //實例方法引用
        Person::new       //構造器引用

        super::toString //引用某個對象的父類方法
        String[]::new //引用一個數組的構造器

        //c1 與 c2 是一樣的(靜態方法引用)
        Comparator<Integer> c2 = (x, y) -> Integer.compare(x, y);
        Comparator<Integer> c1 = Integer::compare;
        List<UserT> persons = new ArrayList<>();
        //下面兩句是一樣的(實例方法引用1)
        persons.forEach(e -> System.out.println(e));
        persons.forEach(System.out::println);

        //下面兩句是一樣的(實例方法引用2)
        persons.forEach(person -> person.eat());
        persons.forEach(Person::eat);

        //下面兩句是一樣的(構造器引用)
        strList.stream().map(s -> new Integer(s));
        strList.stream().map(Integer::new);

        */





    }



    //5、捕獲(Capture)
    /*
    public void testCapture() {
        int tmp3 = 3;       //沒有聲明為final,但是effectively final的本地變量
        final int tmp4 = 4; //聲明為final的本地變量
        int tmp5 = 5;       //普通本地變量

        Function<Integer, Integer> f1 = i -> i + tmp1;
        Function<Integer, Integer> f2 = i -> i + tmp2;
        Function<Integer, Integer> f3 = i -> i + tmp3;
        Function<Integer, Integer> f4 = i -> i + tmp4;
        Function<Integer, Integer> f5 = i -> {
            tmp5  += i; // 編譯錯!對tmp5賦值導致它不是effectively final的
            return tmp5;
        };
        //...
        tmp5 = 9; // 編譯錯!對tmp5賦值導致它不是effectively final的
    }

    */


    //1、給出一個String類型的數組,找出其中所有不重復的素數
    /**
     * 你可能會覺得在這個例子里,List list被迭代了好多次,
     * map,filter,distinct都分別是一次循環,效率會不好。
     * 實際並非如此。這些返回另一個Stream的方法都是“lazy”的,而最后返回最終結果的collect方法則是“eager”的。
     * 在遇到eager方法之前,lazy的方法不會執行。
     *
     * 當遇到eager方法時,前面的lazy方法才會被依次執行。
     * 而且是管道貫通式執行。這意味着每一個元素依次通過這些管道。
     * 例如有個元素“3”,首先它被map成整數型3;
     * 然后通過filter,發現是素數,被保留下來;又通過distinct,
     * 如果已經有一個3了,那么就直接丟棄,如果還沒有則保留。這樣,3個操作其實只經過了一次循環。
     *
     * 除collect外其它的eager操作還有forEach,toArray,reduce等
     */
    public static void distinctPrimary(String... numbers) {
        List<String> l = Arrays.asList(numbers);
        List<Integer> r = l.stream()
                .map(e -> new Integer(e))
//              .map(e -> Integer.parseInt(e))      // 將集合流中的元素一一映射為一個新的元素,並生成到新的輸出流中
                .filter(e ->  isPrime(e))           // 過濾,lambda表達式     .filter(e -> Primes.isPrime(e))
                .distinct()                         // stream的高級方法,去除重復
                .collect(Collectors.toList());      // 將整理好的輸出流收集到新的listInt集合中
        System.out.println("distinctPrimary result is: " + r);
    }

    //2、給出一個String類型的數組,找出其中各個素數,並統計其出現次數
    public static void primaryOccurrence(String... numbers) {
        List<String> l = Arrays.asList(numbers);
        Map<Integer, Integer> r = l.stream()
                .map(e -> new Integer(e))
//              .filter(e -> Primes.isPrime(e))
                .filter(e -> isPrime(e))
                .collect( Collectors.groupingBy(p->p, Collectors.summingInt(p->1)) ); //把結果收集到一個Map中,用統計到的各個素數自身作為鍵,其出現次數作為值。
        System.out.println("primaryOccurrence result is: " + r);
    }

    //3、給出一個String類型的數組,求其中所有不重復素數的和(預定義的reduce操作: 如sum(),max(),min()等。)
    public static void distinctPrimarySum(String... numbers) {
        List<String> l = Arrays.asList(numbers);
        int sum = l.stream()
                .map(e -> new Integer(e))
//                .filter(e -> Primes.isPrime(e))
                .filter(e -> isPrime(e))
                .distinct()
                .reduce(0, (x,y) -> x+y); // equivalent to .sum()  reduce方法用來產生單一的一個最終結果。
        System.out.println("distinctPrimarySum result is: " + sum);
    }
    public static void distinctPrimarySum2(String... numbers) {
        List<String> l = Arrays.asList(numbers);
        int sum = l.stream().map(Integer::new)
//              .filter(Primes::isPrime)
                .filter(e ->  isPrime(e))
                .distinct()
                .mapToInt(item -> item)
                .sum()
                ;
        System.out.println("distinctPrimarySum2 result is: " + sum);
    }

    //3.1、統計年齡在25-35歲的男女人數、比例 (預定義的reduce操作)
    public void boysAndGirls(List<UserT> persons) {
        Map<Integer, Integer> result = persons.parallelStream().filter(p -> p.getAge()>=25 && p.getAge()<=35).
                collect(
                        Collectors.groupingBy(p->p.getSex(), Collectors.summingInt(p->1))
                );
        System.out.print("boysAndGirls result is " + result);
        System.out.println(", ratio (male : female) is " + (float)result.get(UserT.Sex.MALE)/result.get(UserT.Sex.FEMAILE));
    }














    static class UserT {

        public enum Sex {
            MALE("男"),
            FEMAILE("女");

            private String description;

            Sex(String description) {
                this.description = description;
            }

            public String getDescription() {
                return description;
            }

            public void setDescription(String description) {
                this.description = description;
            }

            public static Sex fromName(String name) {
                for (Sex model : Sex.values()) {
                    if (StringUtils.equals(model.name(), name)) {
                        return model;
                    }
                }
                return null;
            }
        }

        String name;
        Integer age;
        Integer sex;

        public Integer getSex() {
            return sex;
        }

        public void setSex(Integer sex) {
            this.sex = sex;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public UserT(String zm) {
            this.name=zm;
        }

        public String getName() {
            return name;
        }

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

 

★、根據條件生成新的 array:

public static void main(String[] args){
        String[] ids={"11","12","13"};
        String[] contents={"a"};

        String[] z1 = new String[0];
        if(ids.length != contents.length){
            int diff = ids.length - contents.length;
            int z0 = diff + contents.length;
            z1 = new String[z0];
            for (int i = 0; i < contents.length; i++) {
                z1[i] = contents[i];
            }
        }
        String[] z3 =  Arrays.stream(z1).map(i -> {
            return i == null ? "" : i;
        }).toArray(String[]::new);
        Arrays.stream(z3).forEach(System.out::println);

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM