我是Java的新手,所以请耐心等待。
我有一个列表的HashMap。
static Map<Integer, List<String>> contactList = new HashMap<Integer, List<String>>();
我正在迭代HashMap的每个条目并使用:
显示它for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
现在,entry.getValue()是我的列表存储的位置,但我只想要这些列表的第一,第二和第三个条目。我相信我需要在迭代之前将列表分配给它自己的对象,但我似乎无法从HashMap中提取列表。
输出必须显示HashMap的每个条目,包括它的键,但只显示列表的前3个项目。
答案 0 :(得分:5)
只需打印subList
而无需修改数据:
System.out.println(entry.getKey() + " - " + entry.getValue().subList(0, 3));
假设,您的列表包含2个以上元素,否则您可以使用Math.min(3, entry.getValue().size())
(如评论中所述)以避免IndexOutOfBoundsException
。
因此,
System.out.println(entry.getKey() + " - " + entry.getValue().subList(0, Math.min(3, entry.getValue().size())));
答案 1 :(得分:2)
你可以这样做。我已经精心设计,以帮助您更好地理解。这段代码可以缩短
Map<Integer, List<String>> contactList = new HashMap<Integer, List<String>>();
for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) {
Integer integer = entry.getKey();
List<String> list = entry.getValue();
//first item
String first = list.get(0);
//second item
String second = list.get(1);
//third item
String third = list.get(2);
}
希望它有所帮助!
答案 2 :(得分:1)
下面的代码可以为您提供所需的内容。
for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) {
List<String> values = entry.getValue();
StringBuilder builder = new StringBuilder(entry.getKey()).append(" - ");
// here I assume the values list is never null, and we pick at most the first 3 entries
builder.append("[")
for (int i = 0; i < Math.min(3, values.size()); i++) {
if (i > 0) builder.append(", ");
builder.append(values.get(i));
}
builder.append("[");
System.out.println(builder.toString());
}
它的作用是,对于地图中的每个条目:
List<String>
)StringBuilder
以在条目如果您考虑一下,肯定会有一种更优雅的方式,这只是解决您问题的快速基本解决方案。
答案 3 :(得分:0)
这样的事情怎么样:
String result = "";
List<String> strings = entry.getValue();
for (int i = 0; i < strings.size(); i++)
{
result += strings.get(i);
}
答案 4 :(得分:0)
我的朋友,你可以通过
来做到这一点 Map<Integer, List<String>> contactList = new HashMap<Integer, List<String>>();
for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) {
List<String> list = entry.getValue();
String firstItem = list.get(0);
String secondItem = list.get(1);
String thirdItem = list.get(2);
}