[英]Java Convert List<String> to Map<String, String>
Is there a nice way to convert/transform a list of Strings (with Collectos API?) into a HashMap? 有没有一种很好的方法将字符串列表(使用Collectos API?)转换/转换为HashMap?
StringList and Map: StringList和Map:
List<String> entries = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
... ...
My StringList contains Strings like: 我的StringList包含如下字符串:
entries.add("id1");
entries.add("name1, district");
entries.add("id2");
entries.add("name2, city");
entries.add("id3");
entries.add("name3");
Output should be: 输出应该是:
{id1=name1, district, id2=name2, city, id3=name3}
Thank you! 谢谢!
You don't need an external library, it's pretty easy: 您不需要外部库,这很简单:
for (int i = 0; i < entries.size(); i += 2) {
map.put(entries.get(i), entries.get(i+1));
}
Or, a more efficient way with non-random access lists would be: 或者,使用非随机访问列表的更有效方法是:
for (Iterator<String> it = entries.iterator(); it.hasNext();) {
map.put(it.next(), it.next());
}
Or, using streams: 或者,使用流:
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));
Andy的答案绝对有效,它是一个不错的三线,但这个答案可能解释了如何使用Stream API)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.