如何实现这个 Map<String, List<>>结构 [封闭]

我有如下数据:

 Key       value
-----      ------
car         toyota
car         bmw
car         honda

fruit       apple
fruit       banana

computer    acer
computer    asus
computer    ibm 
...

(上述数据的每一行都是一个对象,其中包含字段“key”和“value”,全部在一个列表中List<DataObject>)

我想将数据构造如下:Map<String, List<String>>

 "car"      : ["toyota", "bmw", "honda"]
 "fruit"    : ["apple","banana"]
 "computer" : ["acer","asus","ibm"]

如何从数据对象中实现上述结构?Map

******此外******

我更感兴趣的是使用纯JDK提供的类或接口来实现结果,而不是使用外部库。有什么帮助吗?


答案 1
    Map<String, List<String>> myMaps = new HashMap<String, List<String>>();
    for (DataObject item : myList) {
        if (!myMaps.containsKey(item.getKey())) {
            myMaps.put(item.getKey(), new ArrayList<String>());
        }
        myMaps.get(item.getKey()).add(item.getValue());
    }

答案 2

我会使用番石榴实现。但是使用标准的JDK也很容易做到。Multimap

示例标准 JDK:

public static void main(String[] args) {
    Scanner s = new Scanner(
            "car         toyota\n" +
            "car         bmw\n" +
            "car         honda\n" +
            "fruit       apple\n" +
            "fruit       banana\n" +
            "computer    acer\n" +
            "computer    asus\n" +
            "computer    ibm");

    Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();

    while (s.hasNext()) {

        String key = s.next();
        if (!map.containsKey(key))
            map.put(key, new LinkedList<String>());

        map.get(key).add(s.next());
    }

    System.out.println(map);
}

番石榴示例:

public static void main(String[] args) {
    Scanner s = new Scanner(
            "car         toyota\n" +
            "car         bmw\n" +
            "car         honda\n" +
            "fruit       apple\n" +
            "fruit       banana\n" +
            "computer    acer\n" +
            "computer    asus\n" +
            "computer    ibm");

    Multimap<String, String> map = LinkedListMultimap.create();

    while (s.hasNext()) 
        map.put(s.next(), s.next());

    System.out.println(map);
}

输出(两种实现):

{car=[toyota, bmw, honda], fruit=[apple, banana], computer=[acer, asus, ibm]}

推荐