如何使用方法参考/java归纳实用程序功能8 [英] How to generalize utility function using method references/java 8
问题描述
我遇到了一种常见情况,我有一个对象列表,需要生成一个具有单个属性的逗号分隔的字符串,然后每个字符串都用单引号引起来.
I've run into a common situation where i have a list of objects and need to generate a comma separated string with a single property, which are then each surrounded by single quotes.
2个示例
public String partIDsToString(List<Part> parts){
StringBuilder sb = new StringBuilder();
for(Part part : parts)
sb.append("'"+part.getPartNumber() + "',");
return sb.substring(0,sb.length()-1);
}
public String companyIDsToString(List<Company> parts){
StringBuilder sb = new StringBuilder();
for(Company c : parts)
sb.append("'"+c.getId() + "',");
return sb.substring(0,sb.length()-1);
}
将来我将需要创建更多这样的方法,并且想知道是否有一种方法可以推广这种功能,我正在寻找这样的东西.
I'll need to create more methods like this in the future, and was wondering if there was a way to generalize this functionality, im looking for something like this.
public String objectPropertyToString(List<Object> list, Method getProperty){
StringBuilder sb = new StringBuilder();
for(Object obj: list)
sb.append("'"+obj.getProperty() + "',");
return sb.substring(0,sb.length()-1);
}
List<Company> companies = getCompaniesList();//not important
String result = objectPropertyToString(companies , Company::getId);
List<Part> parts= getPartsList();//not important
String result = objectPropertyToString(parts, Part::getPartNumber);
可以使用方法引用/lambdas或任何其他方式来完成此操作吗?
Can this be done using method references/lambdas, or any other way?
推荐答案
Collectors.joining()
是您的朋友.
Stream.map()
and Collectors.joining()
are your friends here.
companies.stream()
.map(Company::getId)
.map(s -> "'" + s + "'")
.collect(joining(","));
您可以创建一个辅助方法,但是根据我的判断,以上内容很简洁,不值得:
You can create a helper method, but in my judgement the above is succinct enough that it isn't worthwhile:
static <T> String mapAndJoin(Collection<T> c, Function<T,String> f){
return c.stream()
.map(f)
.map(s -> "'" + s + "'")
.collect(joining(","));
}
mapAndJoin(companies, Company::getId);
这篇关于如何使用方法参考/java归纳实用程序功能8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!