前言:
每日一點點,先貼程式碼再說!
程式碼:
@Data@ToString@AllArgsConstructor@NoArgsConstructorstatic class User { private Integer id; private String name;}public static void main(String[] args) { // 構造陣列 User[] userArray = {new User(1, "1"), new User(2, "2")}; System.out.println(Arrays.toString(userArray)); // 一般寫法 Arrays.sort(userArray, new Comparator<User>() { public int compare(User u1, User u2) { if (u1.id < u2.id) { return 1; } else if (u1.id > u2.id) { return -1; } return 0; } }); System.out.println(Arrays.toString(userArray)); // 簡寫方式1 Arrays.sort(userArray, (User u1, User u2) -> { return u1.name.compareTo(u2.name); }); System.out.println(Arrays.toString(userArray)); // 簡寫方式2 Arrays.sort(userArray, (a, b) -> { return b.name.compareTo(a.name); }); System.out.println(Arrays.toString(userArray));}
@Data@ToString@AllArgsConstructor@NoArgsConstructorstatic class User { private Integer id; private String name;}public static void main(String[] args) { // 構造List List<User> userList = Arrays.asList(new User(1, "1"), new User(2, "2")); System.out.println(userList); // 一般寫法 Collections.sort(userList, new Comparator<User>() { @Override public int compare(User u1, User u2) { if (u1.id < u2.id) { return 1; } else if (u1.id > u2.id) { return -1; } return 0; } }); System.out.println(userList); // 簡寫方式1 Collections.sort(userList,(User u1,User u2)->{ return u1.name.compareTo(u2.name); }); System.out.println(userList); // 簡寫方式2 Collections.sort(userList,(u1,u2)->{ return u2.name.compareTo(u1.name); }); System.out.println(userList);}
最新評論