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

Time:06-10

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.

CodePudding user response:

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

  •  Tags:  
  • java
  • Related