简体   繁体   English

在java中按字典(按字母顺序)排序

[英]Sorting in lexicographic (alphabetical) order in java

I have a for-loop that prints the data. 我有一个打印数据的for循环。 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); 我应该将数据放入列表中并使用Collections.sort(list); ? In this case the numbers are not in the necessary position. 在这种情况下,数字不在必要的位置。

PS Actually this is a small part of a homework, but I do not know how to solve this. PS:实际上,这只是家庭作业的一小部分,但我不知道该如何解决。

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 . 然后,您可以将Data实例放在ArrayList并使用Collections.sort

*for java users *对于Java用户

put your data into a hashmap(yourMap). 将您的数据放入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) );

You could also use an implementation of Map , for example a TreeMap , using the character as the Key and the number as the Value . 您还可以使用Map的实现,例如TreeMap ,使用字符作为Key ,将数字作为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. 从那里,您可以使用键并以排序的顺序获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM