简体   繁体   中英

Sorting Map<String, List<Object>> using java 8

How can I sort the map using the data from a value Example: Map<String, List<someObject>> is my input. I need to sort and get the order in someObject.getVar2()

Example:

class SomeObject{
    String var1;
    String var2;
    String var3;
    // getters and setters
}

INPUT :

Entry 1:

{
Key1 = 123
[
someObject
[
var1=4
var2=5
var3=6
]
]
}

Entry 2:

{
Key1 = 456
[
someObject
[
var1=2
var2=8
var3=1
]
]
}

Entry 3:

{
Key1 = 789
[
someObject
[
var1=1
var2=2
var3=3
]
]
}

OUTPUT after sorting according to var2:

Entry 1:

{
Key1 = 789
[
someObject
[
var1=1
var2=2
var3=3
]
]
}

Entry 2:

{
Key1 = 123
[
someObject
[
var1=4
var2=5
var3=6
]
]
}

Entry 3:

{
Key1 = 456
[
someObject
[
var1=2
var2=8
var3=1
]
]
}

There are 3 entries in Map with format Map<String, List<someObject>> I need to sort this Map collection with var2 values

Before keys are in: 123,456,789

After sorting keys are in: 789,123,456

What you want is not possible. Looking at the documentation of the Map interface reveals that

[...] Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not. [...]

Your input doesn't really fit in the data structure you've used, ie Map<String, List<SomeObject>> . Since there is never a List there in the values (and if there be, the logic for sorting would have to be redefined.) Hence you could simply represent your current input as a Map<String, SomeObject> :

Map<String, SomeObject> input = new HashMap<>(); // initialised with your sample

and then sort it as:

Map<String, SomeObject> output = map.entrySet()
    .stream()
    .sorted(Comparator.comparing(o -> o.getValue().getVar2())) // **
    .collect(Collectors
        .toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));

** do note that representing Number s(mostly Integer s here) and then sorting based on them is not probably one should desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM