Divide the map into two lists

I have one Map<String,Integer>, and it is sorted by value as follows:

set = map.entrySet();
list = new ArrayList<Map.Entry<String, Integer»(set);
Collections.sort( list, (o1, o2) -> (o2.getValue()).compareTo( o1.getValue() ));

I already have a sorted integer list from this map:

word_used = new ArrayList<Integer>(map.values() 
.stream() 
.sorted() 
.collect(Collectors.toList())); 
Collections.reverse(word_used); 

But how can I get a list of strings that will be sorted equal to Map (by value)?

I mean, if I have a map with elements:

map.put("eggs",1500); 
map.put("echo",150); 
map.put("foo",320); 
map.put("smt",50); 

and sort it as:

eggs : 1500 
foo : 320 
echo : 150 
smt : 50 

I need to get 2 lists:

eggs 
foo 
echo 
smt

and

1500 
320 
150 
50
+4
source share
4 answers

You can add a projection to your threads using map(), for example:

List<String> word_used = map.entrySet() 
        .stream() 
        .sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed())
        .map(Map.Entry<String,Integer>::getKey)
        .collect(Collectors.toList());

List<Integer> ints_used = map.entrySet() 
        .stream() 
        .sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed())
        .map(Map.Entry<String,Integer>::getValue)
        .collect(Collectors.toList());

Demo 1

Note that this approach is sorted twice. You can capture records once and then design from this temporary list, for example:

List<Map.Entry<String,Integer>> sortedList = map
        .entrySet() 
        .stream() 
        .sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed())
        .collect(Collectors.toList());

List<String> word_used = sortedList
        .stream()
        .map(Map.Entry<String,Integer>::getKey)
        .collect(Collectors.toList());

List<Integer> ints_used = sortedList
        .stream()
        .map(Map.Entry<String,Integer>::getValue)
        .collect(Collectors.toList());

Demo 2

+3

List ( List) Entry s, . , List . , , :

List<String> words = new ArrayList<>();
List<Integer> values = new ArrayList<>();

for (Map.Entry<String, Integer> entry : list) {
    words.add(entry.getKey());
    values.add(entry.getValue());
}
+2

You can sort and repeat only once using this method:

    List<String> word_used = new ArrayList<String>();
    List<Integer> ints_used = map.entrySet().stream() 
        .sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed())
        .peek(e -> word_used.add(e.getKey()))
        .map(Map.Entry::getValue)
        .collect(Collectors.toList());
0
source

You can use TreeMap with a comparator that compares values, not keys, and then just calls the keys () and values ​​().

See: https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

0
source

All Articles