I tried to collect the methods to sort arrays and lists with java. Personal notes.
ascending order
int[] array = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8 };
Arrays.sort(array);
descending order
Integer[] array = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8 };
Arrays.sort(array, Collections.reverseOrder());
List
ascending order
ArrayList<Integer> al = new ArrayList<>();
al.add(2);
al.add(7);
al.add(1);
al.add(8);
al.add(2);
al.add(8);
Collections.sort(al);
descending order
ArrayList<Integer> al = new ArrayList<>();
al.add(2);
al.add(7);
al.add(1);
al.add(8);
al.add(2);
al.add(8);
Collections.sort(al, Collections.reverseOrder());
application
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Item> itemList = new ArrayList<>();
itemList.add(new Item(4, "Book", 1000));
itemList.add(new Item(2, "Bag", 3000));
itemList.add(new Item(3, "Calendar", 2000));
itemList.add(new Item(1, "pen", 200));
//id ascending sort
itemList.sort(Comparator.comparing(Item::getId));
//id descending sort
itemList.sort(Comparator.comparing(Item::getId).reversed());
//kind ascending sort
itemList.sort(Comparator.comparing(Item::getKind));
//kind descending sort
itemList.sort(Comparator.comparing(Item::getKind).reversed());
}
}
class Item {
int id;
String kind;
int price;
Item(int id, String kind, int price) {
this.id = id;
this.kind = kind;
this.price = price;
}
public int getId() {
return id;
}
public String getKind() {
return kind;
}
}
Recommended Posts