Головна‎ > ‎Java‎ > ‎Список‎ > ‎

Сортувати за власним критерієм

Новий спосіб

import java.util.Comparator;

fruits.sort(Comparator.comparing(o -> o.getDate()));
for (Fruit fruit : fruits) {
     System.out.println(fruit);
}



Старий спосіб

public class Student implements Comparable<Student> {
    private String studentname;
    private int studentage;

    public Student(String name, int age) {
        this.studentname = name;
        this.studentage = age;
    }

    @Override
    public int compareTo(Student next) {
        return this.studentage - next.studentage;
    }

    @Override
    public String toString() {
        return "[ name = " + studentname + ", age = " + studentage + " ]";
    }
}




import java.util.ArrayList;
import java.util.Collections;

public static void main(String[] args) {
    ArrayList<Student> arraylist = new ArrayList<Student>();
    arraylist.add(new Student("Taras", 40));
    arraylist.add(new Student("Vitaliy", 30));
    arraylist.add(new Student("Andriy", 20));

    Collections.sort(arraylist);

    for(Student str: arraylist){
        System.out.println(str);
    }
}



[ name = Andriy, age = 20 ]
[ name = Vitaliy, age = 30 ]
[ name = Taras, age = 40 ]





List<Fruit> sortedLetters = fruits.stream().sorted().collect(Collectors.toList());