我創建了一些tuple
類,並將它們放入Java集合中。但是我不想直接在迭代collection時使用tuple
作爲函數參數。所以我實現了tuple解包,如下面的代碼。如何在Java中實現函數參數的元組解包?
基本上它的工作原理,但問題是,類型轉換,需要:
map((Func2<Long, Long, Long>) (a, b) -> a + b)
是否有什麼辦法可以去除這裏的類型轉換?
編輯:
也許是我沒有說清楚,不僅tuple2
,也tuple3
,tuple4
...應予支持。 @飛揚的回答作品大爲Tuple2
,但tuple2
,tuple3
,tuple4
在此期間不工作
package test;
import com.google.common.collect.Iterables;
import java.util.Arrays;
import java.util.function.Function;
import static test.TupleIterable.Tuple.tuple;
public interface TupleIterable<T> {
Iterable<T> apply();
static <E> TupleIterable<E> from(Iterable<E> iterable) {
return() -> iterable;
}
default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
return() -> Iterables.transform(TupleIterable.this.apply(), op::apply);
}
interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {
R apply(T1 t1, T2 t2);
@Override
default R apply(Tuple.Tuple2<T1, T2> t) {
return apply(t.t1, t.t2);
}
}
interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {
R apply(T1 t1, T2 t2, T3 t3);
@Override
default R apply(Tuple.Tuple3<T1, T2, T3> t) {
return apply(t.t1, t.t2, t.t3);
}
}
interface Tuple {
static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
return new Tuple2<>(t1, t2);
}
static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
return new Tuple3<>(t1, t2, t3);
}
class Tuple2<T1, T2> implements Tuple {
public T1 t1;
public T2 t2;
public Tuple2(T1 t1, T2 t2) {
this.t1 = t1;
this.t2 = t2;
}
}
class Tuple3<T1, T2, T3> implements Tuple {
public T1 t1;
public T2 t2;
public T3 t3;
public Tuple3(T1 t1, T2 t2, T3 t3) {
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
}
}
public static void main(String[] args) {
TupleIterable.from(Arrays.asList(1L, 2L))
.map(x -> tuple(x, x)) // map long to tuple2
.map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
.map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
.apply()
.forEach(System.out::println);
}
}
感謝您的好評!我還有一個問題,這是否支持其他元組,例如'Tuple3','Tuple4'等等......看來我需要創建很多方法,比如'mapToTuple3','mapToTuple4' ... – moshangcheng
'Tuple3Iterable ','Tuple4Iterable'不兼容。也就是說,參數不能在'Tuple3Iterable :: mapToTuple4'中解壓縮。 – moshangcheng
@moshangcheng如果你想成爲通用的,那麼你無法避免施放。 – Flown