List集合存入的多个对象,要使其对象中根据指定的字段进行升序或者降序。将使用 Collections.sort();
方法。
首先看Collections
的常用方法:
package com.company;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args){
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(5);
list.add(7);
list.add(9);
list.add(12);
System.out.print("初始顺序:");
list.forEach(v -> System.out.print(v+"\t"));
Collections.shuffle(list);
System.out.print("\n打乱顺序");
list.forEach(v -> System.out.print(v + "\t"));
Collections.reverse(list);
System.out.print("\n反转");
list.forEach(v -> System.out.print(v +"\t"));
Collections.swap(list,0,list.size()-1);
System.out.print("\n交换");
list.forEach(v -> System.out.print(v + "\t"));
Collections.sort(list);
System.out.print("\n排序后");
list.forEach(v -> System.out.print(v + "\t"));
System.out.print("\n二分查找数值7的位置:"+ Collections.binarySearch(list,7));
}
}
这里使用到Collections.sort();
方法,如下:
public static void main(String[] args) {
List<User> list = new ArrayList<>();
User user1 = new User();
user1.setId(1);
user1.setName("张三");
User user2 = new User();
user2.setId(2);
user2.setName("李四");
User user3 = new User();
user3.setId(3);
user3.setName("赵六");
list.add(user2);
list.add(user1);
list.add(user3);
Collections.sort(list);
for (User user : list) {
System.out.println(user);
}
}
package cn.goktech.daily.entity.vo;
import lombok.Data;
@Data
public class User implements Comparable<User>{
private Integer id;
private String name;
@Override
public int compareTo(User o) {
// return this.id-o.id;//升序
return o.id-this.id;//降序
}
}
接下来说说 按中文首字母排序的方法:
假设有个User
的类:
public class User{
private String name;
private int age;
}
有个user的List集合:
List<User> userList = Arrays.asList(
new User("张三", 18),
new User("李四", 37),
new User("王五", 50),
new User("赵六", 16),
new User("田七", 8)
);
按中文首字母排序实现
@Test
public void sort(){
// 获取中文环境
Comparator comparator = Collator.getInstance(Locale.CHINA);
// 排序实现
Collections.sort(userList , (e1, e2) -> {
return comparator.compare(e1.getName(), e2.getName());
});
// java8打印排序后的结果
userList .stream().forEach(System.out::println);
}
死鬼~看完了来个三连哦!O.O`
反手就是一个——————————奥里给