java 8 stream Collectors .toMap

 

去重复,当出现相同的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 distinctByTrackId(List uniqTrackList) {
        if (uniqTrackList == null) {
            uniqTrackList = Lists.newArrayList();
        }
        Map 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 needDistinctList=Lists.newArrayList(data3,data4);
        uniqTrackList.addAll(needDistinctList);
        System.out.println(JSON.toJSONString(distinctByTrackId(uniqTrackList)));

    }*/

}

 

你可能感兴趣的:(JAVA基础)