我有一个允许按特定年份删除出版物的方法。然而,我想把所有的出版物,我将删除到一个新的数组和打印它们。
有什么建议或帮助吗?谢谢你。enter code here
public void removeYear(int removeYear)
{
Iterator<Publication> pb = publicationList.iterator();
while(pb.hasNext()){
Publication publication = pb.next();
if(publication.getYear() == removeYear){
pb.remove();
}
}
}
首先你应该做的是将方法的返回类型更改为List,因为除了删除部分,我们还希望将数据保存到新的List
,所以当调用该方法时,它将返回一个包含删除数据的List。
public List<Publication> removeYear(int removeYear){
你必须在方法中声明一个新的List of Publication,这样我们就可以保存已删除的Publications
List<Publication> listNew = new ArrayList<>();
我们用add()
方法保存对象
listNew.add(publication);
所有代码
public List<Publication> removeYear(int removeYear){
Iterator<Publication> pb = publicationList.iterator();
List<Publication> listNew = new ArrayList<>();
while(pb.hasNext()){
Publication publication = pb.next();
if(publication.getYear() == removeYear){
listNew.add(publication);
pb.remove();
}
}
return listNew;
}
这里我们已经返回了一个包含已删除出版物的新列表。
之后如果你想打印它只需调用
方法List<Publication> deletedList = classIntance.removeYear(2000);
并打印出来
System.out.println("Deleted Publication are");
deletedList.stream().forEach(System.out::println);
下面的方法可能不是可选的,但看起来更简洁:
- 按年份筛选要删除的出版物
- 使用
List::removeAll
完成移除:
public void removeYear(int removeYear) {
List<Publication> toDelete = publicationList.stream()
.filter(p -> p.getYear() == removeYear)
.collect(Collectors.toList());
// use publications from `toDelete` as needed
// ...
publicationList.removeAll(toDelete);
}
另一种方法可能基于使用Collectors.partitioningBy
收集器,它将根据谓词值将列表分成两部分:
public void removeYear(int removeYear) {
Map<Boolean, Publication> partitioned = publicationList.stream()
.collect(Collectors.partitioningBy(p.getYear() == removeYear));
System.out.println("deleted publications: " + partitioned.get(true));
// keep publications without the removeYear
publicationList = partitioned.get(false);
}