栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 随笔 stream api

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 随笔 stream api

0. 赶紧写完,我要剪头发…

【RUNOOB】Java 8 Stream
【CSDN】java stream中Collectors的用法
【CSDN】java8 Stream的flatMap的使用
【JB51】Java8的Stream()与ParallelStream()的区别说明


gitee中的sample code

1. sample code
// 一个自己封装的json转换工具类而已,无需多虑...
import com.weng.cloud.commons.JsonUtil;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;



public class TestStreamApi {

    private final static List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl","bc");
    private final static List persons = Arrays.asList(
            Person.builder().no(6).name("james").build(),
            Person.builder().no(8).name("williams").build(),
            Person.builder().no(7).name("kd").build(),
            Person.builder().no(8).name("kobe").build(),
            Person.builder().no(35).name("kd").build()
    );

    public static void main(String[] args) {

        //testForEach(testMap());
//        testForEach(strings.stream());

//        testFilter();
//        testForEach(strings.stream());
        //testForEach(testFilter());

        //testIntStream().forEach(System.out::println);

        testCollect();
    }

    
    static void testForEach(Stream stream){
        stream.forEach(System.out::println);
    }

    static Stream testMap(){
        // 返回的是副本
        return strings
                .stream()
                .map(v->"map前缀 -> "+v)
        ;
    }

    static Stream testFilter(){
        return strings
                .stream()
                // :: 相当于 (ele) -> {},即lambda表达式
                // 相当于需要一个 boolean 作为 filter 的参数
                .filter(StringUtils::isNotBlank)
        ;
    }

    
    static IntStream testIntStream(){
        return new Random()
                //元素个数
                // 这波操作同 .ints(10)
                .ints()
                .limit(10)

                .sorted()
        ;
    }

    static void testCollect(){

        


        Map personMap = persons
                .stream()
                .collect(
                        Collectors.collectingAndThen(
                                //do collecting
                                Collectors.toMap(
                                        // stream中有重复的值,则转换会报IllegalStateException异常
                                        // 返回值本身
                                        //Function.identity(),
                                        //Function::identity
                                        Person::getNo,
                                        Person::getName,
                                        //第三个参数mergeFunction,来解决冲突的问题
                                        //java.util.function.BiFunction.apply
                                        //入参是两个value
                                        (item, identicalItem) -> item.length() < identicalItem.length() ? item : identicalItem
                                ),
                                //then...
                                map -> {
                                    map.put(0,"westbrook");
                                    return map;
                                }

                                //这个故事告诉我们,跟stream相关的操作都是副本的

                        )
                )
        ;

        personMap.forEach((k,v)->System.out.println("key="+k+",value="+v));

        System.err.println("map元素个数->"+ personMap.values().stream().count());
        System.err.println("key的总和->"+ personMap
                .keySet()
                .stream()
                .collect(
                        Collectors.summingInt(value -> value)

                        // 返回的结果是一个统计类:
                        // IntSummaryStatistics{count=5, sum=56, min=0, average=11.200000, max=35}
                        //Collectors.summarizingInt(value -> value)

                        // 平均值
                        //Collectors.averagingInt(value -> value)

                        // 最值
                        // 这种情况下返回的结果是Optional[最大的元素]

                )
        );

        //Map<分组key,分组后的集合Collection>
        //像下面这个样例,将返回Map>
        System.err.println("分组后的Map -> "+persons
                .stream()
                .collect(
                        Collectors.groupingBy(
                                Person::getName,
                                Collectors.toSet()
                        )
                )
        );

        //分组可以理解为特殊的分组
        //分组将产生一个Map<过滤条件Boolean,分区后的集合Collection>
        Map> partitionedMap = persons
                .stream()
                .collect(
                        Collectors.partitioningBy(
                                Person::isNoOverTen,
                                Collectors.toMap(
                                        Person::getName,
                                        Person::getNo
                                )
                        )
                )
        ;

        System.err.println("分区后的Map -> "+partitionedMap);

        System.err.println("降维后的map -> "+ JsonUtil.toJson(partitionedMap
                .values()
                .stream()
                .flatMap(map -> map.keySet().stream())
                //stream -> array
                .toArray()
        )
    );
    }

    
    private static int obtainPreInt(int i){
        return Integer.parseInt(String.valueOf(i).substring(0,1));
    }
}

@Data
@AllArgsConstructor
@Builder
//必须要除Object以外的显式父类才能调用父类的...
//@EqualsAndHashCode(callSuper = true)
class Person implements Serializable {
    Integer no;
    String name;

    @Override
    public String toString() {
        return JsonUtil.toJson(this);
    }

    
    public boolean isNoOverTen(){
        return this.no >= 10;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/866946.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号