Search code examples
listjava-8hashmap

Compare two HashMap in Java


How to fetch the HashMap based on Max-key field

Eaxmple:-

        List<Map<String, Integer>> data = new ArrayList<Map<String, Integer>>();
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("A", 10);
        map1.put("B", 15);
        map1.put("C", 20);

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("A", 20);
        map2.put("B", 30);
        map2.put("C", 50);

        Map<String, Integer> map3 = new HashMap<>();
        map3.put("A", 50);
        map3.put("B", 60);
        map3.put("C", 70);

        data.add(map1);
        data.add(map2);
        data.add(map3);

Here I have 3 maps that I'm storing in the List.

Now I want to filter a map based on max A key value.

In the above map3 A value has the max integer value.

Expected out is:-

In the last only the map3 should present inside the List.

Is it possible to filter using java8?

Any suggestions would be helpful


Solution

  • I finally able to do this with help of comparator

    Here is the code that will filter based filtering based on max date:-

    Result is stored in the firstMap variable...

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Main {
    
        public static void main(String args[]) throws ParseException {
            Map<String, String> s = test();
            System.err.println(s.toString());
    
        }
    
        public static Map<String, String> test() throws ParseException {
            List<Map<String, String>> data = new ArrayList<Map<String, String>>();
            Map<String, String> map1 = new HashMap<>();
            map1.put("A", "2021-03-08");
    
            Map<String, String> map2 = new HashMap<>();
            map2.put("A", "2021-03-23");
    
            Map<String, String> map3 = new HashMap<>();
            map3.put("A", "2021-03-21");
    
            data.add(map1);
            data.add(map2);
            data.add(map3);
    
            SimpleDateFormat si = new SimpleDateFormat("yyyy-MM-dd");
            Date firstMax = si.parse(data.get(0).get("A"));
    
            Map<String, String> firstMap = data.get(0);
    
            for (Map<String, String> map : data) {
    
                Date loopMax = si.parse(map.get("A"));
                if (firstMax.compareTo(loopMax) < 0) {
                    firstMax = loopMax;
                    firstMap = map;
                }
            }
            return firstMap;
    
        }
    }
    

    Output:-

    {A=2021-03-23}