Search code examples
javafiltercollectionsjava-streamoutput

How can i print the final output of program in a single line with space in between after using filter of java 8?


If I provide the input as pass@123 jes@234 12345 human. The output should print as pass@123 jes@234 in a single line with space in between. But it is printing as pass@123jes@234 without any space. Below is my code.

List<String> splitList = Arrays.asList(ans.split(" "));
        
splitList.stream().filter(s -> !s.matches("[0-9]+") && 
    !s.matches("[a-zA-Z]+") && s.length() > 5)
.collect(Collectors.toList()).forEach(System.out::print);

I tried to provide System.out.print but the output is printed with no spaces in between.


Solution

  • I suggest using Collectors.joining

    Here is some helpful Documentation, there are some other useful Collectors as well.

    https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

    example code

    import java.util.Arrays;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
    
    public class Test {
    
        public static void main(String[] args) {
    
            String ans = "pass@123 jes@234 12345 human";
    
            final String space = " ";
            
            String line = Arrays.stream(ans.split(space))// you can use Arrays.stream directly, without calling Arrays.asList first
                .filter(giveMeSomeMeaningFulName()) //separated into separate method to improve readability
                .collect(Collectors.joining(space));//Collectors.joining join the strings with the provided string as separator
    
            System.out.println(line);
        }
    
        private static Predicate<? super String> giveMeSomeMeaningFulName() {
            return s -> !s.matches("[0-9]+") && !s.matches("[a-zA-Z]+") && s.length() > 5;
        }
    }