[英]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.如何使用值中的数据对地图进行排序 示例: Map<String, List<someObject>>
是我的输入。 I need to sort and get the order in someObject.getVar2()
我需要排序并获取someObject.getVar2()
的顺序
Example:例子:
class SomeObject{
String var1;
String var2;
String var3;
// getters and setters
}
INPUT :输入:
Entry 1:条目 1:
{
Key1 = 123
[
someObject
[
var1=4
var2=5
var3=6
]
]
}
Entry 2:条目 2:
{
Key1 = 456
[
someObject
[
var1=2
var2=8
var3=1
]
]
}
Entry 3:条目 3:
{
Key1 = 789
[
someObject
[
var1=1
var2=2
var3=3
]
]
}
OUTPUT after sorting according to var2:根据var2排序后的OUTPUT:
Entry 1:条目 1:
{
Key1 = 789
[
someObject
[
var1=1
var2=2
var3=3
]
]
}
Entry 2:条目 2:
{
Key1 = 123
[
someObject
[
var1=4
var2=5
var3=6
]
]
}
Entry 3:条目 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 Map 中有 3 个条目,格式为Map<String, List<someObject>>
我需要使用 var2 值对这个 Map 集合进行排序
Before keys are in: 123,456,789钥匙进入前:123,456,789
After sorting keys are in: 789,123,456排序后键在:789,123,456
What you want is not possible.你想要的是不可能的。 Looking at the documentation of the Map
interface reveals that查看Map
界面的文档显示
[...] Some map implementations, like the
TreeMap
class, make specific guarantees as to their order; [...] 一些地图实现,如TreeMap
类,对它们的顺序做出特定保证; others, like theHashMap
class, do not.其他的,比如HashMap
类,没有。 [...] [...]
Your input doesn't really fit in the data structure you've used, ie Map<String, List<SomeObject>>
.您的输入并不适合您使用的数据结构,即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>
:由于值中从来没有List
(如果有,则必须重新定义排序逻辑。)因此,您可以简单地将当前输入表示为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. ** 请注意,表示Number
s(这里主要是Integer
s)然后根据它们进行排序可能不是人们应该想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.