【问题标题】:sorting a List<Object> numerically and alphabetically using Object product field使用 Object 产品字段按数字和字母顺序对 List<Object> 进行排序
【发布时间】:2021-06-18 20:15:48
【问题描述】:
List<ShipInventoryReportDataVO> lstShipInvData = shipInventoryReportDAO
    .getShippableInventoryReportData(inputVO, true);

ShipInventoryReportDataVO 是我的对象类并从存储过程中获取数据。在ShipInventoryReportDataVO 对象类中,我有一个名为productCode 的字段,productCode 的数据将以字母数字形式显示

0123, 
654, 
sparem, 
3205, 
the wholeland, 
10, 
1. 

当我对对象类中的productCode 进行排序时,我得到的输出为

0123
1
10
3205
654
sparem
wholeland.

这是我尝试排序的代码

List<ShipInventoryReportDataVO> lstShipInvData = shipInventoryReportDAO.getShippableInventoryReportData(inputVO, true);
                
Collections.sort(lstShipInvData, 
    (o1, o2) -> 
        (o1.getProductCode().compareTo(o2.getProductCode()))
);

还有这个

lstShipInvData = (List) lstShipInvData.stream()
        .sorted(Comparator.comparing(
            ShipInventoryReportDataVO::getProductCode
        ))
        .collect(Collectors.toList());

两个代码都得到如上的输出

但我需要如下输出

1
10
654
0123
3205
sparem
wholeland

这是我现在尝试的代码

List<ShipInventoryReportDataVO> productCodes = shipInventoryReportDAO.getShippableInventoryReportData(inputVO, true);

Comparator<String> byProductCode = Comparator.comparingInt(String::length)
                        .thenComparing(Comparator.naturalOrder());

productCodes.sort(Comparator.comparing(
                        ShipInventoryReportDataVO::getProductCode, byProductCode
));

productCodes.forEach(System.out::println);
System.out.println(productCodes.toString());

【问题讨论】:

  • 使 ShipInventoryReportDataVO 具有可比性,并在接口实现上编写您的自定义逻辑。
  • 无法获得所需的输出
  • @VijayRathod,请编辑并更新您的问题,详细说明哪些问题没有奏效。
  • @AlexRudenko 可能什么都没做,就等你做吧……
  • @m0skit0,很好的尝试咬... :)

标签: java arrays sorting object collections


【解决方案1】:

预期输出显示数据应先按产品代码长度排序,然后按字母顺序排序。

这可以通过链接比较器和使用Comparator.comparing(Function&lt;? super T,? extends U&gt; keyExtractor, &lt;? super U&gt; keyComparator) 来实现:

List<ShipInventoryReportDataVO> productCodes = Arrays.asList(
        new ShipInventoryReportDataVO("0123"),
        new ShipInventoryReportDataVO("654"),
        new ShipInventoryReportDataVO("sparem"),
        new ShipInventoryReportDataVO("3205"),
        new ShipInventoryReportDataVO("the wholeland"),
        new ShipInventoryReportDataVO("10"),
        new ShipInventoryReportDataVO("1")
);

Comparator<String> byProductCode = Comparator.comparingInt(String::length)
    .thenComparing(Comparator.naturalOrder());

productCodes.sort(Comparator.comparing(
    ShipInventoryReportDataVO::getProductCode, byProductCode
));

productCodes.forEach(System.out::println);

输出

1
10
654
0123
3205
sparem
the wholeland

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    相关资源
    最近更新 更多