Java Remove Rows Smaller Than 4 Characters

In this example we have String with rows some of them bigger than four characters and some of them smaller. We want to remove the smaller ones and then print the result. We use lines() method which create stream from Stream API and in which every element is a row from the string rows. Then we use filter and inside we put our test lambda expression to test if the row is bigger or equal than 4 characters. At the end we use collector with Collectors.joining(“\n”) which will create string and the separator “\n” will make new rows in the result string.

package org.example;

import java.util.stream.Collectors;

public class Main {

    private static String rows = """
            aaaa
            bbb
            ccccc
            dd
            eee
            fffff
            """;


    public static void main(String[] args) {
        String result = rows.lines().filter(l -> l.length() >= 4).collect(Collectors.joining("\n"));
        System.out.println(result);
    }
}
aaaa
ccccc
fffff

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.