[英]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: 我想摆脱这些有两个原因:
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.