• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

Java8特性03-关于Stream中Map和FlatMap必知点

Java基础学习 来源:xiakexiaohu 3次浏览
package chap03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


public class FlatMap {
    public static void main(String[] args) {
        //扁平化流
        //找出数组中唯一的字符
        String[] strArray = {"hello", "world"};

        //具体实现
        List<String> res = Arrays.stream(strArray)
                .map(w -> w.split(""))
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toList());
        System.out.println(res);

        //TODO 案例
        System.out.println("--------------------------------");
        //Demo1:给定数组,返回数组平方和(直接使用映射)
        //[1,2,3,4]=>[1,4,9,16]
        Integer[] nums1 = {1, 2, 3, 4};
        List<Integer> nums1List = Arrays.asList(nums1);
        List<Integer> res1 = nums1List.stream().map(i -> i * i).collect(Collectors.toList());
        System.out.println(res1);

        System.out.println("--------------------------------");
        //Demo2:给定两数组,返回数组对
        //[1,2,3],[3,4]=>[1,3],[1,4],[2,3],[2,4],[3,3],[3,4]
        Integer[] nums2 = {1, 2, 3};
        Integer[] nums3 = {3, 4};
        List<Integer> nums2List = Arrays.asList(nums2);
        List<Integer> nums3List = Arrays.asList(nums3);

        //使用2个map嵌套过滤
        List<int[]> res2 = nums2List.stream().flatMap(i -> nums3List.stream().map(j -> new int[]{i, j})).collect(Collectors.toList());
        System.out.println(res2.size());

        System.out.println("--------------------------------");
        //Demo3:针对Demo2和Demo1组合返回总和能被3整除的数对
        //(2,4)和(3,3)是满足条件的
        List<int[]> res3 = nums2List.stream().flatMap(i -> nums3List.stream().filter(j -> (i + j) % 3 == 0).map(j -> new int[]{i, j})).collect(Collectors.toList());
        System.out.println(res3.size());


    }
}

控制台输出结果:

总结:关于流的具体应用测试如下:

Trasaction类:

package chap03.StreamDemo;

public class Transaction {
    private final Trader trader;
    private final int year;
    private final int value;

    public Transaction(Trader trader, int year, int value) {
        this.trader = trader;
        this.year = year;
        this.value = value;
    }

    public Trader getTrader() {
        return trader;
    }

    public int getYear() {
        return year;
    }

    public int getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "{"+this.trader+","+this.year+","+this.value+"}";
    }
}

Trader类:

package chap03.StreamDemo;

public class Trader {
    private final String name;
    private final String city;

    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Trder:" + this.name + " in " + this.city;
    }
}

Main测试主类:

package chap03.StreamDemo;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Main {
    public static void main(String[] args) {
        Trader raoul = new Trader("Raou1", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");

        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

        //1.找出2011年的所有交易并按交易额排序(从低到高)
        List<Transaction> tr2011 = transactions.stream().filter(transaction -> transaction.getYear() == 2011)
                                                        .sorted(Comparator.comparing(Transaction::getValue))
                                                        .collect(toList());
        System.out.println(tr2011);

        //2.交易员都在哪些不同城市工作过
        List<String> cities = transactions.stream().map(transaction -> transaction.getTrader().getCity())
                                                    .distinct()
                                                    .collect(toList());
        System.out.println(cities);

        //3.查找所有来自剑桥的交易员,并按姓名排序
        List<Trader> traders = transactions.stream().map(Transaction::getTrader)
                                    .filter(trader -> trader.getCity().equals("Cambridge"))
                                    .distinct()
                                    .sorted(comparing(Trader::getName))
                                    .collect(toList());
        System.out.println(traders);

        //4.返回所有交易员的姓名字符串,按字母顺序排序
        String traderStr = transactions.stream().map(transaction -> transaction.getTrader().getName())
                .distinct()
                .sorted()
                .reduce("", (str1, str2) -> str1 + str2);
        System.out.println(traderStr);
        //因为上述存在a和b字符串反复拼接比较,所以改进方案如下:
        String traderStr2 = transactions.stream().map(transaction -> transaction.getTrader().getName())
                .distinct()
                .sorted()
                .collect(joining());

        //5.有没有交易员是在米兰工作的
        boolean milanBased = transactions.stream()
                .anyMatch(transaction -> transaction.getTrader().getCity().equals("Milan"));
        System.out.println(milanBased);

        //6.打印生活在剑桥的交易员的所有交易额
        transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
                            .map(Transaction::getValue)
                            .forEach(System.out::println);

        //7.所有交易中,最高的交易额是多少?
        Optional<Integer> highestValue = transactions.stream().map(Transaction::getValue).reduce(Integer::max);
        System.out.println(highestValue);

        //8.找到交易额最小的交易
        Optional<Integer> smallestValue = transactions.stream().map(Transaction::getValue).reduce(Integer::min);
        //或者,Optional为容器类
        Optional<Transaction> smallestValue2 = transactions.stream().reduce((t1, t2) -> t1.getValue() < t2.getValue() ? t1 : t2);
        System.out.println(smallestValue);
        System.out.println(smallestValue2);
    }
}

 


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)