Sorting objects within a Set by a String value that all objects contain

后端 未结 7 958
北荒
北荒 2021-01-01 01:30

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

7条回答
  •  Happy的楠姐
    2021-01-01 02:18

    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 {
        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 {
        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 people = new HashSet();
            people.add(new Person("Bob", "Jones"));
            people.add(new Person("Alice", "Yetti"));
    
            log("Sorted list:");
            List peopleList = new LinkedList();
            peopleList.addAll(people);
            Collections.sort(peopleList);
            for (Person p : peopleList) {
                log(p.getName());
            }
    
            log("TreeSet:");
            TreeSet treeSet = new TreeSet();
            treeSet.addAll(people);
            for (Person p : treeSet) {
                log(p.getName());
            }
    
            log("TreeSet (custom sort):");
            TreeSet treeSet2 = new TreeSet(new FirstNameComparator());
            treeSet2.addAll(people);
            for (Person p : treeSet2) {
                log(p.getName());
            }
          }
    };
    

提交回复
热议问题