I use the code to Sort the data in the map.
我使用代码对地图中的数据进行排序。
Map<Integer, Integer> map = new HashMap<>();
List list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
return a.getValue() - b.getValue();
}
});
I just copy the data from map to List and sort it. How can I get the data from the List? The method get() of list returns just the object, not my 2 integers
我只是将数据从map复制到List并对其进行排序。如何从列表中获取数据? list的get()方法只返回对象,而不是我的2个整数
2 个解决方案
#1
1
You do that :
你做吧 :
List list = new ArrayList(map.entrySet());
You could use generics in your list and then iterate on the Entry
of the list after your sorted it:
您可以在列表中使用泛型,然后在排序之后迭代列表的条目:
List<Entry<Integer, Integer>> list = new ArrayList(map.entrySet());
...
// your sort the list
..
// you iterate on key-value
for (Entry<Integer, Integer> entry : list){
Integer key = entry.getKey();
Integer value = entry.getValue();
}
#2
1
Your list
actually contains elements of type Map.Entry<Integer, Integer>
, so you can retrieve the each Entry
as shown below:
您的列表实际上包含Map.Entry
Map<Integer, Integer> map = new HashMap<>();
//add the values to map here
//Always prefer to use generic types shown below (instead of raw List)
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> a,
Map.Entry<Integer, Integer> b){
return a.getValue() - b.getValue();
}
});
//loop over the list to retrieve the list elements
for(Map.Entry<Integer, Integer> entry : list) {
System.out.println(entry.getValue());
}
#1
1
You do that :
你做吧 :
List list = new ArrayList(map.entrySet());
You could use generics in your list and then iterate on the Entry
of the list after your sorted it:
您可以在列表中使用泛型,然后在排序之后迭代列表的条目:
List<Entry<Integer, Integer>> list = new ArrayList(map.entrySet());
...
// your sort the list
..
// you iterate on key-value
for (Entry<Integer, Integer> entry : list){
Integer key = entry.getKey();
Integer value = entry.getValue();
}
#2
1
Your list
actually contains elements of type Map.Entry<Integer, Integer>
, so you can retrieve the each Entry
as shown below:
您的列表实际上包含Map.Entry
Map<Integer, Integer> map = new HashMap<>();
//add the values to map here
//Always prefer to use generic types shown below (instead of raw List)
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> a,
Map.Entry<Integer, Integer> b){
return a.getValue() - b.getValue();
}
});
//loop over the list to retrieve the list elements
for(Map.Entry<Integer, Integer> entry : list) {
System.out.println(entry.getValue());
}