映射列表中的对象<DropDown>
Map an object in List<DropDown>
假设 getter()
方法 returns List<Object>
。假设 Object
class 有 getFirstName()
、getLastName()
,并尝试执行以下操作。
public List<<String,String>> getSomethingElse(@QueryParam("Id") Long Id) {
getter(id).stream().map(p -> new PDropDown<Object>(?).collect(Collectors.toList());
我只想 return firstName
和 LastName
。我怎样才能映射对象,使其 return 只有这两个?
请注意,getter() 方法必须 return 特定类型,例如 List<Person>
而不是 List<Object>
,否则您必须强制转换它。
这个想法是将 firstName
和 lastName
映射到 PDropDown
实例,该实例提供接受它们的构造函数:
你可以这样做:
List<DropDown> result =
getter(id).stream()
.map(p -> new PDropDown(p.getFirstName(), p.getLastName()))
.collect(Collectors.toList());
If getter()
returns List<Object>
,如果其中一个元素 returned 不是 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());
假设 getter()
方法 returns List<Object>
。假设 Object
class 有 getFirstName()
、getLastName()
,并尝试执行以下操作。
public List<<String,String>> getSomethingElse(@QueryParam("Id") Long Id) {
getter(id).stream().map(p -> new PDropDown<Object>(?).collect(Collectors.toList());
我只想 return firstName
和 LastName
。我怎样才能映射对象,使其 return 只有这两个?
请注意,getter() 方法必须 return 特定类型,例如 List<Person>
而不是 List<Object>
,否则您必须强制转换它。
这个想法是将 firstName
和 lastName
映射到 PDropDown
实例,该实例提供接受它们的构造函数:
你可以这样做:
List<DropDown> result =
getter(id).stream()
.map(p -> new PDropDown(p.getFirstName(), p.getLastName()))
.collect(Collectors.toList());
If getter()
returns List<Object>
,如果其中一个元素 returned 不是 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());