从HashMap打印具有多个值的单个键

时间:2018-05-02 21:52:27

标签: java oop hashmap

我创建了一个Hashmap,它将股票代码作为关键字存储,并将股票代码关联的ETF存储为值。我现在唯一想弄清楚的是如何打印存储在HashMap中的内容。香港专业教育学院尝试了各种方式给我乱码或NullPointException。下面是我的代码以及我尝试打印HashMap的各种方法:

public static void main(String[] args){

        Map<TickerSymbol, List<ETF>> exampleMap = new HashMap<>();

        // create list one and store values
        List<ETF> setOne = new ArrayList<>();
        setOne.add(new ETF("Number 1", .2, .3, .4, .5, .6));
        setOne.add(new ETF("Number 2", .241, .312, .4312, .5423, .642));
        setOne.add(new ETF("Number 3", .21, .31, .41, .51, .61));    

        // create list two and store values
        List<ETF> setTwo = new ArrayList<>();
        setTwo.add(new ETF("Number 4", .3, .4, .5, .6, .8));
        setTwo.add(new ETF("Number 5", .3524, .442, .542, .665, .80));
        setTwo.add(new ETF("Number 6", .23, .32, .43, .76, .89));

        // create list three and store values
        List<ETF> setThree = new ArrayList<>();
        setThree.add(new ETF("Number 7", .37, .47, .57, .68, .89));
        setThree.add(new ETF("Number 8", .38, .48, .58, .68, .89));
        setThree.add(new ETF("Number 9", .39, .49, .59, .68, .89));

        // put values into map
        exampleMap.put(new TickerSymbol("stockA"), setOne);
        exampleMap.put(new TickerSymbol("stockB"), setTwo);
        exampleMap.put(new TickerSymbol("stockC"), setThree);    


        //gibberish prints out with this one
        for (Map.Entry<TickerSymbol, List<ETF>> entry : exampleMap.entrySet()) {
            TickerSymbol key = entry.getKey();
            List<ETF> values = entry.getValue();
            System.out.println("Key = " + key);
            System.out.println("Values = " + values + "n");
        }


        //gibberish prints out with this one
        for (Map.Entry<TickerSymbol, List<ETF>> entry : exampleMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue().toString());
        }


        //gibberish prints out with this one
        exampleMap.forEach((key, value) -> System.out.println(key + ":" + value));
        System.out.println(exampleMap.keySet().toString());

        //I get a null pointer exception with this one
        Iterator iterator = exampleMap.keySet().iterator();

        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            String value = exampleMap.get(key).toString();

            System.out.println(key + " " + value);
        }

    }

真的希望有人可以在这里帮助我...我完全没有想法。

1 个答案:

答案 0 :(得分:0)

您看到的胡言乱语是ArrayListtoString()的结果(在AbstractCollection中实施)。它在每个存储的元素上调用toString()。在您的情况下,这些元素是ETF的实例。如果您没有覆盖ETF中的toString(),它会继承Object的实现,即:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

所以在ETF中添加toString()方法,比如

@Override
public String toString() {
    return number + " (" + floats + ")";
}
相关问题