I have an Map<String,Integer>
which is sorted by value like that
public void sortList(Map<String,Integer> map){
set = map.entrySet();
list = new ArrayList<Map.Entry<String, Integer>>(set);
Collections.sort( list, (o1, o2) -> (o2.getValue()).compareTo( o1.getValue() ));
}
I need to copy all values to new list
word_used = new ArrayList<Integer>(map.values());
but it saves in non-sorted order
When you sort that list
you created from the entrySet
, it doesn't change the order of the entries in the original Map
. You'll have to return the list
from your sortList
method if you want a List
of the sorted values.
map.values()
will not return the values sorted, since the values are not kept in any specific order in the Map
. Some Map
implementations (such as TreeMap
) keep the keys sorted, but not the values.
First extract the list, sort it and then create a new list with it.
List<Integer> tmp = map.values();
Collections.sort(tmp);
word_used = new ArrayList<Integer>(tmp);
word_used = new ArrayList<Integer>(map.values()
.stream()
.sorted()
.collect(Collectors.toList()));
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.