tofacebook.com -专业IT技术社区(指牛堂) List<Map> 获取key重复数据及过滤对应key重复数据 - 指牛堂-专业IT技术平台
213°

List<Map> 获取key重复数据及过滤对应key重复数据

今天主要是给大家分析下: List<Map> 获取key重复数据及过滤对应key重复数据

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

public class StreamEx{
    //过滤重复数据
    public static  Predicate distinctByKey (Function keyExtractor){
        Map seen = new ConcurrentHashMap<>();
        return t->seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)==null;
    }
    //获取重复数据
    public static  Predicate getdistinctByKey (Function keyExtractor){
        Map seen = new ConcurrentHashMap<>();
        return t->seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)!=null;
    }
    public static void main(String[] args) {
        
        List<Map> list = new ArrayList<Map>();
        
        Map  map1 = new HashMap<String,String>();
        map1.put("ywxh","123");
        map1.put("quantity",10);
        map1.put("amount",100);
        
        Map map2 = new HashMap<>();
        map2.put("ywxh","223");
        map2.put("quantity",15);
        map2.put("amount",150);
        Map map3 = new HashMap<>();
        map3.put("ywxh","123");
        map3.put("quantity",5);
        map3.put("amount",50);
        
        list.add(map1);
        list.add(map2);
        list.add(map3);
        
        list.stream().filter(StreamEx.distinctByKey(map->((Map) map).get("ywxh")))
        .forEach(
                
                map->{
            System.out.println(map.toString());
        });
    }
}

//可见上述代码打印了去重后的数据信息。
//获取重复的数据只需要StreamEx中的
//returnt->seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)==null;
//改为
//returnt->seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)!=null;

已有 0 条评论

    我有话说: