-2

This question already has an answer here:

So I am reading a file and need to count the number of duplicates within that file. I cant store duplicates. I would then need to display the contents of the file based on order of occurrence

My code so far:

    // use hashmap to store the values
    Map<String, Integer> myMap = new HashMap<>();

    // loop through
    for (String line = r.readLine(); line!=null; line = r.readLine()) {
        if (myMap.containsKey(line)) {
            myMap.put(line, myMap.get(line)+1);
        } else {
            myMap.put(line, 1);
        }
    }   

I am storing them in a map because they have unique keys; the problem I am facing is that I need to sort them by the value of the integer from greatest to least.

Example input:

World
World
World
Hello
Hello
Hello
Hello

Expected output:

Hello
World


2 답변


1

You could definitely use a TreeMap, but an easier method would be just exporting to an ArrayList and sorting via comparator if you already have everything working in a HashMap. Here's how you would accomplish this:

//This comparator sorts by HashMap values.
Comparator <Map.Entry<String, Integer>> sortCompare = 
(Map.Entry<String, Integer> firstValue, Map.Entry<String, Integer> secondValue)
   -> secondValue.getValue().compareTo(firstValue.getValue());

//This is the list that will hold each entry from the map.
List<Map.Entry<String, Integer>> orderedList = new ArrayList<>();

//Pulls the data from the existing map.
orderedList.addAll(myMap.entrySet());

//Now all that is left to do is sort with the comparator we made.
Collections.sort(orderedList, sortCompare);

//Now the array list is ordered largest to smallest and you can do whatever with it.

This is the way that I would handle the sorting because I don't particularly like TreeMaps, but you can do some research and work with them if you want to eliminate the HashMap.


0

You can use TreeMap to store unique strings as keys and number of occurrences as values. TreeMap supports custom comparator so you can write logic to sort the each and every entry in the map.

Linked


Related

Latest