How to sort objects in arrayList by their class?

java sort arraylist of objects by multiple fields
java sort arraylist of objects by field
sort arraylist of objects java
how to sort arraylist of objects alphabetically in java
java sort list of objects by property
sort list of objects in java without comparator
collections sort for custom objects
java sort array of objects by property

I have an ArrayList that holds 2 types of objects in it (objects from class Student and objects from class Teacher).

My question is how can I sort it so that all objects that are from Student to appear first and then all objects that are from class Teacher to appear after them.

For example: Student1, Student2, Student3, Teacher1,Teacher2,Teacher3

Here is my code:

public ArrayList sortList(){

    ArrayList<Student> students = new  ArrayList<Student>();
    ArrayList<Teacher> teachers = new  ArrayList<Teacher>();
    ArrayList<Person> university = new  ArrayList<Person>();
    for(Person p : list){
        if(p.getClass().getSimpleName().equals("Teacher")){
            teachers.add((Teacher)p);
        };
        if(p.getClass().getSimpleName().equals("Student")){
            students.add((Student)p);
        }
        university.addAll(students);
        university.addAll(teachers);
    }
    return university;
}

You can use Collections.sort(list,comparator)

In the Comparator you can compare the class names because (luckily) S is before T in the alphabet:

   List<Object> studentsAndTeachers = // ...
   Collections.sort(studentsAndTeachers, (o1, o2) -> o1.getClass().getName().compareTo(o2.getClass().getName()));

of cause you ave to apply other sorting criteria first or extend the comparator to recognize them...

Java ArrayList of Object Sort Example (Comparable And Comparator), The sort() method accepts an instance of Comparator implementing class which must be able to compare the elements contained in the arraylist. Internally, the  Here's a Comparator class that orders Human objects based on class name, and then the value of the name attribute. If you use this with Collections.sort(), you can sort the list into the required order. Note that this implementation: sorts objects with the same type based on their name (as implied by the example), and

Sorting like this will do the job for you, although is not a quite good solution generally speaking.

Collections.sort(classroom, (o1, o2) -> {
    if (o1 instanceof Student && o2 instanceof Teacher) {
        return -1;
    }

    if (o1 instanceof Teacher && o2 instanceof Student) {
        return 1;
    }

    return 0;
});

ArrayList sort() - Sort list of objects by field, Learn to sort ArrayList of custom objects by field using comparable and In that case, implement the Comparator interface in those domain class and use same  Sort ArrayList of Objects Using Comparable. Comparable is used to sort an arraylist of object on the basis of single property at a time. For example we have student data in which we have two properties, name and age. We can sort it by name or age. This can be done by implementing Comparable interface and overriding its compareTo() method. Student.java

Now it should work like a bread with butter:

public class Main
{
    public static void main(String[] args)
    {
        List<Human> humans = new ArrayList<>();
        humans.add(new Teacher("Teacher1"));
        humans.add(new Teacher("Teacher2"));
        humans.add(new Student("Student3"));
        humans.add(new Student("Student1"));
        humans.add(new Teacher("Teacher3"));
        humans.add(new Student("Student2"));

        Collections.sort(humans, new Comparator<Human>()
        {
            @Override
            public int compare(Human o1, Human o2)
            {
                if (o2 instanceof Teacher) {
                    return -1;
                } else if (o1 instanceof Teacher && o2 instanceof Student) {
                    return 1;
                }
                /* other checks not about being teacher or student goes here... */                
            }
        });
        System.out.println(humans);
    }
}

interface Human
{
    String getName();

    void setName(String name);
}

class Teacher implements Human
{
    private String name;

    public Teacher(String name)
    {
        super();
        this.name = name;
    }

    @Override
    public String getName()
    {
        return name;
    }

    @Override
    public void setName(String name)
    {
        this.name = name;
    }
}

class Student implements Human
{
    private String name;

    public Student(String name)
    {
        super();
        this.name = name;
    }

    @Override
    public String getName()
    {
        return name;
    }

    @Override
    public void setName(String name)
    {
        this.name = name;
    }
}

Java 8 - Collections sort() method, Since Date implements Comparable , it has a compareTo method just like String does. So your custom Comparator could look like this: public class  Iteams.sort((o1, o2) -> o1.getPoints().compareTo(o2.getPoints())); Also there are options for second comparator, if objects are equals on the first: // e.g. if same points, then compare their names. Iteams.sort(Comparator.comparing(Team::getPoints).thenComparing(Team::getName)); Also note that the default sort option is ascending, but you can

Sort ArrayList of custom Objects by property, Now let's try to store a custom Object (say Student) in the various Collection and see how sorting works. Data(Students) Stored in ArrayList. – Use Collections.sort() method or Java 8 List.sort() to in-place sort the ArrayList, Java 8 Stream.sorted() to return a new sorted ArrayList of Objects without affecting the original List. – For Descending order, just use additional Comparator.reversed() method. Create Class for objects to be sorted. Date.java

You can use Comparator.comparing for that:

list.sort(Comparator.comparing(Teacher.class::isInstance))

This works because Class.isInstance returns boolean which is wrapped into Boolean which implements Comparable.

How To Sort Objects In Java, – Implement Comparator interface for the class we're gonna use for handling sorting. – Override  In the class above, we initialized an ArrayList object in the constructor. In the sortAscending()method, we called the Collections.sort() method passing the initialized ArrayList object and

Java - Sort ArrayList of Objects, In this program, you'll learn to sort an arraylist of custom object by their given property in In the main() method, we've created an array list of custom objects list  Sorting of ArrayList<String> and ArrayList<Integer>. Sorting of ArrayList in descending order. We generally use Collections.sort () method to sort a simple array list. However if the ArrayList is of custom object type then in such case you have two options for sorting- comparable and comparator interfaces. Before going through the example of them, let’s see what’s the output when we try to sort arraylist of Objects without implementing any of these interfaces.

Java Program to Sort ArrayList of Custom Objects By Property, We will add Students to the ArrayList object. import java.util.*; public class ArrayListSort {  In this article, I will be mainly focusing on sorting ArrayList, HashSet, TreeSet from Collection and last but not the least the array. Let's see how to sort a given collection of integers( 5,10,0

Java ArrayList of Object Sort Example(Comparable and Comparator , If your class doesn't implement Comparable interface and Comparator is also not specified then using an ArrayList of such objects with sort()  1.2. Sort arraylist of custom objects by field with Comparable. We may need to sort list of user defined objects which have their own sorting logic. In that case, implement the Comparator interface in those domain class and use same approach as above.

Comments
  • Did you read about "Comparable" in java?
  • While we don't know the context, I would like to generally advice to just keep students and teachers in two separate ArrayLists. We all know that having both in the same class room is already problematic, but the same ArrayList? Oh boy.
  • Well, dirty solution might be to run for loop and check with instanceof keyword.
  • If you really need to have them both in one list, then you can separate into two list sort each list, and then append one list to the other
  • Read up comparator and comparable.
  • The comparable interface should maintain the natural order of object of a class. My feeling is that being Teacher or Student is not the natural order of persons (at least not in that order... ;o) )
  • Or, if you want to sort on class name: Collections.sort(list, Comparator.comparing(o -> o.getClass().getName()))