Comparator ve Comparable | Java

Özge Odabaş
2 min readMar 6, 2024

Java’da farklı senaryolara göre collectionları sıralamanın farklı yolları vardır. Bu yazıda bu farklı yolları ve Java 8 ile gelen lambda expressionları da kullanarak farklı örnekleri inceleyeceğiz.

Natural Ordering’e sahip veri tipleri için genellikle Collections.sort() veya Arrays.sort() metodları kullanılır. Bunun nedeni zaten bu veri tiplerinin Comparable interfaceini implement ediyor olmalarıdır;

Integer ve String class

Bu yazıda doğal bir sıralamaya sahip olmayan nesneler için nasıl sıralama yapabileceğimizi öğreneceğiz.

Örneğin elimizdeki integerlardan oluşan bir arrayı aşağıdaki gibi sort edebiliriz;

//for natural ordering arrays

int[] integerArray = new int[]{5,5,7,2,1,0,86,85,10};
//sorting complete array
Arrays.sort(integerArray);
//sorting part of the array
Arrays.sort(integerArray,0,4);

//Java 8 comes with a new API – parallelSort –
//with a similar signature to the Arrays.sort() API
int[] newIntArray = new int[]{5,5,7,2,1,0,86,85,10};
//Behind the scenes of parallelSort(),
//it breaks the array into different sub-arrays.
//Each sub-array is sorted with Arrays.sort() in different threads
//so that sort can be executed in a parallel fashion and are merged finally as a sorted array.
Arrays.parallelSort(newIntArray);

Veya liste, set veya map yapılarını;

//for lists
List<String> toSortList = new ArrayList<>();
toSortList.addAll(Arrays.asList("Ayşe","Fatma","Hayriye","Hasan","Ali"));
Collections.sort(toSortList);

//for sets
//If you want to use HashSet to store unique strings and then sort them,
//you can first convert the HashSet to a List, sort the List,
//and then create a new HashSet from the sorted List
HashSet<String> stringHashSet = new HashSet<>();
stringHashSet.add("Java");
stringHashSet.add("C#");
stringHashSet.add("Python");
stringHashSet.add("Go");
List<String> sortedList = new ArrayList<>(stringHashSet);
Collections.sort(sortedList);
HashSet<String> sortedHashSet = new HashSet<>(sortedList);

Comparable Interface

Comparable ile sıralama yapabilmek için oluşturduğumuz sınıflarsa Comparable interfaceini implement etmemiz gerekir.

public class Product implements Comparable<Product> {

private int id;
private String name;
private double price;

//constructors, getters and setters

//sorting according to price
@Override
public int compareTo(Product otherProduct) {
return Double.compare(getPrice(), otherProduct.getPrice());
}

}

Sorting order comperTo() metodundan dönecek değere göre yapılır.

Comparator Functional Interface

Comparator ile özel comparator sınıfları oluşturarak veya lambda expression kullanarak sıralama yapabiliriz.

public class ProductNameComparator implements Comparator<Product> {

@Override
public int compare(Product firstProduct, Product secondProduct) {
return firstProduct.getName().compareTo(secondProduct.getName());
}

}


public class ProductPriceComparator implements Comparator<Product> {

@Override
public int compare(Product firstProduct, Product secondProduct) {
return Double.compare(firstProduct.getPrice(),secondProduct.getPrice());
}

}
Collections.sort(productList, new ProductPriceComparator());
//or
Collections.sort(productList, new ProductNameComparator());

Java8 ile birlikte Comparator kullanımı aşağıdaki gibi de olabilir;

Comparator byPrice = (p1, p2) -> Integer.compare(p1.getPrice(), p2.getPrice());
productList.sort(byPrice);

İhtiyacımıza göre iki interfaceden birini kullanarak koleksiyonlar üzerinde sıralama işlemlerimizi yapabiliriz.

--

--

Özge Odabaş

Merhaba! Ben Özge. Junior Java Developerım. Kendimi geliştirirken edindiğim bilgileri yazıyorum. Keyifli okumalar.