gpt4 book ai didi

java - 在 Java 中使用 for 循环打印 TreeMap

转载 作者:行者123 更新时间:2023-11-29 06:44:06 24 4
gpt4 key购买 nike

我使用以下代码:

public void showTablet () {
for (Map.Entry<String, Tablet> entry : tableMap.entrySet()) {
System.out.println(entry.toString());
}
}

结果是:

MyBrand : A123=Brand: MyBrand, Model no.:A123, Price:3000.0
BrandTwo : T222=Brand: BrandTwo, Model no.:T222, Price:2500.0

我想要的结果

Brand: MyBrand, Model no.:A123, Price:3000.0
Brand: BrandTwo, Model no.:T222, Price:2500.0

为什么key也打印出来了?

最佳答案

因为您正在打印一个 Map.Entry,其中包含键和值。

如果你只想要值,你可以使用Map.EntrygetValue()方法:

System.out.println(entry.getValue()); // will call toString by default

这是假设 Tablet 有一个正确覆盖的 toString 方法,当然(如果我正确理解你的输出,它似乎有)。

关于java - 在 Java 中使用 for 循环打印 TreeMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7962430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com