我正在嘗試對 Java 中的物件串列進行排序。每個物件包含兩個日期欄位Date1和Date2. 如果Date1不為空Date2,則應為空,如果Date2不為空,Date1則應為空。假設我們的類名是Product并且我們有一個inventoryListobject串列products。
products :[
{
"name":"abc",
...,
"Date1": "2021-04-18 10:36:34 PM",
...,
"Date2":"null",
...
},
"name":"def",
...,
"Date1": "null",
...,
"Date2":"2021-05-17 11:26:34 PM",
...
]
我想根據物件的任一日期按降序對該串列進行排序。提前致謝。
uj5u.com熱心網友回復:
您可以使用該Comparator.comparing()方法指定要在 lambda 運算式中排序的屬性。
record Product(String name, LocalDate Date1, LocalDate Date2) {}
List<Product> products = Arrays.asList(
new Product("abc", LocalDate.of(2021, 4, 18), null),
new Product("def", null, LocalDate.of(2021, 5, 17)));
products.sort(Collections.reverseOrder(
Comparator.comparing(p -> p.Date1() != null ? p.Date1() : p.Date2())));
products.stream()
.forEach(System.out::println);
輸出:
Product[name=def, Date1=null, Date2=2021-05-17]
Product[name=abc, Date1=2021-04-18, Date2=null]
uj5u.com熱心網友回復:
您可以嘗試使用以下方法使用流根據日期對資料進行排序。
在這里,我使用了 LocalDateTime 格式的日期而不是字串。
public class Test {
public static void main(String[] args) throws ParseException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a", Locale.ENGLISH);
Product p1 = new Product("abc", LocalDateTime.parse("2021-04-18 10:36:34 PM",formatter),null);
Product p2 = new Product("def",null,LocalDateTime.parse("2021-05-17 11:26:34 PM",formatter));
List<Product> sortedList = Stream.of(p1,p2)
.sorted(Comparator.comparing(x -> x.getDate1()!=null ? x.getDate1():x.getDate2(),
Comparator.nullsFirst(Comparator.reverseOrder())))
.collect(Collectors.toList());
System.out.println(sortedList);
}
}
產品.java
public class Product {
private String name;
private LocalDateTime date1;
private LocalDateTime date2;
public Product(String name, LocalDateTime date1, LocalDateTime date2) {
this.name = name;
this.date1 = date1;
this.date2 = date2;
}
//getters and setters
}
輸出:
[Product{name='def', date1=null, date2=2021-05-17T23:26:34},
Product{name='abc', date1=2021-04-18T10:36:34, date2=null}]
uj5u.com熱心網友回復:
Product我建議你像這樣處理類內的選擇日期邏輯
import java.util.Date;
public class Product {
private String name;
private Date dateOne;
private Date dateTwo;
public Product(String name, Date dateOne, Date dateTwo) {
this.name = name;
this.dateOne = dateOne;
this.dateTwo = dateTwo;
}
public Date getDate() {
if (this.dateOne != null) {
return dateOne;
}
return dateTwo;
}
}
然后在Inventory課堂上你可以這樣排序
public class Inventory {
public List<Product> sort(List<Product> products) {
products.sort((Product productOne, Product productTwo) -> {
if (productOne.getDate().before(productTwo.getDate())) {
return -1;
} else if (productOne.getDate().after(productTwo.getDate())) {
return 1;
} else {
return 0;
}
});
return products;
}
}
uj5u.com熱心網友回復:
您可以使用List.sort(Comparator<? super E>)對串列進行原位排序,提供Comparator- 說明如何Products比較兩個串列:
products.sort((x, y) -> {/* logics */})
現在您可以比較 on x,y即獲取和比較他們的日期、進行null檢查等,并回傳一個整數,其符號告訴您是否x按順序大于或小于y。
uj5u.com熱心網友回復:
如果您想使用 Streams,并且您無法更改Product-class,您可以實作自己的Comparator并在 Stream-logic 中使用它。
比較器示例:
public class ProductComparator implements Comparator<Product> {
@Override
public int compare(Product product1, Product product2) {
String product1Date = product1.getDate1() != null ? product1.getDate1() : product1.getDate2();
String product2Date = product2.getDate1() != null ? product2.getDate1() : product2.getDate2();
return product1Date.compareTo(product2Date);
}
}
使用 Streams 的排序可能如下所示:
List<Product> productListSorted = productList.stream()
.sorted(new ProductComparator())
.collect(Collectors.toList());
如果您只想對串列本身進行排序,可以使用:
productList.sort(new ProductComparator());
請注意,NullPointerException如果兩個 Dates 都是,則此 Comparator 將拋出 a null。
uj5u.com熱心網友回復:
您可以使用帶有自定義比較器的集合進行排序。在自定義比較器中,我檢查了哪個日期不為空,然后回傳比較結果。
class Product {
private String name;
private String date1;
private String date2;
public Product(String name, String date1, String date2) {
this.name = name;
this.date1 = date1;
this.date2 = date2;
}
public String getName() {
return this.name;
}
public String getDate1() {
return this.date1;
}
public String getDate2() {
return this.date2;
}
}
public class SortProductsByDate {
public static void main(String[] args) {
List<Product> inventoryList = new ArrayList<>();
inventoryList.add(new Product("abc", "2021-04-18 10:36:34 PM", null));
inventoryList.add(new Product("def", null, "2021-05-17 11:26:34 PM"));
Collections.sort(inventoryList, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
String d1 = p1.getDate1() == null ? p1.getDate2() : p1.getDate1();
String d2 = p2.getDate1() == null ? p2.getDate2() : p2.getDate1();
return d2.compareTo(d1);
}
});
for(Product p : inventoryList) {
System.out.printf("name: %s\nDate1: %s\nDate2: %s\n\n", p.getName(), p.getDate1(), p.getDate2());
}
}
}
控制臺輸出:
name: def
Date1: null
Date2: 2021-05-17 11:26:34 PM
name: abc
Date1: 2021-04-18 10:36:34 PM
Date2: null
您還可以進一步分離邏輯并清理 main 方法。在 Product 類中實作比較器并為 ProductInventory 創建一個單獨的類。還請記住,當您覆寫 compareTo() 時,您還應該注意 equals() 和 hashcode() 方法以避免任何問題。我在 IDE 中自動生成了這些欄位。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
class Product implements Comparable<Product>{
private String name;
private String date1;
private String date2;
public Product(String name, String date1, String date2) {
this.name = name;
this.date1 = date1;
this.date2 = date2;
}
public String getName() {
return this.name;
}
public String getDate1() {
return this.date1;
}
public String getDate2() {
return this.date2;
}
@Override
public int compareTo(Product other) {
String thisDate = this.getDate1() == null ? this.getDate2() : this.getDate1();
String otherDate = other.getDate1() == null ? other.getDate2() : other.getDate1();
return otherDate.compareTo(thisDate);
}
@Override
public int hashCode() {
return Objects.hash(date1, date2, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
return Objects.equals(date1, other.date1)
&& Objects.equals(date2, other.date2)
&& Objects.equals(name, other.name);
}
@Override
public String toString() {
String date = date1 == null ? date2 : date1;
return "[name:" name ", date=" date "]";
}
}
class ProductInventory {
private List<Product> inventoryList;
public ProductInventory() {
this.inventoryList = new ArrayList<Product>();
}
public List<Product> getInventoryList() {
return this.inventoryList;
}
public void add(Product p) {
this.inventoryList.add(p);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(Product p : inventoryList) {
sb.append(p.toString());
sb.append("\n");
}
return sb.toString();
}
}
public class SortProductsByDateDescending {
public static void main(String[] args) {
ProductInventory productInventory = new ProductInventory();
productInventory.add(new Product("abc", "2021-04-18 10:36:34 PM", null));
productInventory.add(new Product("def", null, "2022-03-08 03:30:24 AM"));
productInventory.add(new Product("ghi", null, "2021-05-17 11:26:34 PM"));
productInventory.add(new Product("jkl", "2025-01-22 01:33:16 AM", null));
productInventory.add(new Product("mno", "2025-01-22 01:33:16 PM", null));
productInventory.add(new Product("pqr", "2025-01-22 01:33:17 PM", null));
Collections.sort(productInventory.getInventoryList());
System.out.println(productInventory.toString());
}
}
控制臺輸出:
[name:pqr, date=2025-01-22 01:33:17 PM]
[name:mno, date=2025-01-22 01:33:16 PM]
[name:jkl, date=2025-01-22 01:33:16 AM]
[name:def, date=2022-03-08 03:30:24 AM]
[name:ghi, date=2021-05-17 11:26:34 PM]
[name:abc, date=2021-04-18 10:36:34 PM]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/522668.html
標籤:爪哇列表弹簧靴排序收藏品
上一篇:如何按行對專案進行排序?
