Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. In a simple console app test on my desktop, the counter is preserving the order of the list. Can we be sure the order will always be preserved when executed anywhere else?
  2. Is there a better way to code this?
like image 700
Romonov Avatar asked Jun 15 '26 07:06

Romonov


1 Answers

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:

  • The Merge function (a, b) -> a is not really contributing to this.
  • The supplier of LinkedHashMap::new ensures order is retained. Unfortunately, there is not a Collector.toMap that permits a Supplier without the merge function.
like image 83
WJS Avatar answered Jun 16 '26 20:06

WJS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!