[英]Convert List<String> to Map<String, String> in Java
I want to convert a list to a map where the key is just a counter and it needs to adhere to the order of the list.我想将列表转换为地图,其中键只是一个计数器,它需要遵守列表的顺序。 I currently have this code:
我目前有这个代码:
private static Map<String, String> convertListToMap(final List<String> list) {
AtomicInteger counter = new AtomicInteger(0);
Map<String, String> map = list.stream().collect(Collectors.toMap((c) -> {
Integer integer = counter.incrementAndGet();
return integer.toString();
}, (c) -> c));
return map;
}
I have two questions:我有两个问题:
Try it this way.试试这个方法。
static Map<String, String> convert(List<String> list) {
return IntStream.range(0, list.size()).boxed()
.collect(Collectors.toMap(n -> String.valueOf(n+1), list::get,
(a, b) -> a, LinkedHashMap::new));
}
Notes:笔记:
(a, b) -> a
is not really contributing to this.(a, b) -> a
并没有真正对此做出贡献。LinkedHashMap::new
ensures order is retained. LinkedHashMap::new
的供应商确保保留订单。 Unfortunately, there is not a Collector.toMap
that permits a Supplier
without the merge
function.Collector.toMap
允许没有merge
功能的Supplier
。Probably you can use IntStream
to map index as key to value, and use LinkedHashMap
for preserving order可能您可以使用
IntStream
将索引映射为值的键,并使用LinkedHashMap
保留顺序
IntStream.range(0, list.size())
.mapToObj(i -> new AbstractMap.SimpleEntry<>(String.valueOf(i+1), list.get(i)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> 1, LinkedHashMap::new));
Regarding your first question: As long as your number will not change, your order would be preserved.关于您的第一个问题:只要您的号码不变,您的订单就会保留。 A better solution would be a LinkedList ( https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html ) where entries are ordered by the sequence you add them (It may be easier, I do not know your application).
更好的解决方案是 LinkedList ( https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html ),其中条目按您添加的顺序排序(这可能更容易,我不知道你的申请)。
Regarding your second question: The AtomicInteger mainly advances due to better thread safety ( Performance Difference of AtomicInteger vs Integer ).关于你的第二个问题: AtomicInteger 的进步主要是由于更好的线程安全性( AtomicInteger 与 Integer 的性能差异)。 If you are not performing any concurrent operations there should be no noticable difference.
如果您没有执行任何并发操作,则应该没有明显差异。 Therefore one could use a normal Integer.
因此可以使用普通的整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.