有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何根据字符串的长度对其进行分组?

public class sortingtext {

    public static void main(String[] args) throws IOException {
            String  readline="i have a sentence with words";
            String[] words=readline.split(" ");

            Arrays.sort(words, (a, b)->Integer.compare(b.length(), a.length()));

            for (int i=0;i<words.length;i++)
            {
                int len = words[i].length();

                int t=0;

                System.out.println(len +"-"+words[i]);
            }

        }

输入:

i have a sentence with words

我的代码拆分一个字符串,然后它应该打印每个单词及其长度

我得到的输出如下所示:

8- sentence

5- words

4- have

4-with

1-I

1-a

我想将相同长度的单词分组,得到:

8- sentence

5- words

4- have ,with

1- I ,a

但我不知道如何将它们分组


共 (2) 个答案

  1. # 1 楼答案

    如果您是初学者或不熟悉stream API:

    public static void main(String[] args) {
        String  readline= "i have a sentence with words";
        String[] words = readline.split(" ");
        Arrays.sort(words, (a, b)->Integer.compare(b.length(), a.length()));
        // declare a variable to hold the current string length
        int currLength = -1;
        for(int i = 0; i<words.length; i++){
            if(currLength == words[i].length()){
                // if currLength is equal to current word length just append a comma and this word
                System.out.print(", "+words[i]);
            }
            else{
                // if not update currLength, jump to a new line and print new length with the current word
                currLength = words[i].length();
                System.out.println();
                System.out.print(currLength+ " - "+words[i]);                
            }
        }
    }
    

    注:println(“…”)方法打印字符串“…”并将光标移动到新行。印刷品(“…”)方法只打印字符串“…”,但不会将光标移动到新行。因此,后续打印指令将在同一行上打印。println()方法也可以在没有参数的情况下使用,以将光标定位到下一行

  2. # 2 楼答案

    轻松使用流API:

    final Map<Integer, List<String>> lengthToWords = new TreeMap<>(
        Arrays.stream(words)
            .collect(Collectors.groupingBy(String::length))
    );
    

    流按长度将单词分组到一个映射中(实现细节,但它将是一个HashMap),然后TreeMap根据关键字(单词长度)对该映射进行排序

    或者,你可以这样写,效率更高,但在我看来可读性较差

    final Map<Integer, List<String>> lengthToWords = Arrays.stream(words)
        .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));