Java
1import static java.util.Comparator.*;
2
3import java.util.ArrayList;
4import java.util.List;
5
6public class Sample {
7 public static void main(String[] args) throws Exception {
8 List<Member> list = new ArrayList<>();
9 list.add(new Member("name1", 2));
10 list.add(new Member("name2", 4));
11 list.add(new Member("name3", 1));
12 list.add(new Member("name4", 3));
13 list.add(new Member("name5", 2));
14
15 // 以下お好きな方を
16
17 // 昇順
18 list.sort(comparing(Member::getRank));
19 // 降順
20 // list.sort(comparing(Member::getRank, reverseOrder()));
21
22 list.forEach(System.out::println);
23 }
24}
25
26class Member {
27
28 private String name;
29
30 private int rank;
31
32 public Member(String name, int rank) {
33 super();
34 this.name = name;
35 this.rank = rank;
36 }
37
38 public String getName() {
39 return name;
40 }
41
42 public void setName(String name) {
43 this.name = name;
44 }
45
46 public int getRank() {
47 return rank;
48 }
49
50 public void setRank(int rank) {
51 this.rank = rank;
52 }
53
54 @Override
55 public String toString() {
56 return "[name=" + getName() + "][rank=" + getRank() + "]";
57 }
58}
59
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/05/28 12:56