[英]How to combine two streams?
我正在嘗試學習/理解java中的流並擁有這段代碼:
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);
});
請給我一個提示,告訴我如何將兩個流組合成一個流?
-------已添加23.08.2018 --------
如果我們擺脫ids
變量,它將改善一點性能和下面的代碼,因為我們使用Set <Integer> tagsIds
,所以沒有重復(例如,如果tagIds
包含值(5,6,7,8,5,6,7) )它只適用於(5,6,7,8))。 修改后的代碼下面:
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);
});
這種修改具有諸如讀取和調試代碼的復雜性之類的缺點
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());
首先,如果你有足夠的數據使用Set
會更快,我認為一個Tag
不能有重復的id ...你可以通過幾個步驟完成所有事情:
tagIds.removeAll(ids);
// assuming there is a Tag constructor that takes an Integer
List<Tag> newTags = tagIds.stream().map(Tag::new).collect(Collectors.toList())
tags.addAll(newTags);
Tag
類假定為
class Tag {
Integer id;
Integer getId() {
return id;
}
Tag(Integer id) {
this.id = id;
}
}
改進代碼的一種方法可能是尋找類似的東西: -
List<Integer> ids = tags.stream().map(Tag::getId).collect(Collectors.toList());
tagIds.stream().filter(tagId -> !ids.contains(tagId))
.map(Tag::new)
.forEach(tags::add);
除非您的Tag
類基於id
具有可比性,否則您實際上只需使用單個流 -
List<Tag> tags = Arrays.asList(new Tag(5),new Tag(6)); //example
List <Integer> tagIds = Arrays.asList(1,2,3,4); // from question
tagIds.stream().map(Tag::new)
.filter(tag -> !tags.contains(tag))
.forEach(tags::add);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.