如何按字母顺序对列表进行排序?

时间:2009-04-02 07:42:15

标签: java list sorting collections alphabetical

我有一个包含国家/地区名称的List<String>对象。如何按字母顺序对此列表进行排序?

14 个答案:

答案 0 :(得分:192)

假设这些是字符串,请使用方便的静态方法sort ...

 java.util.Collections.sort(listOfCountryNames)

答案 1 :(得分:137)

Collections.sort

的解决方案

如果您被迫使用该列表,或者您的程序具有类似

的结构
  • 创建列表
  • 添加一些国家/地区名称
  • 将它们排序一次
  • 再也不会更改该列表
然后Thilos的回答将是最好的方式。如果你将它与 Tom Hawtin - tackline 的建议结合起来,你得到:

java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

使用TreeSet的解决方案

如果您可以自由决定,并且您的应用程序可能会变得更复杂,那么您可能会更改代码以使用TreeSet。这种集合在插入时对您的条目进行排序。无需调用sort()。

Collection<String> countryNames = 
    new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.

关于为什么我更喜欢TreeSet

的旁注

这有一些微妙但重要的优点:

  • 它只是更短。但是只有一条线更短。
  • 永远不要担心这个列表现在真正排序因为无论你做什么,TreeSet总是排序。
  • 您不能有重复的条目。根据您的情况,这可能是专业人士或骗子。如果您需要重复,请坚持列表。
  • 一位经验丰富的程序员会查看TreeSet<String> countyNames并立即知道:这是一个没有重复的字符串的排序集合,我可以确定每时每刻都是如此。简短声明中的大量信息。
  • 在某些情况下真正的表现胜利。如果您使用List并经常插入值,并且可以在这些插入之间读取列表,则必须在每次插入后对列表进行排序。该集合也是如此,但速度要快得多。

使用正确的集合来完成正确的任务是编写简短和无错误代码的关键。在这种情况下,它不是示范性的,因为您只需保存一行。但我已经停止计算,当他们想要确保没有重复项时,我会看到有人使用List,然后自己构建该功能。或者更糟糕的是,当你真的需要Map时使用两个列表。

不要误会我的意思:使用Collections.sort不是错误或缺陷。但是在很多情况下,TreeSet更加清晰。

答案 2 :(得分:25)

您可以使用Java 8 Stream或Guava创建新的排序副本:

// Java 8 version
List<String> sortedNames = names.stream().sorted().collect(Collectors.toList());
// Guava version
List<String> sortedNames = Ordering.natural().sortedCopy(names); 

另一种选择是通过Collections API进行就地排序:

Collections.sort(names);

答案 3 :(得分:23)

迟到总比没有好!以下是我们如何做到这一点(仅限学习目的) -

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class SoftDrink {
    String name;
    String color;
    int volume; 

    SoftDrink (String name, String color, int volume) {
        this.name = name;
        this.color = color;
        this.volume = volume;
    }
}

public class ListItemComparision {
    public static void main (String...arg) {
        List<SoftDrink> softDrinkList = new ArrayList<SoftDrink>() ;
        softDrinkList .add(new SoftDrink("Faygo", "ColorOne", 4));
        softDrinkList .add(new SoftDrink("Fanta",  "ColorTwo", 3));
        softDrinkList .add(new SoftDrink("Frooti", "ColorThree", 2));       
        softDrinkList .add(new SoftDrink("Freshie", "ColorFour", 1));

        Collections.sort(softDrinkList, new Comparator() {
            @Override
            public int compare(Object softDrinkOne, Object softDrinkTwo) {
                //use instanceof to verify the references are indeed of the type in question
                return ((SoftDrink)softDrinkOne).name
                        .compareTo(((SoftDrink)softDrinkTwo).name);
            }
        }); 
        for (SoftDrink sd : softDrinkList) {
            System.out.println(sd.name + " - " + sd.color + " - " + sd.volume);
        }
        Collections.sort(softDrinkList, new Comparator() {
            @Override
            public int compare(Object softDrinkOne, Object softDrinkTwo) {
                //comparision for primitive int uses compareTo of the wrapper Integer
                return(new Integer(((SoftDrink)softDrinkOne).volume))
                        .compareTo(((SoftDrink)softDrinkTwo).volume);
            }
        });

        for (SoftDrink sd : softDrinkList) {
            System.out.println(sd.volume + " - " + sd.color + " - " + sd.name);
        }   
    }
}

