'how to get from Stream using FlatMap List<> of items with List
I have a Collection of a Dto (Pojo).
Collection<Dto> dtos = new ArrayList<>();
... <filling dto> now it has items.
Dto has a field List:
class Dto {
private List<Tag> tags;
}
@RequiredArgsConstructor
class Tag {
private String name;
}
Example of Data:
dtos.get(1) => new Tag('name1.1') -> new Tag('name1.2')
dtos.get(2) => new Tag('name2.1')
dtos.get(3) => new Tag('name3.1') > new Tag('name3.2')
dtos.get(4) => null
a QUESTIONL How to get using only stream Java8+ all List is it possible to use flatMap()
You ideas?
Solution 1:[1]
I think this should be straightforward, you filter the null tags then flatmap them and collect to a list
public static void main(String[] args) {
Dto dto1 = new Dto(Arrays.asList(new Tag("name1.1"), new Tag("name1.2")));
Dto dto2 = new Dto(Arrays.asList(new Tag("name2.1")));
Dto dto3 = new Dto(Arrays.asList(new Tag("name3.1"), new Tag("name3.2")));
Dto dto4 = new Dto(null);
Collection<Dto> dtos = new ArrayList<>(Arrays.asList(dto1, dto2, dto3, dto4));
List<Tag> tags = dtos.stream().filter(dto -> dto.getTags() != null).flatMap(dto ->
dto.getTags().stream()).collect(Collectors.toList());
}
Solution 2:[2]
You have a few issues with initialization and size of your buffers.
- The size of your buffer is too short by 1 byte that is needed for 0-termination. Adding the last number causes buffer overrun and undefined behaviour.
- In addition the calculated size is only sufficient as long as
number_of_ints<10because it only allows for single digit numbers. - That buffer is not initialized and us very likely not holding an empty string. Accessing it (via
strcatetc.) invokes undefined behaviour. - The size you provide to
snprintfis not related to the size of the buffer.
You should apply these changes:
#include <stdio.h>
#include <string.h>
int main(void)
{
int number_of_ints = 5;
char s[number_of_ints*2+1];
char suffix[4];
s[0] = 0;
for (int i = 1; i <= number_of_ints; i++)
{
snprintf(suffix, sizeof(suffix), "%d*", i);
strncat(s, suffix, 2);
printf("%s\n", s);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HariHaravelan |
| Solution 2 |
