按所有对象包含的字符串值对 Set 中的对象进行排序

发布于 2024-10-01 20:15:36 字数 557 浏览 5 评论 0原文

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

想象每组代表学校的一个班级。每组都包含人物对象。 person 对象保存名称的字符串值。我想在循环并写出集合中的人员之前按名称排列它们。

是否有无论如何使用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 
        }                              
      }        

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

Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.

Imagine each set as repressenting a class in a school. Each set contains person objects. A person object holds a String value for name. I'd like to arrange the Persons in the Set by name before I loop through and write them out.

Is there anywahy to use Collections.sort(); or something similar to achieve this?

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 
        }                              
      }        

I do know that 2+ children in a class may share the same name but please ignore this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

醉生梦死 2024-10-08 20:15:36

Set 没有排序的概念,因为它是一个集合。

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

A Set has no notion of ordering because, well, it's a set.

There is a SortedSet interface implemented by TreeSet class that you can use. Simply provide an appropriate Comparator to the constructor, or let your Person class implements Comparable.

甜警司 2024-10-08 20:15:36

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

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

With Java 8 you can sort the Set of persons and generate List of persons which are sorted as follows.

List<Person> personList = personSet.stream().sorted((e1, e2) -> 
e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
云淡月浅 2024-10-08 20:15:36

您必须实现 Comparable 用于可排序对象(Person 等)。

然后:

  1. 将 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());
        }
      }
};

You must implement Comparable for your sortable objects (Person etc).

Then:

  1. Convert Set to List (some info here) since you can't sort a Set
  2. Use Collections.sort

or

  1. Convert to a SortedSet (like a TreeSet)
  2. Use a Comparator for custom ordering

Examples:

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());
        }
      }
};
江挽川 2024-10-08 20:15:36

可以考虑使用TreeSet来存储对象。排序时,为 Person 对象创建带有自定义比较器的新 TreeSet。我不建议使用 Collection.sort 因为 AFAIR 它只能对列表进行排序。

You can consider using TreeSet to store objects. And when sorting create new TreeSet with custom comparator for your Person objects. I do not suggest using Collection.sort because AFAIR it can sort only lists.

眼眸里的那抹悲凉 2024-10-08 20:15:36

您可以使您的 Person 类实现 Comparable接口如此处所示,然后进行相应的排序。

You could make your Person class implement the Comparable interface as shown here and then sort them accordingly.

無處可尋 2024-10-08 20:15:36

您可能想考虑使用 SortedSet 例如 TreeSet。这允许您提供一个Comparator,在您的情况下可以比较Person的名称。

You may want to look at using a SortedSet for example a TreeSet. This allows you to provide a Comparator which in your case can compare the name of the Person.

猫七 2024-10-08 20:15:36

是的!这你绝对可以使用 Collection.sort()。但您需要使用排序集(如 TreeSet)。或者,您可以先将集合中的所有元素插入到列表中。

然后,您的 Person 类需要实现 Comparable,因为当 Collections.sort() 尝试决定放置它们的顺序时,将调用此接口。所以它可以是简单的事情,例如:

public class Person implements Comparable<Person> {
  ...
  @Override
  public int compareTo(Person p) {
    return this.name.compareTo(p.name);
  }
}

如果使用 TreeSet,它应该已经排序。否则,如果使用列表,只需对每个列表调用 Collections.sort(List l) 即可。

Yes! This you can definitely use Collection.sort(). But you will need to either use a sorted set (like TreeSet). Or, alternatively, you can first insert all the elements in the Set to a List.

Then, your Person class needs to implement Comparable, as this interface will be called by the Collections.sort() when it tries to decide in which order to place them. So it can be something simple like:

public class Person implements Comparable<Person> {
  ...
  @Override
  public int compareTo(Person p) {
    return this.name.compareTo(p.name);
  }
}

If using a TreeSet, it should be sorted already. Otherwise, if using a List, simply call Collections.sort(List l) on each list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文