简体   繁体   中英

how can we identify a Map object based on its type arguments by its type arguments?

I have a List of objects. Some objects are Map<String, String> and others are Map<String, List<String>> types. I need to group those in to different lists.

Please tell me If there any methods to handle these challenge.

This looked like a fun code challenge. I wrote a small java class demonstrating how you can use 'instanceof' operator to split out these values into separate collections.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Scratch {
    public static void main(String[] args) {
        // test data
        List<Map<String, ?>> mixed = new ArrayList<>();
        Map<String, String> strings = new HashMap<>();
        strings.put("x", "y");
        Map<String, List<String>> lists = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add("z");
        lists.put("w", list);

        mixed.add(strings);
        mixed.add(lists);

        // split out data
        Map<String, String> onlyStrings = new HashMap<>();
        Map<String, List<String>> onlyLists = new HashMap<>();
        for (Map<String, ?> item : mixed) {
            for (Map.Entry<String, ?> entry : item.entrySet()) {
                Object value = entry.getValue();
                if (value instanceof String) {
                    onlyStrings.put(entry.getKey(), (String)entry.getValue());
                } else if (value instanceof List) {
                    onlyLists.put(entry.getKey(), (List<String>)entry.getValue());
                }
            }
        }

        // print out
        System.out.println("---Strings---");
        for (Map.Entry<String, String> entry : onlyStrings.entrySet()) {
            System.out.println(entry);
        }

        System.out.println("---Lists---");
        for (Map.Entry<String, List<String>> entry : onlyLists.entrySet()) {
            System.out.println(entry);
        }
    }
}

Output

---Strings---
x=y
---Lists---
w=[z]

Hope it helps and is what you are after

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM