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

后端 未结 8 1762
星月不相逢
星月不相逢 2020-12-01 01:28

I have the ViewValue class defined as follows:

class ViewValue {

private Long id;
private Integer value;
private String description;
private View view;
priv         


        
相关标签:
8条回答
  • 2020-12-01 02:06

    You can populate a map from the properties of a list of objects (say id as key and some property as value) as below

    Map<String, Integer> mapCount = list.stream().collect(Collectors.toMap(Object::get_id, Object::proprty));
    
    0 讨论(0)
  • 2020-12-01 02:11

    You could ude a wrapper:

    public class IdList impements List<Long>
    {
        private List<ViewValue> underlying;
    
        pubic IdList(List<ViewValue> underying)
        {
            this.underlying = underying;
        }
    
        public Long get(int index)
        {
            return underlying.get(index).getId()
        }
    
        // other List methods
    }
    

    though thats even more tedious work, it could improve performance.

    You could also implement your and my solution genericaly using reflection, but that woud be very bad for perforance.

    Theres no short and easy generic solution in Java, Im afraid. In Groovy, you would simply use collect(), but I believe that involves reflection as well.

    0 讨论(0)
提交回复
热议问题