【问题标题】:How to consider space at the end while sorting in Java在Java中排序时如何考虑最后的空间
【发布时间】:2020-06-28 08:02:54
【问题描述】:

我有一个字符串列表。

TagSort-Test-CA-ASSET-ID1_ tag4
 TagSort-Test-CA-ASSET-ID13_tag
 TagSort-Test-CA-ASSET-ID1_ 6th_tag
 TagSort-Test-CA-ASSET-ID1_tag1
 TagSort-Test-CA-ASSET-ID1_tag2
 TagSort-Test-CA-ASSET-ID1_tag5

当我这样做时

 List<String> test = Arrays.asList(
            "TagSort-Test-CA-ASSET-ID1_ tag4",
            "TagSort-Test-CA-ASSET-ID13_tag",
            "TagSort-Test-CA-ASSET-ID1_ 6th_tag",
            "TagSort-Test-CA-ASSET-ID1_tag1",
            "TagSort-Test-CA-ASSET-ID1_tag2",

            "TagSort-Test-CA-ASSET-ID1_tag5");
        Collections.sort(test);
        System.out.println(test);

输出为[TagSort-Test-CA-ASSET-ID13_tag, TagSort-Test-CA-ASSET-ID1_ 6th_tag, TagSort-Test-CA-ASSET-ID1_ tag4, TagSort-Test-CA-ASSET-ID1_tag1, TagSort-Test-CA-ASSET-ID1_tag2, TagSort-Test-CA-ASSET-ID1_tag5]

我怎样才能得到订单 [TagSort-Test-CA-ASSET-ID13_tag, TagSort-Test-CA-ASSET-ID1_ 6th_tag, TagSort-Test-CA-ASSET-ID1_tag1, TagSort-Test-CA-ASSET-ID1_tag2,TagSort-Test-CA-ASSET-ID1_ tag4, TagSort-Test-CA-ASSET-ID1_tag5]

这是我从 postgres DB 获得的格式。我也需要在 Java 中保持相同的行为。

【问题讨论】:

  • 你的尝试是什么?你知道 postgress DB 遵循什么模式吗?

标签: java sorting collections java-8 comparator


【解决方案1】:

Postgress DB 排序看起来正在删除空格,例如以下输出与您的预期输出相似:

test.stream()
    .map(s -> s.replace(" ", ""))
    .sorted()
    .forEach(System.out::println);

但是由于现在映射了实际数据,因此您最终会丢失它,因此将实际字符串映射为输入键和删除空格的字符串作为值可以为您解决:

test.stream()
    .map(s -> new AbstractMap.SimpleEntry<>(s, s.replace(" ", "")))
    .sorted(Map.Entry.comparingByValue())
    .map(AbstractMap.SimpleEntry::getKey)
    .forEach(System.out::println);

【讨论】:

  • stackoverflow.com/questions/37984264/… Collat​​e 是造成这种行为差异的罪魁祸首
  • @SantoshHegde 嗯,很有趣,谢谢分享,如果我需要的话,会收藏以备将来参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 2013-05-18
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2021-03-15
相关资源
最近更新 更多