【问题标题】:How to remove properties of objects in ArrayList如何删除 ArrayList 中对象的属性
【发布时间】:2018-06-21 10:10:13
【问题描述】:

我有一个返回大量数据的端点,我想删除其中的一部分。

例如:

A 类

public class A{

private String id;
private Date createOn;
private String processed;
}

B 类

public class B extends MongoDBObject{
private String id;
private Date createOn;
private String processed;
}

控制器

@RestController
@RequestMapping("/v1/read")
public class ReadController{

@Autowired
private StatementBundleService bundleService;

@CrossOrigin
@GetMapping(value = "/statementBundles")
public List<A> listStatements() {
   List<A> result = new ArrayList<A>();

   List<B> bundles = bundleService.getAll();

   for(B bundle: bundles) {
       result.add(new A(bundle));
   }

   return result;
}

我试图找出返回 A 列表的最佳方法是什么,而不需要从类 A 和类 B 中“处理”属性。

我应该只使用for each 循环还是iterator?我还应该将属性设置为null 还是其他方法?

【问题讨论】:

  • 如何从B 创建A
  • 为什么new A(bundle) 有效?你能修改那个构造函数不复制processed吗?
  • A 中有构造函数,其参数 B 用于设置属性。问题是A类在其他地方使用所以我不能修改这个构造函数
  • 是否可以从 A 中提取接口并使用它?然后,您可以根据某些要求创建 A 的多个实现。其中之一不会从初始化B-object 中复制processed 的值。

标签: java spring spring-restcontroller spring-rest


【解决方案1】:

我怀疑是否可以在不迭代的情况下更改属性。 尽管您可以尝试使用 java8 来获得快速简单的输出。看看soln。

public class Java8 {
public static void main(String[] args) {
    List<Student> myList = new ArrayList<Student>();
    myList.add(new Student(1, "John", "John is a good Student"));
    myList.add(new Student(1, "Paul", "Paul is a good Player"));
    myList.add(new Student(1, "Tom", "Paul is a good Teacher"));

    System.out.println(myList);//old list
    myList = myList.stream().peek(obj -> obj.setBiography(null)).collect(Collectors.toList());
    System.out.println(myList);//new list
}

/*Output*/
//[Student [id=1, Name=John, biography=John is a good Student], Student [id=1, Name=Paul, biography=Paul is a good Player], Student [id=1, Name=Tom, biography=Paul is a good Teacher]]
//[Student [id=1, Name=John, biography=null], Student [id=1, Name=Paul, biography=null], Student [id=1, Name=Tom, biography=null]]

}

学生所在的班级

public class Student{
private int id;
private String Name;
private String biography;

public Student(int id, String name, String biography) {
    super();
    this.id = id;
    Name = name;
    this.biography = biography;
}
public int getId() {
    return id;
}       
public String getBiography() {
    return biography;
}
public void setBiography(String biography) {
    this.biography = biography;
}
@Override
public String toString() {
    return "Student [id=" + id + ", Name=" + Name + ", biography=" + biography + "]";
}       
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2015-05-23
    • 2011-05-09
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多