如何在Java中对对象数组进行排序?

时间:2021-10-21 15:57:42

My array does not contain any string. But its contains object references. Every object reference returns name, id, author and publisher by toString method.

我的数组不包含任何字符串。但是它包含对象引用。每个对象引用通过toString方法返回名称、id、作者和发布者。

public String toString() {
        return (name + "\n" + id + "\n" + author + "\n" + publisher + "\n");
}

Now I need to sort that array of objects by the name. I know how to sort, but I do not know how to extract the name from the objects and sort them.

现在我需要按对象名对数组进行排序。我知道如何排序,但我不知道如何从对象中提取名称并对它们进行排序。

5 个解决方案

#1


25  

You have two ways to do that, both use the Arrays utility class

有两种方法可以做到这一点,都使用了array工具类

  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. 实现一个比较器,并将数组与比较器一起传递给以它为第二个参数的排序方法。
  3. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.
  4. 在对象所在的类中实现可比较的接口,并将数组传递给仅接受一个参数的sort方法。

Example

例子

class Book implements Comparable<Book> {
    public String name, id, author, publisher;
    public Book(String name, String id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }
    public String toString() {
        return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
    }
    @Override
    public int compareTo(Book o) {
        // usually toString should not be used,
        // instead one of the attributes or more in a comparator chain
        return toString().compareTo(o.toString());
    }
}

@Test
public void sortBooks() {
    Book[] books = {
            new Book("foo", "1", "author1", "pub1"),
            new Book("bar", "2", "author2", "pub2")
    };

    // 1. sort using Comparable
    Arrays.sort(books);
    System.out.println(Arrays.asList(books));

    // 2. sort using comparator: sort by id
    Arrays.sort(books, new Comparator<Book>() {
        @Override
        public int compare(Book o1, Book o2) {
            return o1.id.compareTo(o2.id);
        }
    });
    System.out.println(Arrays.asList(books));
}

Output

输出

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

#2


29  

You can try something like this:

你可以试试这样的方法:

List<Book> books = new ArrayList<Book>();

Collections.sort(books, new Comparator<Book>(){

  public int compare(Book o1, Book o2)
  {
     return o1.name.compareTo(o2.name);
  }
});

#3


17  

Java 8


Using lambda expressions

Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));

Test.java

Test.java

public class Test {

    public static void main(String[] args) {

        MyType[] myTypes = {
                new MyType("John", 2, "author1", "publisher1"),
                new MyType("Marry", 298, "author2", "publisher2"),
                new MyType("David", 3, "author3", "publisher3"),
        };

        System.out.println("--- before");
        System.out.println(Arrays.asList(myTypes));
        Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));
        System.out.println("--- after");
        System.out.println(Arrays.asList(myTypes));

    }

}

MyType.java

MyType.java

public class MyType {

    public String name;
    public int id;
    public String author;
    public String publisher;

    public MyType(String name, int id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }

    @Override
    public String toString() {
        return "MyType{" +
                "name=" + name + '\'' +
                ", id=" + id +
                ", author='" + author + '\'' +
                ", publisher='" + publisher + '\'' +
                '}' + System.getProperty("line.separator");
    }
}

Output:

输出:

