写一个Java代码给定一个list集合,里面包含5行文本,每行文本都由Int,String, Localdate,Int这几个数据类型组成,现在要根据Localdatede大小来排序并遍历输出每行文本
时间: 2024-01-11 11:04:52 浏览: 85
好的,以下是Java代码实现:
```java
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortListByLocalDate {
public static void main(String[] args) {
List<MyData> list = new ArrayList<>();
list.add(new MyData(2, "hello", LocalDate.of(2022, 2, 2), 5));
list.add(new MyData(1, "world", LocalDate.of(2021, 1, 1), 3));
list.add(new MyData(3, "java", LocalDate.of(2023, 3, 3), 7));
list.add(new MyData(5, "python", LocalDate.of(2025, 5, 5), 8));
list.add(new MyData(4, "javascript", LocalDate.of(2024, 4, 4), 6));
Collections.sort(list, Comparator.comparing(MyData::getLocalDate));
for (MyData data : list) {
System.out.println(data);
}
}
static class MyData {
private int num1;
private String str;
private LocalDate localDate;
private int num2;
public MyData(int num1, String str, LocalDate localDate, int num2) {
this.num1 = num1;
this.str = str;
this.localDate = localDate;
this.num2 = num2;
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
@Override
public String toString() {
return "MyData{" +
"num1=" + num1 +
", str='" + str + '\'' +
", localDate=" + localDate +
", num2=" + num2 +
'}';
}
}
}
```
这段代码中,我们首先定义了一个包含 MyData 对象的 list 集合,并初始化了其中的 5 个元素。然后,我们使用 `Collections.sort()` 方法和 `Comparator.comparing()` 方法对 list 进行排序,按照 MyData 对象的 `localDate` 属性从小到大排序。最后,我们使用 for 循环遍历输出每行文本。
阅读全文