list.sort()与冒泡排序
示例代码:
//简单排序
public class ListSort {
public static void main(String[] args) {
List<Books> list = new ArrayList<>();
list.add(new Books("三国志", "陈寿", 10));
list.add(new Books("水浒传", "施耐庵", 50));
list.add(new Books("红楼梦", "曹雪芹", 30));
list.add(new Books("西游记", "吴承恩", 20));
System.out.println(list);
//sort排序 升序
list.sort((o1, o2)->{
return o1.getPrice().compareTo(o2.getPrice());
});
System.out.println(list);
//冒泡排序 降序
int size = list.size();
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 1 - i; j++) {
Books book01 = list.get(j);
Books book02 = list.get(j + 1);
if (book01.getPrice() < book02.getPrice()){
list.set(j, book02);
list.set(j + 1, book01);
}
}
}
System.out.println(list);
}
}
class Books{
String name;
String author;
Integer price;
public Books(String name, String author, Integer price) {
this.name = name;
this.author = author;
this.price = price;
}
@Override
public String toString() {
return "Books{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}
运行效果: