javajava-8java-streamstreamex

Create a Map with SimpleEntry and StreamEx


I saw an example of StreamEx which is quite nice and which goes like this

    Map<String, String> toMap = StreamEx.of(splittedTimeUnit1)
            .pairMap((s1, s2) -> s1.matches("-?\\d+(\\.\\d+)?") ? new String[]{s2, s1} : null)
            .nonNull()
            .toMap(a -> a[0], a -> a[1]);

This works well an my output is {seconds=1, minutes=1} which is ok. Not perfect cause I have to convert the number later on.

I tried to optimize with SimpleEntry<String,Integer>:

    Map<String, String> toMap2 = StreamEx.of(splittedTimeUnit1)
            .pairMap((s1, s2) -> s1.matches("-?\\d+(\\.\\d+)?") ? new SimpleEntry<>(s1,s2) : null)
            .nonNull()
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

which compiles but now I have the problem, that some values are put multiple times into the map which leads to an:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key minutes

How can I fix this?

EDIT

Stupid Mistake: I forgot to switch s1 and s2 at the second example

Map<String, String> toMap2 = StreamEx.of(splittedTimeUnit1)
                    .pairMap((s1, s2) -> s1.matches("-?\\d+(\\.\\d+)?") ? new SimpleEntry<>(s2,s1) : null)
                    .nonNull()
                    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

Solution

  • The statement seems to be correct, I think the problem was, that I forgot to switch s1 and s2. If I switch them everything works as expected, thank you.