2

I am trying to sort the map by String values with predicted. For example, I have the next values in my map

message,
message_message1_message2,
message1_message2,

I wanna sort my map by _ symbols in values String. The result should be like this:

message_message1_message2,
message1_message2,
message

I am trying this way:

        myMap.entrySet().stream().sorted((e1, e2) -> {
            String[] firstCompareValue = e1.getKey().split("_");
            String[] secondCompareValue = e2.getKey().split("_");
            return Integer.compare(firstCompareValue.length, secondCompareValue.length);
        }).collect(Collectors.toMap(Map.Entry::getKey, Function.identity()));

and I've got next notification

Redundant 'sorted' call: subsequent 'toMap' call doesn't depend on the sort order

What am I doing wrong? How it can be done?

1 Answer 1

8

The Collectors.toMap() variant you are using creates a HashMap (at least that's the current implementation), so it doesn't preserve the ordering produced by your Stream.

If you produce a LinkedHashMap, it would be preserved:

    myMap.entrySet().stream().sorted((e1, e2) -> {
        String[] firstCompareValue = e1.getKey().split("_");
        String[] secondCompareValue = e2.getKey().split("_");
        return Integer.compare(firstCompareValue.length, secondCompareValue.length);
    }).collect(Collectors.toMap(Map.Entry::getKey,
                                Function.identity(),
                                (v1,v2)->v1,
                                LinkedHashMap::new));

BTW, you are creating a Map<String,Map.Entry<String,String>>, which I'm not sure is what you want. If you want a Map<String,String> change Function.identity() to Map.Entry::getValue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.