Java8: Stream displays two properties in one stream

I have a Model class with the following signature:

 class Model { private String stringA; private String stringB; public Model(String stringA, String stringB) { this.stringA = stringA; this.stringB = stringB; } public String getStringA() { return stringA; } public String getStringB() { return stringB; } } 

I would like to map a List<Model> to a List<String> containing both stringA and stringB in one thread

 List<String> strings = models.stream() .mapFirst(Model::getStringA) .thenMap(Model::getStringB) .collect(Collectors.toList()); 

or

 List<String> strings = models.stream() .map(Mapping.and(Model::getStringA,Model::getStringB)) .collect(Collectors.toList()); 

Of course, none of them compiles, but you get the idea.

How is this possible?

Edit:

Example:

 Model ab = new Model("A","B"); Model cd = new Model("C","D"); List<String> stringsFromModels = {"A","B","C","D"}; 
+5
source share
2 answers

You can have a list of all the values ​​one by one, for example:

 List<String> resultSet = modelList.stream() .flatMap(e -> Stream.of(e.getStringA(), e.getStringB())) .collect(Collectors.toList()); 

The function passed to flatMap will be applied to each element giving a Stream<String> . Using flatMap necessary here to collapse all nested Stream<Stream<String>> to a Stream<String> and therefore allow us to collect elements in a List<String> .

+7
source

flatMap is your friend here:

 models .stream() .flatMap(model -> Stream.of(model.getStringA(),model.getStringB())) .collect(Collectors.toList()); 

flatMap accepts Type R and expects to Stream (from the list, collections, Array) a new type of RR ago. For each model 1 you get n new elements (in this case, StringA and StringB ):

 {model_1[String_A1,String_B1] , model_2[String_A2,String_B2] , model_3[String_A3,String_B3]} 

All your items are n { [String_A1,String_B1], [String_A2,String_B2],[String_A3,String_B3]}

then flattened, which are placed in a new thread with a structure

{String_A1,String_B1,String_A2,String_B2,String_A3,String_B3}

of type String. It's like you have a new stream.

You can use flatMap , for example, when you have many collections / streams of elements that need to be combined into only one. For simpler explanations check this answer

+2
source

Source: https://habr.com/ru/post/1276155/


All Articles