1

I have a for-loop that prints the data. In the first position is a letter and in the second is number. Like this:

H 8
T 3
A 9
F 4

How can I sort this data in lexicographic (alphabetical) (key is a letter) order? Output must be:

A 9
F 4
H 8
T 3

Should I put the data into the list and use Collections.sort(list);? In this case the numbers are not in the necessary position.

P.S Actually this is a small part of a homework, but I do not know how to solve this.

1

3 Answers 3

3

If you define your data type as:

class Data implements Comparable<Data> {
     private char letter;
     private int number;

     public int compareTo(Data d) {
        if(letter > d.letter) return 1;
        if(letter < d.letter) return -1;
        return 0;
     }
}

Then you can put your Data instances in an ArrayList and use Collections.sort.

0

You could also use an implementation of Map, for example a TreeMap, using the character as the Key and the number as the Value. That way you don't have to encapsulate the character and the number in one object and still keep the mapping.

This answer to another question shows how to get the keys from that map in a sorted order. From there, you can use the keys and get the values in a sorted order as well.

0

*for java users

put your data into a hashmap(yourMap).

HashMap<Integer,String> map = new HashMap<Integer,String>();
youMap.put(H,8);
youMap.put(T,3);
youMap.put(A,9);
youMap.put(F,4);



List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);

for(String key: sortedKeys){
system.out.println(key+" "+yourMap.get(key) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.