如果你想有一个轻量级的视图来List
应用Function
和支持链接,你可以这样做:
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
public class MappingList<E> extends AbstractList<E> {
// using this helper class we avoid carrying <S> with the public API
static final class Source<E,S> {
final List<S> list;
final Function<? super S, ? extends E> mapper;
Source(List<S> l, Function<? super S, ? extends E> m) {
list=l;
mapper=m;
}
E get(int index) { return mapper.apply(list.get(index)); }
<T> Source map(Function<? super E, ? extends T> f) {
Objects.requireNonNull(f);
return new Source<>(list, mapper.andThen(f));
}
Stream<E> stream() { return list.stream().map(mapper); }
Stream<E> parallelStream() { return list.parallelStream().map(mapper); }
}
final Source<E,?> source;
private MappingList(Source<E,?> s) {
Objects.requireNonNull(s);
source=s;
}
@Override
public E get(int index) {
return source.get(index);
}
@Override
public int size() {
return source.list.size();
}
@Override
public Stream<E> stream() {
return source.stream();
}
@Override
public Stream<E> parallelStream() {
return source.parallelStream();
}
public <T> MappingList<T> map(Function<? super E, ? extends T> f) {
return new MappingList<>(source.map(f));
}
public static <S,T> MappingList<T> map(
List<S> l, Function<? super S, ? extends T> f) {
Objects.requireNonNull(l);
if(l instanceof MappingList)
return ((MappingList<S>)l).map(f);
return new MappingList<>(new Source<>(l, f));
}
}
它支持 GUAVA 风格的映射列表创建,同时仍然允许使用Stream
API 和映射列表懒惰地评估所有值:
public static void main(String[] arg) {
List<String> strings=Arrays.asList("a", "simple", "list");
List<Integer> ints=MappingList.map(strings, s->compute(s));
List<Integer> results=MappingList.map(ints, i->compute(i));
for(int result:results) {
System.out.println("first result: "+result);
System.out.println("Not computing any more values");
break;
}
System.out.println();
System.out.println(" interacting with stream API:");
System.out.println(results.stream().filter(i-> i>500).findFirst());
}
public static int compute(String s) {
System.out.println("doing computation for "+s);
return Integer.parseInt(s, 36);
}
public static int compute(int i) {
System.out.println("doing computation for "+i);
return i*i;
}
为 a 做计算
计算 10
第一个结果:100
不再计算任何值
与流 API 交互:
为 a 做计算
计算 10
做简单的计算
为 1724345618 做计算
可选[410277188]
如果你想创建一个List
预先计算好的值,你可以简单地使用new ArrayList<>(mappedList)
.