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

查看:18
本文介绍了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?

推荐答案

此答案基于这样一种想法,即您需要对代码中其他地方的不同实体和不同属性执行类似的操作.如果您需要按 ID 将 ViewValues 列表转换为 Longs 列表,那么坚持使用您的原始代码.但是,如果您想要一个更可重用的解决方案,请继续阅读...

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天全站免登陆