【问题标题】:How to sort a String with folderIDs in Java如何在 Java 中使用文件夹 ID 对字符串进行排序
【发布时间】:2016-12-20 18:44:06
【问题描述】:

我想知道如何使用文件夹ID 对String 进行排序。我的String 的输出是这样的:

6.8
7.4.1
10
11
1
2
3
1.1
11.1
4
1.2
10.1
2.1
5
1.3
2.2
3.1
6
2.3
3.2
4.1
7
3.3
4.2
5.1
8
4.3
5.2

我需要将这些 ID 放入我的 JTree 中,并且需要对其进行排序。

那么排序后的String 应该是这样的:

1
1.1
1.2
2
2.1
2.2
3
etc.

or 

1
2
3
1.1
1.2
2.1
2.2
etc.

我怎样才能做到这一点?

【问题讨论】:

  • 我假设您的意思是 String[] 而不是 String。 (如果没有,您将不得不从单个 String 对象中创建一个数组。)您是否尝试简单地对数组进行排序?
  • 创建一个custom Comparator
  • 好的,我现在已经从我的字符串中创建了一个数组,如下所示: String[] array = new String[] {list};我现在如何对这个数组进行排序?
  • 这个数组只有一个元素...我们不能对一个元素进行排序(重新排序)。如果您的字符串代表多行,那么您可以考虑将其拆分为行分隔符。在 Java 中 split 方法采用正则表达式,并且由于 Java 8 表示行分隔符,我们可以使用 \R 所以尝试使用 String[] elements = yourString.split("\\R");。检查这是否是您想要的,然后我们可以考虑对这样的数组进行排序。

标签: java string sorting


【解决方案1】:

如果数组的每个输入由空格分隔,您可以使用 split() 方法并选择类似 yourArray.split("\\s+") 的内容,或者如果它们有结束行字符,您可以使用 yourArray.split( "\\n") 表示行尾字符。此方法根据 split 方法中的内容返回您拆分的字符串,并返回一个包含拆分的每个部分的数组。

例如 "1.2 2.3 8.9.7 4.2".split("\\s+") 给出一个包含 {"1.2", "2.3", "8.9.7", "4.2"} 的数组您可以将数组输入我提供的方法中。

public static String[] sortString(String[] input)
{
    HashMap<Integer, String> mappedInputs = new HashMap<>();
    ArrayList<Integer> values = new ArrayList<>();

    for(String value : input)
    {
        //check that the input is a valid number
        if(value.replace(".", "").matches("\\d+"))
        {
            mappedInputs.put(Integer.parseInt(value.replace(".", "")), value);
            values.add(Integer.parseInt(value.replace(".", "")));
        }
    }
    //use the collections built in method to sort
    Collections.sort(values);
    String[] sortedStrings = new String[values.size()];
    //now grab the sorted numbers and add their mapped string values to the String array
    for(int i = 0; i < values.size(); i++)
    {
        sortedStrings[i] = mappedInputs.get(values.get(i));
        //debug to make sure they are sorted
        System.out.println(sortedStrings[i]);
    }

    return sortedStrings;

}

public static void main(String[] args) {
    String[] yourArray = {"1.2", "3", "2.1", "7.4.5"};
    sortString(yourArray);
}//main method

我并没有使用 Comparator 来展示如何在没有 Comparator 的情况下完成此操作,以防您还没有学习 Comparator,并且只使用基本数据结构来完成基本相同的事情。但是 Comparator 更加灵活,如果您已经学会了如何创建它们,请使用它们。

【讨论】:

  • 感谢您的帮助,但我不知道如何调用此方法。我已经从 public static void main(String[] args) {} 中实现了这个方法,我的数组在 public static void main(String[] args) {} 中。所以我不能用我的数组来喂这个方法......或者我做错了。我试图将该方法放入 public static void main(String[] args) { ...} 但它给我一个错误。
  • 您需要将函数设为静态,因为您在另一个静态方法中使用它,因此将函数名称从“public String[] sortString(String[] input)”更改为“public static String[] sortString (字符串[] 输入)"
  • 我收到这条消息:Illegal modifier for the variable sortString;只有 final 是允许的,这个:Void 方法不能返回值
  • 我编辑了你的数组应该是什么的答案。您不需要使用最终类型对象
  • 非常感谢您的代码和示例运行良好,但 myarray 没有排序。也许数组没有以正确的方式拆分。
猜你喜欢
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 2012-10-14
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多