Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - map a list of objects to a list with values of their property attributes

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?

like image 749
mgamer Avatar asked Apr 10 '09 10:04

mgamer


People also ask

Can Java Map contain list?

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.


2 Answers

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

like image 96
Radhakrishna Sharma Gorenta Avatar answered Oct 13 '22 14:10

Radhakrishna Sharma Gorenta


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")); 
like image 26
Ulf Lindback Avatar answered Oct 13 '22 15:10

Ulf Lindback