Sortowanie, Comparable

0

Proszę o pomoc mianowicie zrobiłem sobie sortowanie ArrayList po roczniku i średniej. Jak zrobić teraz, żeby w przypadku tej samej średniej posortowało mi po nazwisku.

	public int compareTo(student st){  
		
		
		
		if(rocznik==st.rocznik && srednia==st.srednia)  
			return 0;  
		else if(rocznik>st.rocznik)  
			return 1; 
		else
			return -1;  
		}  
	}   
0

Chcesz mieć dwa sortowania do wyboru, czy chcesz dotychczasowe zastąpić nowym?

1

Nie odpowiadaj w komentarzach.

public int compareTo(student st) 
{
    int result = ((Integer)rocznik).compareTo((Integer)st.rocznik);
    if(result == 0)
    {
        result = ((Double)srednia).compareTo((Double)st.srednia);
    }
    if(result == 0)
    {
        result = nazwisko.compareTo(st.nazwisko);
    }
    return result;
}

będzie niedobrze, jeśli w nazwiskach są polskie znaki diakrytyczne.

1

Nie zalogowałem się :/
On chce mieć trzy poziomy sortowania. Tu masz rozwiązanie:

 
package pl.dmichalski.project.utils;

import com.google.common.collect.Lists;

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

public class Main {

    public static void main(String[] args) {
        ArrayList<Student> students = Lists.newArrayList(
            new Student(1999, "Dabacki", 3.0),
            new Student(1999, "Abacki", 4.0),
            new Student(1999, "Kowalski", 4.0),
            new Student(1999, "Nowak", 4.5),
            new Student(1999, "Cabacki", 4.5),
            new Student(1999, "Babacki", 4.5),
            new Student(2000, "Kowalski", 4.0),
            new Student(2000, "Nowa", 5.0),
            new Student(2000, "Cabacki", 5.0),
            new Student(2000, "Babacki", 5.0)
        );

        Collections.sort(students);
        students.forEach(System.out::println);

    }
}

class Student implements Comparable<Student> {

    private int year;
    private String surname;
    private double average;

    Student(int year, String surname, double average) {
        this.year = year;
        this.surname = surname;
        this.average = average;
    }

    @Override
    public int compareTo(Student o) {
        if (year == o.year && average == o.average) {
            return surname.compareTo(o.surname);
        } else if (year == o.year) {
            return ((Double)average).compareTo(o.average);
        } else {
            return ((Integer)year).compareTo(o.year);
        }
    }

    @Override
    public String toString() {
        return String.format("%d %s %.1f", year, surname, average);
    }
}
4

Jeśli nie możesz/nie chcesz implementować Comparable w swojej klasie wtedy możesz użyć Comparatora.

W Javie 8 aż się o to prosi no i wygląda to pięknie :)

students.sort(Comparator.comparing(Student::getYear).thenComparing(Student::getAverage)
.thenComparing(Student::getSurname));

tylko musisz mieć gettery dla pól, które porównujesz

1 użytkowników online, w tym zalogowanych: 0, gości: 1