안드로이드 자바

[Android][Java] 날짜순으로 정렬하기

teamnova 2023. 3. 29. 12:00
728x90

안녕하세요. 배열안에 담긴 객체들을 날짜 또는 숫자 순으로 정렬해보겠습니다.

 

목차

1. Coffee class

2. 정렬

3. 결과

 

 

 

1. Coffee class

public class Coffee {

    String name;
    String date;
    int price;

    public Coffee(String name, int price, String date) {
        this.name = name;
        this.price = price;
        this.date = date;
    }

    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "\nCoffee{" +
                "name='" + name + '\'' +
                ", date='" + date + '\'' +
                ", price=" + price +
                '}';
    }
}

날짜순, 금액순으로 정렬할 예정입니다.

 

 

 

2. 정렬

        Coffee[] coffees = new Coffee[]{
                new Coffee("Green tea",5500, "20-03-25"),
                new Coffee("StrawBerry Latte",5500, "19-01-27"),
                new Coffee("Americano",3500, "20-03-25"),
                new Coffee("Green tea Latte",5500, "20-03-26"),
                new Coffee("Vanilla Latte",4500, "18-03-25"),
                new Coffee("Vanilla Latte",3600, "20-03-25"),
                new Coffee("Espresso",3000, "20-02-26")
        };


        List<Coffee> coffeesToSort = Arrays.asList(coffees);
        coffeesToSort.sort(Comparator.comparing(Coffee::getDate)
                .thenComparing(Coffee::getPrice)
        );
        Log.e("coffees2:", coffees2.toString());

 

 

3. 결과

3-1)

coffeesToSort.sort(Comparator.comparing(Coffee::getDate)
        .thenComparing(Coffee::getPrice)
);

일 때는 날짜먼저 정렬하고, 동일하다면 금액순으로 정렬합니다.

 

 

3-2)

coffeesToSort.sort(Comparator.comparing(Coffee::getDate)
);

날짜로만 정렬했을 때, 그 이후는 add된 순으로 정렬

 

 

3-3)

coffeesToSort.sort(Comparator.comparing(Coffee::getDate).reversed()
        .thenComparing(Coffee::getPrice)
);

반대로 정렬도 가능합니다.