Comment trier un tableau d'objets en Java?

mon tableau ne contient aucune chaîne. Mais il contient des références à des objets. Chaque référence d'objet renvoie le nom, l'auteur et l'éditeur par la méthode toString.

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

maintenant je dois trier ce tableau d'objets par le nom. Je sais trier, mais je ne sais pas extraire le nom des objets et les trier.

24
demandé sur Flow 2013-09-19 17:25:38

8 réponses

vous avez deux façons de faire cela, les deux utilisent le tableaux classe d'utilité

  1. implémenter un comparateur et passer votre tableau avec le comparateur à la méthode de tri qui le prennent comme second paramètre.
  2. implémenter l'interface Comparable dans la classe d'où proviennent vos objets et passer votre tableau à la méthode de tri qui ne prend qu'un seul paramètre.

exemple

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

Sortie

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]
28
répondu A4L 2015-09-28 16:27:54

Vous pouvez essayer quelque chose comme ceci:

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);
  }
});
32
répondu zbess 2013-09-19 13:43:07

Java 8


utilisant lambda expressions

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

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

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");
    }
}

sortie:

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

à l'Aide méthode de référence

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

compareThem doit être ajouté dans MyType.java :

public static int compareThem(MyType a, MyType b) {
    return a.name.compareTo(b.name);
}
18
répondu ROMANIA_engineer 2016-02-08 13:53:35

Parfois, vous voulez trier un tableau d'objets sur une valeur arbitraire. Puisque compareTo () utilise toujours les mêmes informations sur l'instance, vous pourriez vouloir utiliser une technique différente. Une façon est d'utiliser un algorithme de tri. Disons que vous avez une rangée de livres et vous voulez les trier sur leur hauteur, qui est stockée comme un int et accessible par la méthode getHeight(). Voici comment vous pouvez trier les livres dans votre tableau. (Si vous ne voulez pas changer l'original tableau, il suffit de faire une copie et de trier cela.)

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

quand ce code est terminé, le tableau d'objets de livre sera trié par hauteur dans l'ordre décroissant--le rêve d'un designer d'intérieur!

0
répondu Stephen Barner 2017-12-20 19:10:37

avec java 8 à l'aide de la méthode de référence

vous pouvez ajouter compare méthode à votre Book classe

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

et alors vous pourriez faire ceci :

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

voici un exemple complet:

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);

}
0
répondu Ali 2018-01-24 09:26:52

vous pouvez implémenter l'interface" Comparable " sur une classe dont vous voulez comparer les objets.

et aussi mettre en œuvre la méthode" compareTo " en cela.

ajouter les instances de la classe dans un ArrayList

puis le " java.utils.Collection.la méthode sort () " fera la magie nécessaire.

Ici--->( https://deva-codes.herokuapp.com/CompareOnTwoKeys ) un exemple de travail où les objets sont triés en fonction de deux clés d'abord par l'id puis par nom.

0
répondu Devashish Priyadarshi 2018-07-15 11:42:04
public class Student implements Comparable<Student> {

    private int sid;
    private String sname;

    public Student(int sid, String sname) {
        super();
        this.sid = sid;
        this.sname = sname;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Override
    public String toString() {
        return "Student [sid=" + sid + ", sname=" + sname + "]";
    }

    public int compareTo(Student o) {
        if (this.getSname().compareTo(o.getSname()) > 1) {
            return toString().compareTo(o.getSname());
        } else if (this.getSname().compareTo(o.getSname()) < 1) {
            return toString().compareTo(o.getSname());
        }
        return 0;
    }

}
0
répondu Manash Ranjan Dakua 2018-08-05 15:38:21
import java.util.Collections;

import java.util.List;

import java.util.ArrayList;


public class Test {

public static void main(String[] args) {

   List<Student> str = new ArrayList<Student>();

   str.add(new Student(101, "aaa"));

   str.add(new Student(104, "bbb"));

   str.add(new Student(103, "ccc"));

   str.add(new Student(105, "ddd"));

   str.add(new Student(104, "eee"));

   str.add(new Student(102, "fff"));




   Collections.sort(str);
    for(Student student : str) {

        System.out.println(student);
    }

}
}
0
répondu Manash Ranjan Dakua 2018-08-05 15:40:38