--- before
[MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
, MyType{name=David', id=3, author='author3', publisher='publisher3'}
]
--- after
[MyType{name=David', id=3, author='author3', publisher='publisher3'}
, MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
]

Using method references

Arrays.sort(myTypes, MyType::compareThem);

where compareThem has to be added in MyType.java:

其中compareThem必须添加到MyType.java:

public static int compareThem(MyType a, MyType b) {
    return a.name.compareTo(b.name);
}

#4


0  

Sometimes you want to sort an array of objects on an arbitrary value. Since compareTo() always uses the same information about the instance, you might want to use a different technique. One way is to use a standard sorting algorithm. Let's say you have an array of books and you want to sort them on their height, which is stored as an int and accessible through the method getHeight(). Here's how you could sort the books in your array. (If you don't want to change the original array, simply make a copy and sort that.)

有时,您希望对任意值上的对象数组进行排序。由于compareTo()总是使用与实例相同的信息,所以您可能需要使用不同的技术。一种方法是使用标准的排序算法。假设您有一个图书数组,您希望在它们的高度上对它们进行排序,并将它们存储为int并通过getHeight()方法进行访问。下面是如何对数组中的书籍进行排序的方法。(如果您不想更改原始数组,只需复制并对其进行排序即可。)

`int tallest; // the index of tallest book found thus far
 Book temp; // used in the swap
 for(int a = 0; a < booksArray.length - 1; a++) {
   tallest = a; // reset tallest to current index
   // start inner loop at next index
   for(int b = a + 1; b < booksArray.length; b++)
     // check if the book at this index is taller than the
     // tallest found thus far
     if(booksArray[b].getHeight() > booksArray[tallest].getHeight())
       tallest = b;
   // once inner loop is complete, swap the tallest book found with
   // the one at the current index of the outer loop
   temp = booksArray[a];
   booksArray[a] = booksArray[tallest];
   booksArray[tallest] = temp;
 }`

When this code is done, the array of Book object will be sorted by height in descending order--an interior designer's dream!

当这段代码完成后,Book对象的数组将按照高度按降序排序——这是一个室内设计师的梦想!

#5


0  

with java 8 using of reference method

使用java 8的参考方法。

you could add compare method to your Book class

您可以将compare方法添加到图书类中

class Book {
     public static int compare(Book a , Book b)
     {
         return a.name.compareTo(b.name);
     }
}

and then you could do this :

然后你可以这样做:

Arrays.sort(books , Book::compare);

here is full example :

这里有一个完整的例子:

static class Book {
    String name;
    String author;

    public Book(String name, String author) {
        this.name = name;
        this.author = author;
    }

    public static int compareBooks(Book a , Book b)
    {
        return a.name.compareTo(b.name);
    }

    @Override
    public String toString() {
        return "name : " + name + "\t" + "author : " + author;
    }
}


public static void main(String[] args) {

    Book[] books = {
            new Book("Book 3" , "Author 1"),
            new Book("Book 2" , "Author 2"),
            new Book("Book 1" , "Author 3"),
            new Book("Book 4" , "Author 4")
    };

    Arrays.sort(books , Book::compareBooks);
    Arrays.asList(books).forEach(System.out::println);

}

#1


25  

You have two ways to do that, both use the Arrays utility class

有两种方法可以做到这一点,都使用了array工具类

  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. 实现一个比较器,并将数组与比较器一起传递给以它为第二个参数的排序方法。
  3. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.
  4. 在对象所在的类中实现可比较的接口,并将数组传递给仅接受一个参数的sort方法。

Example

例子

class Book implements Comparable<Book> {
    public String name, id, author, publisher;
    public Book(String name, String id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }
    public String toString() {
        return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
    }
    @Override
    public int compareTo(Book o) {
        // usually toString should not be used,
        // instead one of the attributes or more in a comparator chain
        return toString().compareTo(o.toString());
    }
}

@Test
public void sortBooks() {
    Book[] books = {
            new Book("foo", "1", "author1", "pub1"),
            new Book("bar", "2", "author2", "pub2")
    };

    // 1. sort using Comparable
    Arrays.sort(books);
    System.out.println(Arrays.asList(books));

    // 2. sort using comparator: sort by id
    Arrays.sort(books, new Comparator<Book>() {
        @Override
        public int compare(Book o1, Book o2) {
            return o1.id.compareTo(o2.id);
        }
    });
    System.out.println(Arrays.asList(books));
}

Output

输出

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

#2


29  

You can try something like this:

你可以试试这样的方法:

List<Book> books = new ArrayList<Book>();

Collections.sort(books, new Comparator<Book>(){

  public int compare(Book o1, Book o2)
  {
     return o1.name.compareTo(o2.name);
  }
});

#3


17  

Java 8


Using lambda expressions

Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));

Test.java

Test.java

public class Test {

    public static void main(String[] args) {

        MyType[] myTypes = {
                new MyType("John", 2, "author1", "publisher1"),
                new MyType("Marry", 298, "author2", "publisher2"),
                new MyType("David", 3, "author3", "publisher3"),
        };

        System.out.println("--- before");
        System.out.println(Arrays.asList(myTypes));
        Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));
        System.out.println("--- after");
        System.out.println(Arrays.asList(myTypes));

    }

}

