我知道这个问题可能很奇怪,但我发现我一直在使用流,然后在我的程序中标准地映射列表,我认为它有点长,我在想是否真的可以将它重构为易于调用的简短方法,看起来像
public List<?> getStreamMap(List<?> list, String attribute)
这相当于:
list.stream().map(e->e.getAttribute).collect(Collectors.toList());
答案 0 :(得分:3)
我知道这个问题可能很奇怪,但我发现我一直在 使用流,然后在我的程序和我的列表上进行标准映射 认为它有点长,我在想它是否真的 可以将其重构为一个易于调用的简短方法 看起来像
public List getStreamMap(List list, String attribute)
您并没有那么离谱,您需要将 lambda 作为参数传递,即函数式接口 Function,即:
public <T> List<?> method(List <T> list, Function<T, ?> attribute){
return list.stream().map(attribute).collect(Collectors.toList());
}