Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation using nested streams

I have two lists of Strings, List categories, and List choices, and my objective is to concatenate contents of these 2 lists as-

List<String> categories = Arrays.asList(new String[]{"Cat-1" , "Cat-2", "Cat-3"});
List<String> choices = Arrays.asList(new String[]{"Choice-1" , "Choice-2", "Choice-3"});
List<String> result = new ArrayList<>(categories.size() * choices.size());
for (String cat : categories) {
    for (String choice: choices) {
        result.add(cat + ':' + choice);
    }
}

How can I achieve it using java Streams.

like image 703
Abhijeet srivastava Avatar asked Jan 05 '23 10:01

Abhijeet srivastava


1 Answers

You could use a simple flat map here:

 categories.stream()
          .flatMap(left -> choices.stream().map(right -> left + ":" + right))
          .collect(Collectors.toList())
like image 171
Eugene Avatar answered Jan 13 '23 10:01

Eugene