How to use Collectors to combine List<String> into a String in Java

1 Answer

0 votes
package javaapplication1;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JavaApplication1 {

    public static void main(String[] args) {

        List<String> s = Arrays.asList("abc", "", "def", "", "uvw", "", "xyz");
        List<String> ls1 = s.stream().filter(str -> !str.isEmpty()).collect(Collectors.toList());

        System.out.println(ls1);
        
        String s2 = s.stream().filter(st -> !st.isEmpty()).collect(Collectors.joining(", "));
        System.out.println(s2);
    }
}

/*
run:

[abc, def, uvw, xyz]
abc, def, uvw, xyz

*/

 



answered Sep 5, 2016 by avibootz

Related questions

1 answer 195 views
1 answer 220 views
1 answer 183 views
1 answer 144 views
1 answer 195 views
...