Using Collections.sort and Comparator in Java

Sorting a collection in Java is easy, just use Collections.sort(Collection) to sort your values. For example:

package de.vogella.algorithms.sort.standardjava;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Simple {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(5);
        list.add(4);
        list.add(3);
        list.add(7);
        list.add(2);
        list.add(1);
        Collections.sort(list);
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
}

?

This is possible because Integer implements the Comparable interface. This interface defines the method compare which performs pairwise comparison of the elements and returns -1 if the element is smaller then the compared element, 0 if it is equal and 1 if it is larger.

package de.vogella.algorithms.sort.standardjava;
 
import java.util.Comparator;
 
public class MyIntComparable implements Comparator<Integer>{
 
    @Override
    public int compare(Integer o1, Integer o2) {
        return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
    }
}

But what if what to sort differently, e.g. for example in different order. Well, you could just use Collection.reverse(). Or you define your own class with implements the interface Comparator.

package de.vogella.algorithms.sort.standardjava;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Simple2 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(5);
        list.add(4);
        list.add(3);
        list.add(7);
        list.add(2);
        list.add(1);
        Collections.sort(list, new MyIntComparable());
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
}


?
?

The nice thing about this approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值