雪洗中关村

导航

java8 array、list操作 汇【20】)- (FlatMap)用法汇总

 

public class FlatMapTest {
    public static void main(String[] args) throws IOException {
        FlatMapTest test = new FlatMapTest();
//        test.test1();
//        test.test2();

//        test.test3();
        test.test31();
//        test.test4();


    }


    private void test4() throws IOException {
        // 文件生成流    https://blog.csdn.net/FBB360JAVA/article/details/102072659
        // 遍历每一个单词出现的次数(简单的使用空格切割)
        // 读取txt文件;设置编码格式
        Stream<String> lines = Files.lines(Paths.get("D:\\000temp1\\tes1.txt"), Charset.defaultCharset());
        // 将英文逗号、句号、感叹号全部替换为空格字符串
        lines.map(str -> str.replaceAll("[,]|[.]|[!]", " "))
            .flatMap(line -> Arrays.stream(line.split(" ")))// 按照空格切割字符串
            .filter(str -> !"".equals(str))// 过滤掉包含的空字符串
            .collect(Collectors.groupingBy(String::toString, Collectors.counting()))//使用String的toString方法,获取单词作为map的键;计算个数作为值
            .forEach((k, v) -> System.out.println("k=" + k + ",v=" + v));
    }

    private void test3() throws IOException {
        //Java8中的字数统计
        Map<String, Long> wordCount = Files.lines(Paths.get("D:\\000temp1\\tes1.txt"))
                .parallel()
                .flatMap(line -> Arrays.stream(line.trim().split("\\s")))
                .map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim())
                .filter(word -> word.length() > 0)
                .map(word -> new AbstractMap.SimpleEntry<>(word, 1))
                .collect(groupingBy(AbstractMap.SimpleEntry::getKey, counting()));
        wordCount.forEach((k, v) -> System.out.println(String.format("%s ==>> %d", k, v)));
    }
    private void test31() { //https://blog.csdn.net/mqdxiaoxiao/java/article/details/90315626
        Map.Entry<String,String> entry = new AbstractMap.SimpleEntry<String, String>("name", "野猿新一");
        System.out.println("new AbstractMap.SimpleEntry:-->" + entry);
        System.out.println("getKey:-->" + entry.getKey());
        System.out.println("getValue:-->" + entry.getValue());
        entry.setValue("野猿新二");
        System.out.println("setValue:-->" + entry);
    }

    private void test2() {
        //扁平化流
        //找出数组中唯一的字符
        String[] strArray = {"hello", "world"};

        List<String[]> a = Arrays.stream(strArray)
                .map(word -> word.split(""))
                .distinct()
                .collect(toList());
        a.forEach(obj -> System.out.print(obj));//两个数组[h, e, l]; [o, w, r, d]
        System.out.println("--------------------------------");
        //示意图:https://www.cnblogs.com/wangjing666/p/9999666.html

        //具体实现
        List<String> res = Arrays.stream(strArray)
                .map(w -> w.split(""))
                .flatMap(Arrays::stream)
                .distinct()
                .collect(toList());
        System.out.println("-2-->" + res);//[h, e, l, o, w, r, d]

        //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(toList());
        System.out.println("-3-->" + 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(toList());
        System.out.println("-4-->" + 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(toList());
        System.out.println("-5-->" + res3.size());

//        原文链接:https://blog.csdn.net/ZYC88888/java/article/details/90377010
    }

    private void test1() {
        List<String> teamIndia = Arrays.asList("Virat", "Dhoni", "Jadeja");
        List<String> teamAustralia = Arrays.asList("Warner", "Watson", "Smith");

        List<List<String>> playersInWorldCup2016 = new ArrayList<>();
        playersInWorldCup2016.add(teamIndia);
        playersInWorldCup2016.add(teamAustralia);

        List<String> listOfAllPlayers = new ArrayList<>();
        for (List<String> team : playersInWorldCup2016) {
            for (String name : team) {
                listOfAllPlayers.add(name);
            }
        }

        System.out.println("Players playing in world cup 2016");
        System.out.println("-11-->" + listOfAllPlayers);//[Virat, Dhoni, Jadeja, Warner, Watson, Smith]

        // Now let's do this in Java 8 using FlatMap
        List<String> flatMapList = playersInWorldCup2016.stream()
                .flatMap(pList -> pList.stream())
                .collect(toList());
        System.out.println("-12-->" + flatMapList);//[Virat, Dhoni, Jadeja, Warner, Watson, Smith]
        //https://www.jianshu.com/p/8d80dcb4e7e0
    }

}

 

test.txt

Hello everyone!
my name is feng jin song. I am come from xi'an, i like play pingpong and computer games.
Three month ago,i was leave my university life.
when i walked on the street, i always want see anyone who named xxx.
i also like java.

 

posted on 2020-06-15 16:04  雪洗中关村  阅读(1260)  评论(0编辑  收藏  举报