关于列表的排序而不迭代

时间:2012-04-28 04:47:57

标签: java

我有一个数组列表,现在我要对它进行排序,我的arraylist也包含重复元素,重复元素也应该在最终结果排序列表中删除,请指教

 ArrayList list=new ArrayList();
      list.add("Ram");
       list.add("Dinesh");
      list.add("Sachin");
      list.add("Dinesh");

2 个答案:

答案 0 :(得分:1)

如果没有一些迭代,则无法进行排序,但您不必自己进行排序。 尝试使用在插入时排序的排序集,并删除重复项:

list = new ArrayList<String>( new TreeSet<String>(list) );

基本上,您将列表内容放入有序集(在本例中为TreeSet),然后将集合的内容复制回新列表。

答案 1 :(得分:0)

同上。如果要对您创建的对象的集合进行排序,则需要让集合和数组知道如何比较对象。

import java.util.Arrays;

public class delme {
    public static void main(String[] args)
    {

        SomeData[] theData = new SomeData[5];
        theData[0] = new SomeData("zzzz", 1);
        theData[1] = new SomeData("aaaa", 1);
        theData[2] = new SomeData("zzzz", 0);
        theData[3] = new SomeData("aaaa", 0);
        theData[4] = new SomeData("aaaa", 0);

        Arrays.sort(theData);

        for (int i = 0; i < theData.length; i++){
            System.out.println("theData[" + i + "]=" + theData[i].toString());
        }
    }
  }


  public class SomeData implements Comparable {

    public String someData1;
    public int someData2;


    public SomeData(String s, int i) {
        someData1 = s;
        someData2 = i;
    }


    //return -1 if this object should come before the arguments object in a sorted list
    //return 0 if they have the same value
    //return 1 if this object should come after in a sorted list
    public int compareTo(Object arg0) throws ClassCastException {
        if (!(arg0 instanceof SomeData)) //we must accept type Object so lets check to make sure its of type SomeData
            throw new ClassCastException("peram given is not a SomeData object");

        SomeData otherData = (SomeData)arg0; //lets cast it to our data type for ez access
        if (someData2 == otherData.someData2)
            return someData1.compareTo(otherData.someData1);
        return Integer.compare(someData2, otherData.someData2);
    }

    public String toString() {
        return "someData1=" + someData1 + ", someData2=" + someData2;
    }
  }