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

java 8 stream Collectors .toMap

Java基础 来源:学要无止尽 2次浏览

 

去重复,当出现相同的key,已后来的值替换

package com.cainiao.xg.lable.pojo.valueobject.v1;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;

/**
 * 描述:
 *
 * @author:  创建: 2017-12-07
 */
public class AnnotateDataVO implements Serializable {
    private static final long serialVersionUID = -7362393752729246320L;
    @Getter
    @Setter
    private Properties properties;

    @Getter
    @Setter
    public static class Properties {
        //对应配置文件中的数据库 类型 ID
        private Integer labelCode;
        //追踪ID
        private Integer trackId;
    }

    public static List<AnnotateDataVO> distinctByTrackId(List<? extends AnnotateDataVO> uniqTrackList) {
        if (uniqTrackList == null) {
            uniqTrackList = Lists.newArrayList();
        }
        Map<Integer, AnnotateDataVO> uniqMap = uniqTrackList.stream().collect(
            Collectors
                .toMap(vo -> vo.getProperties().getTrackId(), Function.identity(), (oldValue, newValue) -> newValue));

        return uniqMap.values().stream().collect(Collectors.toList());
    }

    /*public static void main(String[] args) {
        AnnotateDataVO data1=new AnnotateDataVO();
        Properties properties1=new Properties();
        properties1.setTrackId(1);
        data1.setProperties(properties1);

        AnnotateDataVO data2=new AnnotateDataVO();
        Properties properties2=new Properties();
        properties2.setTrackId(1);
        data2.setProperties(properties2);


        AnnotateDataVO data3=new AnnotateDataVO();
        Properties properties3=new Properties();
        properties3.setTrackId(2);
        data3.setProperties(properties3);


        AnnotateDataVO data4=new AnnotateDataVO();
        Properties properties4=new Properties();
        properties4.setLabelCode(11);
        properties4.setTrackId(1);
        data4.setProperties(properties4);

        List uniqTrackList=Lists.newArrayList(data1,data2);
        List<? extends AnnotateDataVO> needDistinctList=Lists.newArrayList(data3,data4);
        uniqTrackList.addAll(needDistinctList);
        System.out.println(JSON.toJSONString(distinctByTrackId(uniqTrackList)));

    }*/

}

 


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