我想实现一个接口(interface),允许我使用以下默认方法从任何集合创建 map :
default <T_KEY> Map<T_KEY, T_ELEM> toMap(final Function<T_ELEM, T_KEY> getKey)
getKey
返回给定 T_ELEM
的 map 键。
应该这样调用:
Map<String, String> values = ExtCollection.of(list).toMap(it -> it.substring(0, 3));
如何检索集合以解决问题?
最佳答案
您的 API ExtCollection.of(list).toMap
需要保留对集合的引用,因为您不能仅将其实现为接口(interface)。
这是一个带有普通类的实现:
public class ExtCollection<T_ELEM> {
private Collection<T_ELEM> collection;
private ExtCollection(Collection<T_ELEM> collection) {
this.collection = collection;
}
public static <T_ELEM> ExtCollection<T_ELEM> of(Collection<T_ELEM> collection){
return new ExtCollection<>(collection);
}
public <T_KEY> Map<T_KEY, T_ELEM> toMap(final Function<T_ELEM, T_KEY> getKey){
return collection.stream().collect(Collectors.toMap(getKey, Function.identity()));
}
}
您也可以扩展接口(interface),但您需要调用 ExtCollection.of
方法内部的类。
public interface ExtCollection<T_ELEM> extends Collection<T_ELEM> {
...
default <T_KEY> Map<T_KEY, T_ELEM> toMap(final Function<T_ELEM, T_KEY> getKey){
return stream().collect(Collectors.toMap(getKey, Function.identity()));
}
static<T_ELEM> ExtCollection<T_ELEM> of(Collection<T_ELEM> collection){
return new ExtCollection<T_ELEM>() {
...
};
}
}
关于java - 将任何集合扭曲成 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616785/