Java转换列表<;字符串>;映射<;字符串,字符串>;

Java转换列表<;字符串>;映射<;字符串,字符串>;,java,list,collections,hashmap,java-stream,Java,List,Collections,Hashmap,Java Stream,是否有一种很好的方法将字符串列表(使用CollectosAPI)转换成HashMap 字符串列表和映射: List<String> entries = new ArrayList<>(); HashMap<String, String> map = new HashMap<>(); 输出应为: {id1=name1, district, id2=name2, city, id3=name3} 谢谢大家! 您不需要外部库,它非常简单: for (

是否有一种很好的方法将字符串列表(使用CollectosAPI)转换成HashMap

字符串列表和映射:

List<String> entries = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
输出应为:

{id1=name1, district, id2=name2, city, id3=name3}

谢谢大家!

您不需要外部库,它非常简单:

for (int i = 0; i < entries.size(); i += 2) {
  map.put(entries.get(i), entries.get(i+1));
}
for(int i=0;i
或者,使用非随机访问列表的更有效方法是:

for (Iterator<String> it = entries.iterator(); it.hasNext();) {
  map.put(it.next(), it.next());
}
for(Iterator it=entries.Iterator();it.hasNext();){
map.put(it.next(),it.next());
}
或者,使用流:

IntStream.range(0, entries.size() / 2)
    .mapToObj(i -> new SimpleEntry<>(entries.get(2*i), entries.get(2*i+1))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
IntStream.range(0,entries.size()/2)
.mapToObj(i->newSimpleEntry(entries.get(2*i),entries.get(2*i+1))
.collect(Collectors.toMap(条目::getKey,条目::getValue));

Andy的答案肯定有效,它是一个很好的三行程序,但是可能会解释如何使用Stream API来实现它。

只需迭代列表(在第2步中)并将所有内容放入地图中即可。这只是两行代码。这肯定回答了OP的问题,但我说问题是XY问题,首先谢谢你的及时回复!我还尝试了前两种选择。我想知道是否还有其他方法,比如你的第三个解决方案。@Malsor前两个选项比第三个更可取:它们清晰、高效且惯用。你可以(使用特定答案下的“共享”链接)。
IntStream.range(0, entries.size() / 2)
    .mapToObj(i -> new SimpleEntry<>(entries.get(2*i), entries.get(2*i+1))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));