答案 4 :(得分:9)

使用Collections.sort的两个参数。您需要一个合适的Comparator来处理适当的案例(即词法,而不是UTF16排序),例如可通过java.text.Collator.getInstance获得的。

答案 5 :(得分:7)

除非您使用无重音英语对字符串进行排序,否则您可能希望使用Collator。它会正确排序变音符号,可以忽略大小写和其他语言特定的东西:

Collections.sort(countries, Collator.getInstance(new Locale(languageCode)));

您可以设置collator strength,请参阅javadoc。

这是斯洛伐克的一个例子:

List<String> countries = Arrays.asList("Slovensko", "Švédsko", "Turecko");

Collections.sort(countries);
System.out.println(countries); // outputs [Slovensko, Turecko, Švédsko]

Collections.sort(countries, Collator.getInstance(new Locale("sk")));
System.out.println(countries); // outputs [Slovensko, Švédsko, Turecko]

答案 6 :(得分:5)

以下是您要找的内容

listOfCountryNames.sort(String::compareToIgnoreCase)

答案 7 :(得分:4)

通过使用Collections.sort(),我们可以对列表进行排序。

public class EmployeeList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<String> empNames= new ArrayList<String>();

        empNames.add("sudheer");
        empNames.add("kumar");
        empNames.add("surendra");
        empNames.add("kb");

        if(!empNames.isEmpty()){

            for(String emp:empNames){

                System.out.println(emp);
            }

            Collections.sort(empNames);

            System.out.println(empNames);
        }
    }
}

输出:

sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]

答案 8 :(得分:4)

在一行中,使用Java 8:

list.sort(Comparator.naturalOrder());

答案 9 :(得分:2)

降序字母:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

答案 10 :(得分:2)

您可以使用以下行

require('./bootstrap'); window.Vue = require('vue'); Vue.component('example-component', require('./components/ExampleComponent.vue').default); const app = new Vue({ el: '#app', });

类似于Thilo的建议,但不会区分大小写字符。

答案 11 :(得分:0)

//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) {

List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee)synchronizedListOne).name
.compareTo(((Employee)synchronizedListTwo).name);
}
}); 
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/

// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}

}
}
class Employee {
String name;
Employee (String name) {
this.name = name;

}
}

答案 12 :(得分:0)

JAVA 8中的相同: -

//Assecnding order
        listOfCountryNames.stream().sorted().forEach((x) -> System.out.println(x));

//Decending order
        listOfCountryNames.stream().sorted((o1, o2) -> o2.compareTo(o1)).forEach((x) -> System.out.println(x));

答案 13 :(得分:-11)

您可以尝试使用我制作的方法。

String key - 将是您想要的订单,在这种情况下按字母顺序排列。只需输入“abc ......”。

String list[] - 您要使用密钥按顺序放置的列表。

int index - 设置为0,将设置密钥的偏移量。

    public static String[] order(String key, String list[], int index) {
    ArrayList<String> order_List = new ArrayList<String>();
    ArrayList<String> temp_Order_List = null;
    char[] key_char = key.toCharArray();
    for (int offset = 0; offset < key_char.length; offset++) {
        if (key_char.length >= offset + index) {
            String str = (index > 1 ? list[0].substring(0, index - 1) : "")
                    + new String(key_char, offset, 1);
            for (int i = 0; i < list.length; i++) {
                temp_Order_List = new ArrayList<String>();
                for (int k = 0; k < list.length; k++) {
                    if (!order_List.contains(list[k])
                            && !temp_Order_List.contains(list[k])) {
                        if (list[k].equalsIgnoreCase(str))
                            order_List.add(list[k]);
                        else if (list[k].toLowerCase().startsWith(str.toLowerCase())) {
                            temp_Order_List.add(list[k]);

                        }
                    }
                }
                if (temp_Order_List.size() > 0) {
                    if (temp_Order_List.size() > 1) {
                        String[] add = order(key,
                                temp_Order_List.toArray(new String[temp_Order_List
                                        .size()]), index + 1);
                        for (String s : add) {
                            order_List.add(s);
                        }
                    } else {
                        order_List.add(temp_Order_List.get(0));
                    }
                }
            }
        }
    }
    return order_List.toArray(new String[order_List.size()]);
}
相关问题