我正在尝试对Java中的一个对象列表进行排序。每个对象包含两个日期字段Date1
和Date2
。如果Date1
不为空,则Date2
应为空,如果Date2
不为空,则Date1
应为空。假设我们的类名为Product
,我们有一个对象products
的列表inventoryList
。
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",
...
]
我想把这个列表按照对象的日期降序排列。提前感谢。
6条答案
按热度按时间qq24tv8q1#
您可以使用
Comparator.comparing()
方法,指定要在Lambda运算式中排序的属性。输出:
nwnhqdif2#
您可以尝试使用以下方法,使用数据流根据日期对数据进行排序。
产品.java
输出:
oipij1gg3#
我建议您这样处理
Product
类中的选择日期逻辑然后在
Inventory
类中,您可以这样排序a6b3iqyw4#
你可以使用
List.sort(Comparator<? super E>)
对列表进行原位排序,提供一个Comparator
a-一个如何比较两个Products
的指令:现在,您可以比较
x
和y
,即获取并比较它们的日期,执行null
检查等,并返回一个整数,其正负号表明x
是大于还是小于y
。f0ofjuux5#
如果你想使用流,并且你不能改变
Product
-类,你可以实现你自己的Comparator
并在流逻辑中使用。比较器示例:
使用流进行的排序可能如下所示:
如果只想对列表本身进行排序,可以用途:
请注意,如果两个日期都是
null
,则此比较器将引发NullPointerException
。xytpbqjk6#
您可以使用带有自定义比较器的集合进行排序。在自定义比较器中,我检查了哪个日期不为空,然后返回比较结果。
控制台输出:
您还可以进一步分离逻辑并清理main方法。在Product类中实现比较器,并为ProductInventory创建一个单独的类。另外,请记住,在重写compareTo()时,还应注意equals()和hashcode()方法,以避免出现任何问题。我在IDE中自动生成了这些字段。
控制台输出: