Search code examples
javacollectionsmappingunique

How do you map unique values from a list of maps to a new list of maps in Java?


I have a list of maps

List<Map<String, Object>> myList = [{value1=3, value2=11},{value1=8, value2=16},{value1=3, value2=11},{value1=10, value2=11} ...]

and I want to extract value2 to a new list of maps but have only unique values there:

List<Map<String, Object>> res = [{value2=11},{value2=16} ...]

What id the best way to do it?


Solution

  • Try this. Here first I am creating a list of Entry<value2, anyUniqueValue> by using 2 functions. First filtering only those Entries which has key value2 by using function filterFunction

    Secondly by filtering unique value by using function distinctByValue

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.function.Function;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
    
    public class Demo{
    
    public static void main(String[] args) {
        List<Map<String, Object>> myList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("value1", 3);
        map1.put("value2", 11);
    
        Map<String, Object> map2 = new HashMap<>();
        map2.put("value1", 8);
        map2.put("value2", 16);
    
        Map<String, Object> map3 = new HashMap<>();
        map3.put("value1", 3);
        map3.put("value2", 11);
    
        Map<String, Object> map4 = new HashMap<>();
        map4.put("value1", 10);
        map4.put("value2", 11);
    
        myList.add(map1);
        myList.add(map2);
        myList.add(map3);
        myList.add(map4);
    
        List<Entry<String, Object>> list = myList.stream().flatMap(map -> map.entrySet().stream())
                .filter(s -> filterFuction(s)).filter(distinctByValue(entry -> entry.getValue()))
                .collect(Collectors.toList());
    
        List<Map<String, Object>> list1 = list.stream().map(t -> {
            Map<String, Object> map = new HashMap<>();
            map.put(t.getKey(), t.getValue());
            return map;
        }).collect(Collectors.toList());
        System.out.println(list1);
    }
    
    public static <T> Predicate<T> distinctByValue(Function<? super T, ?> keyExtractor) {
    
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    
    public static boolean filterFuction(Entry<String, Object> entry) {
        if (entry.getKey().equals("value2"))
            return true;
        return false;
     }
    
    }