【问题标题】:how can we identify a Map object based on its type arguments by its type arguments?我们如何通过类型参数根据其类型参数来识别 Map 对象?
【发布时间】:2018-09-12 07:28:05
【问题描述】:

我有一个List 的对象。有些对象是Map<String, String>,有些是Map<String, List<String>> 类型。我需要将它们分组到不同的列表中。

请告诉我是否有任何方法可以处理这些挑战。

【问题讨论】:

  • 我怀疑这是 XY 问题的一个实例。请先阅读xyproblem.info,然后重新表述问题。
  • 好消息@HonzaZidek。 Sukumar,您使用此变量映射列表解决的实际问题是什么?

标签: java generics collections


【解决方案1】:

这看起来像是一个有趣的代码挑战。我编写了一个小型 Java 类,演示如何使用“instanceof”运算符将这些值拆分为单独的集合。

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);
        }
    }
}

输出

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

希望它有所帮助,并且是你所追求的

【讨论】:

  • 太棒了……!感谢您分享您的知识..!真的很有帮助..!下次当我遇到类似的挑战时,我一定会像你一样想解决这个问题:)
猜你喜欢
  • 2021-12-26
  • 2021-11-06
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多