假设 getter()
方法返回 List<Object>
.假设 Object
类有getFirstName()
, getLastName()
,并尝试执行以下操作。
public List<<String,String>> getSomethingElse(@QueryParam("Id") Long Id) {
getter(id).stream().map(p -> new PDropDown<Object>(?).collect(Collectors.toList());
我希望它只返回 firstName
和 LastName
.我怎样才能映射对象,以便它只返回这两个?
最佳答案
请注意,getter() 方法必须返回特定类型,例如 List<Person>
而不是 List<Object>
否则你必须施放它。
这个想法是映射 firstName
和 lastName
到 PDropDown
提供接受它们的构造函数的实例:
你可以这样做:
List<DropDown> result =
getter(id).stream()
.map(p -> new PDropDown(p.getFirstName(), p.getLastName()))
.collect(Collectors.toList());
如果getter()
返回 List<Object>
,如果返回的元素之一不是 Person
,您可能会抛出异常:
List<DropDown> result =
getter(id).stream()
.map( o -> { if (o instanceof Person){
Person p = (Person) o;
return new PDropDown(p.getFirstName(), p.getLastName());
}
throw new IllegalArgumentException("o "+ o + " is not a Person");
})
.collect(Collectors.toList());
关于java - 映射 List<DropDown> 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770843/