2

Assume the getter() method returns List<Object>. Assume the Object class has getFirstName(), getLastName(), and trying to do the following.

public List<<String,String>> getSomethingElse(@QueryParam("Id") Long Id) {
    getter(id).stream().map(p -> new PDropDown<Object>(?).collect(Collectors.toList()); 

I want this to return only firstName and LastName. How can I map the object so it returns only those two?

Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306

1 Answers1

1

Note that the getter() method has to return a specific type for example List<Person> rather than List<Object> otherwise you have to cast it.
The idea would be to map firstName and the lastName to a PDropDown instance that provides a constructor that accepts them :

You could do that :

List<DropDown> result =  
    getter(id).stream()
              .map(p -> new PDropDown(p.getFirstName(), p.getLastName()))
              .collect(Collectors.toList()); 

If getter() returns List<Object>, you could throw an exception if one of the elements returned is not a 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()); 
davidxxx
  • 104,693
  • 13
  • 159
  • 179