简体   繁体   English

如何使用转换器从其他类型的Iterable获取泛型类型安全的Iterble? (Java 7)

[英]How to get a generic type-safe Iterble from Iterable of other type, with a convertor? (Java 7)

In our project, we use proxies-based database API (Tinkerpop Frames), so we have a lot of loops like: 在我们的项目中,我们使用基于代理的数据库API(Tinkerpop框架),因此有很多循环,例如:

    List<Link> links = new LinkedList<>();
    for (LinkModel model : obj.getLinks())
    {
        Link l = new Link(model.getLink(), model.getDescription());
        links.add(l);
    }

I would like to get rid of these for two reasons: 我想摆脱这些有两个原因:

  1. To remove boilerplate code 删除样板代码
  2. For larger lists, memory issues may arise. 对于较大的列表,可能会出现内存问题。

Is there a nice way to get an Iterable that takes from the other one and converts using given method? 有没有一种很好的方法来获取一个从另一个中获取并使用给定方法进行转换的Iterable What I would like to do is: 我想做的是:

Iterable<Link> links_ = new IterableConverter<LinkModel, Link>(obj.getLinks()){
    public Link from(LinkModel m){ return new Link(m.getLink(), m.getDescription()); }
};

I guess there's something like that in Java 8. I need this for Java 7. 我猜Java 8中有类似的东西。Java7需要它。

I've spent a while battling the generics, and here's the result, which seems to work fine: 我花了一段时间与泛型作斗争,得到的结果似乎很好:

import java.util.Iterator;

/**
 * An Iterable that takes from the other Iterable and converts the items using given method.
 * The primary reason is to prevent memory issues which may arise with larger lists.
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public abstract class IterableConverter<TFrom, TTo> implements Iterable<TTo>, Converter<TFrom, TTo>
{
    final Iterable<TFrom> sourceIterable;

    public IterableConverter(Iterable<TFrom> sourceIterable)
    {
        this.sourceIterable = sourceIterable;
    }

    public abstract TTo from(TFrom m);


    @Override
    public Iterator<TTo> iterator()
    {
        return new IteratorBacked<TFrom, TTo>(sourceIterable.iterator(), this);
    }

    class IteratorBacked<TFromX extends TFrom, TToX extends TTo> implements Iterator<TToX> {

        private final Iterator<TFromX> backIterator;
        private final Converter<TFromX, TToX> converter;

        public IteratorBacked(Iterator<TFromX> backIterator, Converter<TFromX, TToX> converter)
        {
            this.backIterator = backIterator;
            this.converter = converter;
        }

        @Override
        public boolean hasNext()
        {
            return backIterator.hasNext();
        }


        @Override
        public TToX next()
        {
            return converter.from(backIterator.next());
        }

    }
}

interface Converter<TFromC, TToC> {
    TToC from(TFromC m);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM