我现在正在学习lambda,我想知道如何使用lambda在一行代码中编写此代码。
我有一个包括ID
和name
字段的Person
类。
目前,我有一个存储这些Person
对象的List<Person>
。我想要实现的是获取一个由人物id组成的字符串,就像"id1,id2,id3"。
如何使用lambda实现这个功能?
我现在正在学习lambda,我想知道如何使用lambda在一行代码中编写此代码。
我有一个包括ID
和name
字段的Person
类。
目前,我有一个存储这些Person
对象的List<Person>
。我想要实现的是获取一个由人物id组成的字符串,就像"id1,id2,id3"。
如何使用lambda实现这个功能?
map
Person ID映射到一个新的流中,然后可以在该流上应用Collectors.joining
。String result = personList.stream().map(Person::getId)
.collect(Collectors.joining(","));
String
),而是一个整数(int
)或其他原始数字类型,则应使用以下解决方案:String result = personList.stream().map(p -> String.valueOf(p.getId()))
.collect(Collectors.joining(","));
将流映射为map,然后收集到列表中!
List<String> myListofPersons = personList.stream()
.map(Person::getId)
.collect(Collectors.toList());
String res = String.join(" , ", myListStringId);
System.out.println(res);
您也可以如下使用 Collectors#mapping:
String ids = personList.stream().collect(mapping(Person::getId
, Collectors.joining(",")));
Person.ID
不是 CharSequence
的实例,则需要进行以下双重映射:String ids = personList.stream().collect(mapping(Person::getId
, mapping(String::valueOf
, Collectors.joining(","))));
/**
* @param separator used to join the values. NOTE: the separator is interpreted as a regular expression.
* @return a list of the values' string representation according to <code>mapper</code>, separated by the specified
* string. Null if list is null or empty.
*/
public static <R> String toListString(Collection<R> list, String separator,
Function<? super R, ? extends String> mapper)
{
if (list == null || list.isEmpty())
{
return null;
}
return list.stream()
.map(mapper)
.collect(Collectors.joining(separator));
}
和相应的反函数:
/**
* @param list a list of values, separated by the specified separator
* @param separator used to join the values. NOTE: the separator is interpreted as a regular expression.
* @param mapper the function to map a single string to a value.
* @return a list of the values. Empty if string is null or empty.
*/
public static <R> List<R> fromListString(String list, String separator,
Function<? super String, ? extends R> mapper)
{
if (list == null || list.isEmpty())
{
return new ArrayList<>();
}
return Arrays.stream(list.trim().split(separator))
.map(mapper)
.collect(Collectors.toCollection(ArrayList::new));
}
StringBuilder s = new StringBuilder();
for(R r : list){
if (s.length() != 0)
s.append(separator);
s.append(mapper.apply(r));
}
return s.toString();
并且:
List<R> result = new ArrayList<>();
for (String s : list.trim().split(separator)){
result.add(mapper.apply(s));
}
return result;
.map(Person::getId).map(String::valueOf)
进行翻译:将每个Person
对象的id
属性转换为字符串类型。 - shmosel