简体   繁体   中英

How to sort the elements of an ArrayList according to their ascii values?

I have read a file using Scanner and then used a HashMap and ArrayList to sort the words according to the number of occurrences of words(ascending and descending) and everything is working fine. But I want the output to be sorted in a way that it first displays numbers then uppercase and then lowercase.

Following is my code for the same:

`Scanner scanner = new Scanner(new File("file"));
    Map<String, Integer> map = new HashMap<String, Integer>();
    int count=0;
    String whole="";
    while (scanner.hasNext())
        {
        count++;
        String word = scanner.next();
        whole=whole + " " + word;
        if (map.containsKey(word))
            {
            map.put(word, map.get(word)+1);
            }
        else
            {
            map.put(word, 1);
            }
        }

    List<Map.Entry<String, Integer>> entries = new ArrayList<Entry<String,Integer>>( map.entrySet());

    Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {

        @Override
        public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
            return a.getValue().compareTo(b.getValue());
        }
    });

    System.out.println("Count: " +count);
    System.out.print("Output 1(Ascending): ");
    for(int j = 0; j < map.size(); j++){
        System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
    }

    System.out.print("Output 2(Descending): ");
    for(int i = 0; i < map.size(); i++){
        System.out.println(entries.get(entries.size() - i - 1).getKey()+" "+entries.get(entries.size() - i - 1).getValue());
    }`

My input is:

I have 10 dogs and all the dogs are of different size

And my output is:

Count: 12
Output 1(Ascending): all 1
the 1
size 1
are 1
and 1
of 1
have 1
I 1
different 1
10 1
dogs 2
Output 2(Descending): dogs 2
10 1
different 1
I 1
have 1
of 1
and 1
are 1
size 1
the 1
all 1

Desired output:

dogs 2 \\since it has more number of occurrences than any other word
10 1 \\since it is a number
I 1 \\since it is an uppercase letter
have 1 \\followed by all the lowercase words

I've written a code snippet and the following should work for print the input in ascending order.

String input = "I have 10 dogs and all the dogs are of different size";
String [] inputSplit = input.split(" ");

Map<String, Integer> map = new HashMap<>();

for (int i=0; i < inputSplit.length; i++) {
    String word = inputSplit[i];
    if (map.containsKey(word)) {
        map.put(word,  map.get(word) + 1);
    }
    else {
        map.put(word, 1);
    }
}

List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
    @Override
    public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
        int compareWordCount = a.getValue().compareTo(b.getValue());

        if (compareWordCount == 0) {
            return a.getKey().compareTo(b.getKey());
        }
        return compareWordCount;
    }
});

for (int j=0; j < entries.size(); j++) {
    System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
}

Result

10 1
I 1
all 1
and 1
are 1
different 1
have 1
of 1
size 1
the 1
dogs 2

Update with descending sort

String input = "I have 10 dogs and all the dogs are of different size";

String [] inputSplit = input.split(" ");

Map<String, Integer> map = new HashMap<>();

for(int i = 0; i < inputSplit.length; i++){
    String word = inputSplit[i];
    if(map.containsKey(word)){
        map.put(word,  map.get(word) + 1);
    }
    else{
        map.put(word, 1);
    }
}

List<Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());

Comparator <Entry<String, Integer>> ascComparator = new Comparator<Entry<String, Integer>>(){

    @Override
    public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {

        int compareWordCount = a.getValue().compareTo(b.getValue());

        if(compareWordCount == 0){
            return a.getKey().compareTo(b.getKey());
        }
        return compareWordCount;
    }

};

Comparator <Entry<String, Integer>> descComparator = new Comparator<Entry<String, Integer>>(){

    @Override
    public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {

        int compareWordCount = a.getValue().compareTo(b.getValue());

        if(compareWordCount == 0){
            return b.getKey().compareTo(a.getKey());
        }
        return compareWordCount;
    }

};

System.out.println("Ascending Sort");
Collections.sort(entries, ascComparator);       
for(int j = 0; j < entries.size(); j++){
    System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
}

System.out.println("\nDescending Sort");
Collections.sort(entries, descComparator);

for(int j = 0; j < entries.size(); j++){
    System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
}

Results

Ascending Sort
10 1
I 1
all 1
and 1
are 1
different 1
have 1
of 1
size 1
the 1
dogs 2

Descending Sort
the 1
size 1
of 1
have 1
different 1
are 1
and 1
all 1
I 1
10 1
dogs 2

you can extend your comparison logic to add ascii sort logic as well

        public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
            int i = a.getValue().compareTo(b.getValue());
            if(i==0) {
                i = b.getKey().compareTo(a.getKey());
            }
            return i;
        }

Hope this helps.

Just update your compare method part:

    Scanner scanner = new Scanner(new File("file"));
    Map<String, Integer> map = new HashMap<String, Integer>();
    int count=0;
    String whole="";
    while (scanner.hasNext())
        {
        count++;
        String word = scanner.next();
        whole=whole + " " + word;
        if (map.containsKey(word))
            {
            map.put(word, map.get(word)+1);
            }
        else
            {
            map.put(word, 1);
            }
        }

    List<Map.Entry<String, Integer>> entries = new ArrayList<Entry<String,Integer>>( map.entrySet());

    Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {

        @Override
        public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
            int compareResult = a.getValue().compareTo(b.getValue());
            if (compareResult != 0) {
                return compareResult;
            } else {
                //Here, when the occurance numbers are equal, then compare
                //with the key values where the texts are stored
                return a.getKey().compareTo(b.getKey());
            }
        }
    });

    System.out.println("Count: " +count);
    System.out.print("Output 1(Ascending): ");
    for(int j = 0; j < map.size(); j++){
        System.out.println(entries.get(j).getKey()+" "+entries.get(j).getValue());
    }

    System.out.print("Output 2(Descending): ");
    for(int i = 0; i < map.size(); i++){
        System.out.println(entries.get(entries.size() - i - 1).getKey()+" "+entries.get(entries.size() - i - 1).getValue());
    }

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