koniga-ganica :
I'm trying to learn/understand streams in java and have this piece of code:
List <Tag> tags = (classA.getTags() != null ? classA.getTags() : new ArrayList<>());
List <Integer> tagsIds = new ArrayList<>(Arrays.asList(1,2,3,4));
List<Integer> ids = tags.stream().map(Tag::getId).collect(Collectors.toList());
tagIds.stream()
.filter(tagId -> !ids.contains(tagId))
.forEach(tagId -> {
Tag tag = new Tag();
tag.setId(tagId);
tags.add(tag);
});
Please, give me a tip how I can combine two streams into one?
------- Added 23.08.2018 --------
If we get rid of ids
variable it will improve a bit performance and code below perform as we work with Set <Integer> tagsIds
, so no duplicates (e.g. if tagIds
contains values (5,6,7,8,5,6,7) it will work only with (5,6,7,8)). Below the modified code:
List <Tag> tags = (classA.getTags() != null ? classA.getTags() : new ArrayList<>());
List <Integer> tagIds = new ArrayList<>(Arrays.asList(5,6,7,8,5,6,7));
tagIds.stream()
.filter(tagId -> !tags.stream().map(Tag::getId).collect(Collectors.toList()).contains(tagId))
.forEach(tagId -> {
Tag tag = new Tag();
tag.setId(tagId);
tags.add(tag);
});
This modification has disadvantages like the complexity of reading and debugging code
Fritz Duchardt :
List<Tag> combinedTags = Stream
.concat( // combine streams
tags.stream(),
tagIds.stream().map(Tag::new) // assuming constructor with id parameter
)
.distinct() // get rid of duplicates assuming correctly implemented equals method in Tag
.collect(Collectors.toList());