I have the ViewValue class defined as follows:
class ViewValue {  private Long id; private Integer value; private String description; private View view; private Double defaultFeeRate;  // getters and setters for all properties }   Somewhere in my code i need to convert a list of ViewValue instances to a list containing values of id fields from corresponding ViewValue.
I do it using foreach loop:
List<Long> toIdsList(List<ViewValue> viewValues) {     List<Long> ids = new ArrayList<Long>();     for (ViewValue viewValue : viewValues) {       ids.add(viewValue.getId());    }     return ids;   }
Is there a better approach to this problem?
The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed: List of values and. List of keys from a Map.
We can do it in a single line of code using java 8
List<Long> ids = viewValues.stream().map(ViewValue::getId).collect(Collectors.toList());   For more info : Java 8 - Streams
You could do it in a one-liner using Commons BeanUtils and Collections:
(why write your own code when others have done it for you?)
import org.apache.commons.beanutils.BeanToPropertyValueTransformer; import org.apache.commons.collections.CollectionUtils;  ...  List<Long> ids = (List<Long>) CollectionUtils.collect(viewValues,                                         new BeanToPropertyValueTransformer("id")); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With