MyType.java

MyType.java

public class MyType {

    public String name;
    public int id;
    public String author;
    public String publisher;

    public MyType(String name, int id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }

    @Override
    public String toString() {
        return "MyType{" +
                "name=" + name + '\'' +
                ", id=" + id +
                ", author='" + author + '\'' +
                ", publisher='" + publisher + '\'' +
                '}' + System.getProperty("line.separator");
    }
}

Output:

输出:

--- before
[MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
, MyType{name=David', id=3, author='author3', publisher='publisher3'}
]
--- after
[MyType{name=David', id=3, author='author3', publisher='publisher3'}
, MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
]

Using method references

Arrays.sort(myTypes, MyType::compareThem);

where compareThem has to be added in MyType.java:

其中compareThem必须添加到MyType.java:

public static int compareThem(MyType a, MyType b) {
    return a.name.compareTo(b.name);
}

#4


0  

Sometimes you want to sort an array of objects on an arbitrary value. Since compareTo() always uses the same information about the instance, you might want to use a different technique. One way is to use a standard sorting algorithm. Let's say you have an array of books and you want to sort them on their height, which is stored as an int and accessible through the method getHeight(). Here's how you could sort the books in your array. (If you don't want to change the original array, simply make a copy and sort that.)

有时,您希望对任意值上的对象数组进行排序。由于compareTo()总是使用与实例相同的信息,所以您可能需要使用不同的技术。一种方法是使用标准的排序算法。假设您有一个图书数组,您希望在它们的高度上对它们进行排序,并将它们存储为int并通过getHeight()方法进行访问。下面是如何对数组中的书籍进行排序的方法。(如果您不想更改原始数组,只需复制并对其进行排序即可。)

`int tallest; // the index of tallest book found thus far
 Book temp; // used in the swap
 for(int a = 0; a < booksArray.length - 1; a++) {
   tallest = a; // reset tallest to current index
   // start inner loop at next index
   for(int b = a + 1; b < booksArray.length; b++)
     // check if the book at this index is taller than the
     // tallest found thus far
     if(booksArray[b].getHeight() > booksArray[tallest].getHeight())
       tallest = b;
   // once inner loop is complete, swap the tallest book found with
   // the one at the current index of the outer loop
   temp = booksArray[a];
   booksArray[a] = booksArray[tallest];
   booksArray[tallest] = temp;
 }`

When this code is done, the array of Book object will be sorted by height in descending order--an interior designer's dream!

当这段代码完成后,Book对象的数组将按照高度按降序排序——这是一个室内设计师的梦想!

#5


0  

with java 8 using of reference method

使用java 8的参考方法。

you could add compare method to your Book class

您可以将compare方法添加到图书类中

class Book {
     public static int compare(Book a , Book b)
     {
         return a.name.compareTo(b.name);
     }
}

and then you could do this :

然后你可以这样做:

Arrays.sort(books , Book::compare);

here is full example :

这里有一个完整的例子:

static class Book {
    String name;
    String author;

    public Book(String name, String author) {
        this.name = name;
        this.author = author;
    }

    public static int compareBooks(Book a , Book b)
    {
        return a.name.compareTo(b.name);
    }

    @Override
    public String toString() {
        return "name : " + name + "\t" + "author : " + author;
    }
}


public static void main(String[] args) {

    Book[] books = {
            new Book("Book 3" , "Author 1"),
            new Book("Book 2" , "Author 2"),
            new Book("Book 1" , "Author 3"),
            new Book("Book 4" , "Author 4")
    };

    Arrays.sort(books , Book::compareBooks);
    Arrays.asList(books).forEach(System.out::println);

}