简体   繁体   中英

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"

to

"ab

cc dd ee

fff hhh"

Thanks for any help.

I would use stream for that job:

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)
  2. Iterate through the array. If the previousLength is smaller than the length of the currentString, insert a newline.
  3. Print the current string with a whitespace at the end.
  4. Set the variable in 1 to the length of the current string
  5. End of the loop

Please try to code this yourself, as this helps you to better understand 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();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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