Java - 将对象列表映射到包含其属性属性值的列表 [英] Java - map a list of objects to a list with values of their property attributes

查看:101
本文介绍了Java - 将对象列表映射到包含其属性属性值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将ViewValue类定义如下:

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
}

在我的代码中的某处我需要将ViewValue实例列表转换为包含来自相应ViewValue的id字段值的列表。

Somewhere in my code i need to convert a list of ViewValue instances to a list containing values of id fields from corresponding ViewValue.

我使用foreach循环执行此操作:

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?

推荐答案

编辑:这个答案是基于你需要为其他地方的不同实体和不同属性做类似事情的想法在你的代码中。如果需要将ViewValues列表转换为ID列表,请坚持使用原始代码。如果你想要一个更可重用的解决方案,请继续阅读......

This answer is based on the idea that you'll need to do similar things for different entities and different properties elsewhere in your code. If you only need to convert the list of ViewValues to a list of Longs by ID, then stick with your original code. If you want a more reusable solution, however, read on...

我会为投影声明一个接口,例如

I would declare an interface for the projection, e.g.

public interface Function<Arg,Result>
{
    public Result apply(Arg arg);
}

然后你可以写一个通用的转换方法:

Then you can write a single generic conversion method:

public <Source, Result> List<Result> convertAll(List<Source> source,
    Function<Source, Result> projection)
{
    ArrayList<Result> results = new ArrayList<Result>();
    for (Source element : source)
    {
         results.add(projection.apply(element));
    }
    return results;
}

然后你可以定义这样的简单投影:

Then you can define simple projections like this:

private static final Function<ViewValue, Long> ID_PROJECTION =
    new Function<ViewValue, Long>()
    {
        public Long apply(ViewValue x)
        {
            return x.getId();
        }
    };

并按照以下方式应用:

List<Long> ids = convertAll(values, ID_PROJECTION);

(显然使用K& R支撑和更长的线条会使投影声明更短一些:)

(Obviously using K&R bracing and longer lines makes the projection declaration a bit shorter :)

坦率地说,所有这些对于lambda表达式来说会好很多,但不要介意......

Frankly all of this would be a lot nicer with lambda expressions, but never mind...

这篇关于Java - 将对象列表映射到包含其属性属性值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