0
0

(java silver) ComparatorとCompareble

Last updated at Posted at 2024-05-15

JavaSilverでメモしたところ備忘録として残しておこうと思います。

Comparator

  • java.utilのComparatorを実装したクラスを定義しcomparaメソッドをオーバーライドし比較ロジックを定義
  • Comparatorは比較ロジックに応じていくつも作れる
  • 自分で定義したクラスオブジェクトの特定や特定の値をもとにソートしたいときや細かい条件等でソートしたい場合に使用する
public class ShoseNameComparator implements Comparator<Shose> {

    @Override
    public int compare(Shose shose1, Shose shose2){
        return shose1.getTitle().compareTo(shose2.getName());
    }

}

値段比較

public class ShosePriceComparator implements Comparator<Shose> {

    @Override
    public int compare(Shose,shose1, Shose shose2){
        return Integer.valueOf(shose1.getPrice()).compareTo(shose2.getPrice());
    }

}

販売日比較

public class ShoseDateOfIssueComparator implements Comparator<Shose> {

    @Override
    public int compare(Shose shose1, Shose shose){
        return shose1.getDateOfIssue().compareTo(shose2.getDateOfIssue());
    }

}

Comparable

  • java.langのComparableインターフェースを実装しcompareToメソッドをオーバーライドします
public class Shose implements Comparable<Shose>{

    // name
    private String name;

    // 値段
    private int price;

    // 販売日
    private LocalDate dateOfIssue;

    @Override
    public int compareTo(Book book){
        return title.compareTo(book.title);
    }
}
Shose shose1 = new Shose();
shose1.setName("jordan");
shose1.setValue(8710);
shose1.setDataOfIssue(1985,9,15);

Shose shose2 = new Shose();
shose2.setName("Super Star");
shose2.setValue(10000);
shose2.setDataOfIssue(1969,4,1);

Shose shose3 = new Shose();
shose3.setName("ALL STAR");
shose3.setValue(7700);
shose3.setDataOfIssue(1917,4,2);

List<Shose> shoseList = Arrays.asList(shose1,shose2,shose3);

System.out.println("ソート前:" + shoseList);

Collections.sort(shoseList);

System.out.println("ソート後:" + shoseList);
  • java.util.Collectionsのsort(List list)は、要素のオブジェクトが持つcompareToにより要素同士を比較し、ソート実施
ソート前: [Shose(name=jordan,price=8710,dateOfIssue=1985-9-15),Shose(name=Super Star,price=10000,dateOfIssue=1969-4-1),Shose(name=ALL STAR,price=7700,dateOfIssue=1917-4-2)]
ソート後: [Shose(name=ALL STAR,price=7700,dateOfIssue=1917-4-2),Shose(name=jordan,price=8710,dateOfIssue=1985-9-15),Shose(name=Super Star,price=10000,dateOfIssue=1969-4-1)]

compareToでは比較ロジックを一つしか定義できない

配列(固定長)のソート

  • Arrayクラスのsortメソッドを使用
Arrays.sort(配列名);//昇順
Arrays.sort(配列名, Collections.reverseOrder());//降順

Listのソート

  • collectionクラスのsortメソッドを使用
collection.sort(リスト名);//昇順
collection.sort(リスト名, Collections.reverseOrder());//降順

ラムダ式とStream API

リスト名.stream().sorted((x, y) -> y - x);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0