Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何对集合进行排序<;T>;?_Java_Sorting_Collections - Fatal编程技术网

Java 如何对集合进行排序<;T>;?

Java 如何对集合进行排序<;T>;?,java,sorting,collections,Java,Sorting,Collections,我有一个通用的集合,我正在尝试如何对其中包含的项目进行排序。我尝试了一些方法,但都无法奏效。下面是一个例子。(为了方便起见,我使用Apache提供的CompareToBuilder类,尽管这可以不用它来完成。) import java.util.ArrayList; 导入java.util.Calendar; 导入java.util.Collections; 导入java.util.Comparator; 导入java.util.Date; 导入java.util.HashMap; 导入java

我有一个通用的
集合
,我正在尝试如何对其中包含的项目进行排序。我尝试了一些方法,但都无法奏效。

下面是一个例子。(为了方便起见,我使用Apache提供的
CompareToBuilder
类,尽管这可以不用它来完成。)

import java.util.ArrayList;
导入java.util.Calendar;
导入java.util.Collections;
导入java.util.Comparator;
导入java.util.Date;
导入java.util.HashMap;
导入java.util.List;
导入org.apache.commons.lang.builder.CompareToBuilder;
公共类测试员{
布尔升序=真;
公共静态void main(字符串参数[]){
测试仪=新测试仪();
tester.printValues();
}
public void printValues(){
列表=
新的ArrayList();
哈希映射=
新的HashMap();
put(“actionId”,新整数(1234));
put(“eventId”,新的整数(21));
map.put(“fromDate”,getDate(1));
地图放置(“toDate”,getDate(7));
列表。添加(地图);
map=新的HashMap();
put(“actionId”,新的整数(456));
put(“eventId”,新的整数(11));
map.put(“fromDate”,getDate(1));
map.put(“toDate”,getDate(1));
列表。添加(地图);
map=新的HashMap();
put(“actionId”,新整数(1234));
put(“eventId”,新的整数(20));
map.put(“fromDate”,getDate(4));
map.put(“toDate”,getDate(16));
列表。添加(地图);
map=新的HashMap();
put(“actionId”,新整数(1234));
put(“eventId”,新的整数(22));
map.put(“fromDate”,getDate(8));
地图放置(“toDate”,getDate(11));
列表。添加(地图);
map=新的HashMap();
put(“actionId”,新整数(1234));
put(“eventId”,新的整数(11));
map.put(“fromDate”,getDate(1));
地图放置(“toDate”,getDate(10));
列表。添加(地图);
map=新的HashMap();
put(“actionId”,新整数(1234));
put(“eventId”,新的整数(11));
map.put(“fromDate”,getDate(4));
地图放置(“toDate”,getDate(15));
列表。添加(地图);
map=新的HashMap();
put(“actionId”,新整数(567));
put(“eventId”,新的整数(12));
map.put(“fromDate”,getDate(-1));
map.put(“toDate”,getDate(1));
列表。添加(地图);
System.out.println(“\n排序前\n”);
对于(int j=0;j

如果你有一个特定的代码,你正在工作,并有问题,你可以张贴你的伪代码,我们可以尝试帮助你

如果你只有t,那就不行了。它必须由提供程序注入:

Collection<T extends Comparable>

集合
没有排序,因此想要对其进行排序是没有意义的。您可以对
列表
实例和数组进行排序,执行排序的方法是和

集合本身没有预定义的顺序,因此必须将它们转换为 a
java.util.List
。然后可以使用一种形式的
java.util.Collections.sort

Collection< T > collection = ...;

List< T > list = new ArrayList< T >( collection );

Collections.sort( list );
 // or
Collections.sort( list, new Comparator< T >( ){...} );

// list now is sorted
CollectionCollection=。。。;
ListList=newarraylist(集合);
集合。排序(列表);
//或
排序(列表,新的比较器({…});
//列表现在已排序

java.util.Collections提供了两个基本选项:

    • 如果
      T实现了可比较的
      ,并且您对这种自然排序很满意,请使用此选项
    • 如果您想提供自己的
      比较器
      ,请使用此选项

根据
集合
是什么,您还可以查看
分类数据集
分类地图
如果您的集合对象是列表,我将使用其他答案中建议的排序方法

但是,如果它不是列表,并且您并不真正关心返回的集合对象的类型,我认为创建树集而不是列表会更快:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

假设您有一个Person类型的对象列表,使用Lambda表达式,您可以对用户的姓氏进行排序,例如,执行以下操作:

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

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }
导入java.util.array;
导入java.util.Collections;
英普
TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }
List<ThirdPartyClass> tpc = getTpcList(...);
//Sort ThirdPartyClass based on the value of some attribute/function
Collections.sort(tpc, Compare3rdPartyObjects.tpcComp);
public abstract class Compare3rdPartyObjects {

public static Comparator<ThirdPartyClass> tpcComp = new Comparator<ThirdPartyClass>() {

    public int compare(ThirdPartyClass tpc1, ThirdPartyClass tpc2) {

        Integer tpc1Offset = compareUsing(tpc1);
        Integer tpc2Offset = compareUsing(tpc2);

        //ascending order
        return tpc1Offset.compareTo(tpc2Offset);

    }
};

//Fetch the attribute value that you would like to use to compare the ThirdPartyClass instances 
public static Integer compareUsing(ThirdPartyClass tpc) {

    Integer value = tpc.getValueUsingSomeFunction();
    return value;
}
}