Java – how do I combine two streams?
•
Java
I'm trying to learn / understand the flow in Java and have this 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 hint on how to combine two streams into one stream?
——-Added 23.08 2018 – if we get rid of the IDS variable, it will improve the performance and the following code execution. Because we use set < integer > tagsids, there are no duplicates (for example, if tagids contains values (5,6,7,8,5,7), it can only be used for (5,8)) The modified code is as follows:
List <Tag> tags = (classA.getTags() != null ? classA.getTags() : new ArrayList<>()); List <Integer> tagIds = new ArrayList<>(Arrays.asList(5,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 such as the complexity of reading and debugging code
Solution
List<Tag> combinedTags = Stream
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());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码