2

I have to store values into a list/map which contains three values:

size  |   amount |  description
2,34  |     4    |  "I'm a long String"
1,14  |     2    |  "I'm another long String"

So I thought about using a nested Map like :

        Map<Double, Map<Integer,String>> a = new HashMap<Double, Map<Integer,String>>();

But how can I easy add entries to that Map? Syntax like

a.put(1,43, new Map.Entry<>(7,"9890"));

didn't work, cause Map is abstract. What is the best way to get my nested Map?

4

3 回答 3

3

这将是乏味的:

Map<Integer,String> val1 = a.get(2.34);
if (val1 == null) {
    val1 = new TreeMap<Integer, String>();
    a.put(2.34, val1);
}
val1.put(4, "I'm a long String");

我已将其更新为 TreeMap,因为您想访问最小的元素。您还应该将地图“a”也更改为 TreeMap。

编辑 2

我在这里努力了,希望这是你要找的:)

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {

    public static void main(String[] args) throws IOException {
        TreeMap<Double, TreeMap<Integer, String>> map = new TreeMap<>();
        add(2.5, 5, "wrong value 1", map);
        add(3, 2, "wrong value 2", map);
        add(2.5, 3, "good value", map);

        System.out.println(map.pollFirstEntry().getValue().pollFirstEntry().getValue());
    }
    public static void add(double val1, int val2, String val3, TreeMap<Double, TreeMap<Integer, String>> map) {
        TreeMap<Integer,String> subMap = map.get(val1);
        if (subMap == null) {
            subMap = new TreeMap<Integer, String>();
            map.put(val1, subMap);
        }
        subMap.put(val2, val3);
    }

}
于 2013-05-13T17:35:06.790 回答
1

只需定义一个 Entry 类:

final class Entry {
    final int amount;
    final String description;

    Entry(final int amount, final String description) {
        // check parameters
        this.amount = amount;
        this.description = description;
    }


    // implement getAmount
    // implement getDescription
}

地图的类型是

Map<Double, Entry>
于 2013-05-13T17:33:46.280 回答
0

正如@Sotirios Delimanolis 提到的,您应该为您的三人组创建课程并根据您的需要选择集合。如果您只想存储您的对象,然后可能会遍历它们,请使用List. 如果您必须允许使用简单或复杂的唯一键访问您的对象Map

但要小心:永远不要Double用作Map. 两个“相等”的类型值double在实践中可能不相等,因此您将获得重复的条目。

于 2013-05-13T17:34:24.830 回答