I\'m writing an adapter framework where I need to convert a list of objects from one class to another. I can iterate through the source list to do this as in
Java: Best
Here's an on-the-fly approach. (There must be something already like this in the jdk; I just can't find it.)
package com.gnahraf.util;
import java.util.AbstractList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
*
*/
public class Lists {
private Lists() { }
public static List transform(List source, Function mapper) {
return new ListView(source, mapper);
}
protected static class ListView extends AbstractList {
private final List source;
private final Function mapper;
protected ListView(List source, Function mapper) {
this.source = Objects.requireNonNull(source, "source");
this.mapper = Objects.requireNonNull(mapper, "mapper");
}
@Override
public V get(int index) {
return mapper.apply(source.get(index));
}
@Override
public int size() {
return source.size();
}
}
}