简体   繁体   English

Java var 类型推断泛型参数类型

[英]Java var type inference on generic parameter type

I'm having a merge-Function for a stream collector and trying to make it generical applicable.我有一个 stream 收集器的合并功能,并试图使其通用。 Since the lambda is accepting var as parameter type and the resulting type is of BinaryOperator, I'm trying to get something like BinaryOperator<?> or similar.由于 lambda 接受 var 作为参数类型并且结果类型是 BinaryOperator,因此我试图获得类似 BinaryOperator<?> 或类似的东西。

BinaryOperator<InsertYourFavouriteType> rejectNewValueAndWarn = (oldValue, newValue ) -> {
            LOGGER.warn( "Old value already present in map, rejecting to collect new value" );
            LOGGER.warn( "Old value:" + oldValue );
            LOGGER.warn( "New value:" + newValue );
            return oldValue;
        };

This is already pretty generic applicable, but I want to get rid of the explicit type in the generics parameter.这已经非常通用,但我想摆脱 generics 参数中的显式类型。

You can't do that directly 1 with a variable, but it is entirely possible using a method:您不能直接使用变量1执行此操作,但完全可以使用以下方法:

public final class Rejecter {
    public static <T> T rejectNewValueAndWarn(T oldValue, T newValue) {
        LOGGER.warn("Old value already present in map, rejecting to collect new value");
        LOGGER.warn("Old value:" + oldValue);
        LOGGER.warn("New value:" + newValue);
        return oldValue;
    }
}

Then you can use method references to reference the method directly:然后您可以使用方法引用直接引用该方法:

Map<A, B> map = whatever.stream()
    .collect(Collectors.toMap(
        ..., // your key mapper
        ..., // your value mapper
        Rejecter::rejectNewValueAndWarn // the merge function
    ));

1 You could define the generic parameter to be either ? 1您可以将通用参数定义为? or Object , but then you would need casts for every usage, like (BinaryOperator<SomeType>) rejectNewValueAndWarn , which effectively eliminates the whole purpose of extracting this logic into a common place.Object ,但是您需要针对每种用法进行强制转换,例如(BinaryOperator<SomeType>) rejectNewValueAndWarn ,这有效地消除了将这个逻辑提取到一个公共位置的整个目的。

Ok, after the hint with the generics type as type parameter I came up with having a mergefunction defined as follows:好的,在 generics 类型作为类型参数的提示之后,我想出了一个定义如下的合并函数:

static < K > BinaryOperator< K > mergeFunction()
    {
        BinaryOperator< K > rejectNewValueAndWarn = ( oldValue, newValue ) -> {
            LOGGER.warn( "Old value already present in map, rejecting to collect new value" );
            LOGGER.warn( "Old value:" + oldValue );
            LOGGER.warn( "New value:" + newValue );
            return oldValue;
        };
        return rejectNewValueAndWarn;
    }

blablaList.
            .stream()
            .collect( Collectors.toMap( AbstractDto::getName, Function.identity(), mergeFunction() ) );

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

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