简体   繁体   English

从集合创建地图的Util方法

[英]Util method to create map from collection

I try to create static method that creates map of instance field as key and instance itself as value.我尝试创建静态方法,将实例字段的映射创建为键,将实例本身创建为值。 I tried something like this:我试过这样的事情:

public static <T> Map<Object, T> collectionToMap(Collection<T> collection, Function<Object, T> fieldExtractor) {
        return collection.stream()
                .collect(Collectors.toMap(fieldExtractor, e -> e));
    }

But when I tried pass a function as an argument.但是当我尝试将函数作为参数传递时。 I have compilation error, because getEmail() method non static, but toMap() static.我有编译错误,因为getEmail()方法非静态,但toMap()静态的。

ProjectUtils.collectionToMap(collection, User::getEmail);

How can I write static method with similar signature and pass non static method reference?如何编写具有相似签名的静态方法并传递非静态方法引用? Or maybe another approach exists to do this?或者也许存在另一种方法来做到这一点?

Write a generic method collectionToMap like so.像这样编写一个通用方法collectionToMap

public static <T, S> Map<S, T> collectionToMap(Collection<? extends T> collection,
    Function<? super T, ? extends S> fieldExtractor) {
    return collection.stream()
        .collect(Collectors.toMap(fieldExtractor, v -> v, (a, b) -> a));
}

Then the client code should be something like this.那么客户端代码应该是这样的。

ProjectUtils.collectionToMap(Collections.emptyList(), User::getEmail);

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

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