dk40149
dk40149

Reputation: 99

How to convert a list of Strings to a LinkedHashMap?

I have a list:

private List <String> list;

I want to convert it to a LinkedHashMap (to preserve order), such that the first two values in the map are a LinkedHashMap entry and so on until the list is a LinkedHashMap:

private LinkedHashMap<String, String> linked;

This is what I have come up with. Admittedly I am new to the Collectors implementations so bear with me:

            linked = list.stream()
                .collect(Collectors.toMap(
                        Function.identity(),
                        String::valueOf, //Used to be String::length
                        LinkedHashMap::new));

this is giving me an error on the LinkedHashMap constructor line:

Cannot resolve constructor of LinkedHashMap

This is an example of what the list may look like:

zero
test0
one
test1
two
test2

and what I want the Map to look like:

zero:test0
one:test1
two:test2

Thanks

Upvotes: 1

Views: 3117

Answers (3)

BENJEBARA Zakaria
BENJEBARA Zakaria

Reputation: 1

This my attempt with java 8.

   IntStream.range(0, list.size())
            .mapToObj(index -> {
                    if (index % 2 == 0) {
                        return new AbstractMap.SimpleImmutableEntry<>(list.get(index), list.get(index + 1));
                    }
                    return null;
                }
            )
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(AbstractMap.SimpleImmutableEntry::getKey, AbstractMap.SimpleImmutableEntry::getValue));

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

You missed merge function:

a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)

But to fill map with your expected values using stream api you can use forEach method and IntStream::iterate from java9

LinkedHashMap<String, String> linked = new LinkedHashMap<>();

IntStream.iterate(0, n -> n < list.size(), n -> n + 2)
        .forEach(i -> linked.put(list.get(i), list.get(i + 1)));

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

Why you complicate your code, a simple loop in your case solve the problem :

for (int i = 0; i < list.size(); i += 2) {
    linked.put(list.get(i), list.get(i + 1));
}

Quick, Ideone demo

Outputs

zero:test0
one:test1
two:test2

Upvotes: 2

Related Questions