Nick
Nick

Reputation: 147

How to save order of the stream in map

I try to get order map from stream. I have next code:

Map<String, PatternWrapper> regexps = allConfigurations
    .stream()
    .flatMap(configuration -> configuration.getPlugins().stream())
    .sorted(
            (left, right) -> {
                if (left.getType().equals(ObfuscationType.REGEX_BLACKLIST) &&
                        right.getType().equals(ObfuscationType.REGEX_BLACKLIST))
                    return 0;
                else if (left.getType().equals(ObfuscationType.REGEX_BLACKLIST) &&
                        (!right.getType().equals(ObfuscationType.REGEX_BLACKLIST)))
                    return 1;
                else
                    return -1;
            }
    )
//    .sorted(LogConfiguration.Plugin::compareTo)
    .filter(plugin -> (ObfuscationType.REGEX.equals(plugin.getType())
            || ObfuscationType.REGEX_BLACKLIST.equals(plugin.getType())))
    .collect(Collectors.toMap(
            plugin -> plugin.getId(),
            plugin -> new
                    PatternWrapper(plugin.getId(), Pattern.
                    compile(plugin.getValue()))));

return regexps;

Where I try order a stream of the data and I think that map also was ordered. But I was wrong. I think that call collect(Collectors.toMap()) don't save order of the stream. Are there example how I can do that?

Upvotes: 4

Views: 1222

Answers (1)

Thiyagu
Thiyagu

Reputation: 17890

Assuming allConfigurations.stream maintains order as you have told...

You can use the overload of Collectors.toMap that takes a mapSupplier and hence you can pass a LinkedHashMap since that maintains insertion order.

Collectors.toMap(
        plugin -> plugin.getId(),
        plugin -> new
                PatternWrapper(plugin.getId(), Pattern.
                compile(plugin.getValue())),
        (left, right) -> left,
        LinkedHashMap::new);

The third parameter here is a merge function that is used to resolve collisions between values associated with the same key. But that shouldn't be an issue here as you didn't have one in your original code.

Upvotes: 11

Related Questions