0

How to manipulate the string using stream API in Java. which api method is suitable.

I am trying some Java 8 features.

so lets say I have list of string

List<String> str = Arrays.asList("Hello World","Welcome America");
        List<String> res = str.stream()
                          .map(st -> st.split(" "))
                          .collect(Collectors.)); // here after Collectors what should I use. 
                          
                      
                      

my output should be like : [Hello Welcome, Wrold America]

hwrw by using map i am transforming the list but I am not getting any method to collect that. any help so i can do it by using stream.

1 Answer 1

4

It's not very clean or efficient, but here's one way:

List<String> res = IntStream.range(0, str.size())
        .mapToObj(i -> str.stream()
                .map(s -> s.split(" ")[i])
                .collect(Collectors.joining(" ")))
        .collect(Collectors.toList());

Ideone Demo

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answer, it works. let me see what Intstream do. also why this is not right aproch to do. i know the complexity and both traditional way and by using stream api. can you please give some light on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.