通过所有对象包含的String值对Set内的对象进行排序

Jul*_*lio 5 java sorting object set

好的,这是一个棘手的问题.我有一个集合列表.我想按顺序对集合中的对象进行排序.

想象一下,每一套都是在学校里代表一个班级.每组包含人物对象.person对象包含name的String值.在我循环并写出来之前,我想按照名字安排人员.

有没有使用Collections.sort();或类似的东西实现这一点?

for (Set<Person> s : listOfAllChildren) {       
      for (Person p : s) {
        if(p.getClass().equalsIgnoreCase("Jones")){
          System.out.println(p.getName());
          }
         else if...//carry on through other classes 
        }                              
      }        
Run Code Online (Sandbox Code Playgroud)

我知道一个班级的2个以上的孩子可能有相同的名字,但请忽略这一点

Nic*_*uet 14

A Set没有订购的概念,因为它是一套.

您可以使用SortedSet由TreeSet类实现的接口.只需提供适当Comparator的构造函数,或让您的Person类实现Comparable.


sje*_*397 8

您必须Comparable为可排序对象(Person等)实现.

然后:

  1. 将Set转换为List(这里有一些信息),因为你无法对它进行排序Set
  2. 使用 Collections.sort

要么

  1. 转换为SortedSet(如TreeSet)
  2. 使用比较器进行自定义排序

例子:

import java.util.*;

class Person implements Comparable<Person> {
    private String firstName, lastName;

    public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName;}
    public String getFirstName() {return firstName;}
    public String getLastName() {return lastName;}
    public String getName() {return firstName + " " + lastName;}

    public int compareTo(Person p) {
        return lastName.compareTo(p.lastName);
    }
}

class FirstNameComparator implements Comparator<Person> {
    public int compare(Person p1, Person p2){
            return p1.getFirstName().compareTo(p2.getFirstName());
    }
}

class Test {
  public static void log(String s) {
        System.out.println(s);
    }

  public static void main(String[] args) {
        Set<Person> people = new HashSet<Person>();
        people.add(new Person("Bob", "Jones"));
        people.add(new Person("Alice", "Yetti"));

        log("Sorted list:");
        List<Person> peopleList = new LinkedList<Person>();
        peopleList.addAll(people);
        Collections.<Person>sort(peopleList);
        for (Person p : peopleList) {
            log(p.getName());
        }

        log("TreeSet:");
        TreeSet<Person> treeSet = new TreeSet<Person>();
        treeSet.addAll(people);
        for (Person p : treeSet) {
            log(p.getName());
        }

        log("TreeSet (custom sort):");
        TreeSet<Person> treeSet2 = new TreeSet<Person>(new FirstNameComparator());
        treeSet2.addAll(people);
        for (Person p : treeSet2) {
            log(p.getName());
        }
      }
};
Run Code Online (Sandbox Code Playgroud)


rav*_*iru 6

使用Java 8,您可以对人员进行排序Set并生成List按如下方式排序的人员.

List<Person> personList = personSet.stream().sorted((e1, e2) -> 
e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)