简体   繁体   中英

How to refactor this Java code so it creates a String List of key:value pairs as opposed to printing them out?

So I saw some code online that I implemented into my program to sort a hashmap<String, int> based on the values of the integers, and it works successfully but only outputs the values, I need to store the values into a String list but don't understand the code well enough to do this and have been failing repeatedly, it is confusing me to have so many brackets.

If anyone could point me in the right direction that'd be helpful, I don't even know what to google to find out how to do this, thanks.

public List<String> getMaxList(int n, HashMap<String, Integer> itemCount){
        List<Map.Entry<String, Integer>> maxList = new ArrayList<>();
        Object[] a = itemCount.entrySet().toArray();
        int n_iterator = n-1;

        Arrays.sort(a, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Map.Entry<String, Integer>) o2).getValue()
                     .compareTo(((Map.Entry<String, Integer>) o1).getValue());
            }
        });

        for (Object e : a) {
            System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
                    + ((Map.Entry<String, Integer>) e).getValue());
            if (n_iterator <= 0){
                break;
            } else {
                n_iterator--;
            }
        }
        return null;
    }
}

How to refactor this Java code so it creates a String List of key:value pairs as opposed to printing them out? Try it like this.

Create some data

Map<String, Integer> map =
        Map.of("A", 10, "B", 3, "C", 8, "D", 2);

Now stream the map's entry set. Sort based on the value and convert the entry to a String:int string and put in a list.

List<String> list = map.entrySet().stream()
        .sorted(Entry.comparingByValue()))
        .map(e -> e.getKey() + ":" + e.getValue())
        .collect(Collectors.toList());

System.out.println(list);

Prints

[D:2, B:3, C:8, A:10]

To sort in descending order, change the above sort method to

.sorted(Entry.<String,Integer>comparingByValue().reversed())

Note that the Entry comparator had to be witnessed with the types as the compiler could not discern them to properly apply the reversed() method. The above simply reverses the natural sorting order for Integers which is ascending.

Finally, not all objects provide methods that return comparators, so the following would also have worked.

.sorted(Comparator.comparing(Entry::getValue,
                      Comparator.reverseOrder()))

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