# Item.java
public class Item {
private String name;
private int value;
public Item(String name, int value) {
this.name = name;
this.value = value;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
}
# Main.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
private static void printItems(List<Item> items) {
for (Item item : items) {
System.out.println(item.getName());
}
}
public static void main(String[] args) {
Item i01 = new Item("alpha", 20);
Item i02 = new Item("beta", 30);
Item i03 = new Item("gamma", 10);
List<Item> items = new ArrayList<>();
items.add(i01);
items.add(i02);
items.add(i03);
System.out.println("Not sorted");
printItems(items);
System.out.println("\n");
Collections.sort(items, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
if (o1.getValue() > o2.getValue())
return 1;
else if (o1.getValue() < o2.getValue())
return -1;
return 0;
}
});
System.out.println("Sorted by value");
printItems(items);
System.out.println("\n");
Collections.sort(items, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return -o1.getName().compareTo(o2.getName());
}
});
System.out.println("Sorted reverse order by name");
printItems(items);
}
}
# 결과
Not sorted
alpha
beta
gamma
Sorted by value
gamma
alpha
beta
Sorted reverse order by value
gamma
beta
alpha
댓글 영역