简体   繁体   English

打印时将每行中相同值的数组元素分组 - Java

[英]Grouping array elements of same value in each line while printing - Java

there is a way to print elements of a String array sorted for word length at every line?有没有办法打印在每一行按字长排序的字符串数组的元素? So, considering the code below,所以,考虑下面的代码,

String[] arr = {"a", "b", "cc", "dd", "ee", "fff", "hhh"};
            
    for (int i = 0; i < 5; i++) {
        System.out.println(arr[i]);
    }

there is a way to change the output from:有一种方法可以改变输出:

"ab cc dd ee fff hhh" “ab cc dd ee fff hhh”

to

"ab "ab

cc dd ee cc dd ee

fff hhh" ffhhhh”

Thanks for any help.谢谢你的帮助。

I would use stream for that job:我会使用stream来完成这项工作:

Arrays.stream(arr).collect(
            Collectors.groupingBy(String::length, 
                    Collectors.joining(" ")))
      .values().forEach(System.out::println);
    

Output:输出:

a b
cc dd ee
fff hhh

Before spoilering the answer, I will give you some hints:在剧透回答之前,先给大家一些提示:

  1. Create a variable that stores the length of the previous string.创建一个变量来存储前一个字符串的长度。 (Set to Integer.MAX_Value for beginning) (设置为 Integer.MAX_Value 开始)
  2. Iterate through the array.遍历数组。 If the previousLength is smaller than the length of the currentString, insert a newline.如果 previousLength 小于 currentString 的长度,则插入换行符。
  3. Print the current string with a whitespace at the end.以空格结尾打印当前字符串。
  4. Set the variable in 1 to the length of the current string将1中的变量设置为当前字符串的长度
  5. End of the loop循环结束

Please try to code this yourself, as this helps you to better understand Java.请尝试自己编写代码,因为这有助于您更好地理解 Java。

So here is my take on this problem.所以这是我对这个问题的看法。 It doesn't involve using indices and avoids streams as this is not something a beginner should start with.它不涉及使用索引并避免使用流,因为这不是初学者应该开始的。

   public static void main(String[] args) {
        String[] arr = {"a", "b", "cc", "dd", "ee", "fff", "hhh"};
        int previousLength = Integer.MAX_VALUE;
    
        for (String currentString: arr){
            if(previousLength < currentString.length()){
                System.out.println("");
            }
            System.out.print(currentString+" ");
            previousLength = currentString.length();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM