将对象属性列表加入String

时间:2017-05-29 15:16:11

标签: java lambda java-8 java-stream

我现在正在学习lambda,我想知道如何用lambda一行编写这段代码。

我有一个 var n = 0; var dynamicObject; scope.widgetItems = {}; angular.forEach(scope.report.executeResult.rowData, function (i) { var a = scope.report.executeResult.rowData[n].values[0].value; var name = 'a'; dynamicObject = { [eval(name)]: scope.report.executeResult.rowData[n].values[1].value }; scope.widgetItems[n] = dynamicObject; n++; });` 课程,其中包含PersonID字段

目前,我有name存储这些List<Person>个对象。我想要完成的是获取一个由人的id组成的字符串,就像。

“ID1,ID2,ID3”即可。

我怎样才能用lambda完成这个?

4 个答案:

答案 0 :(得分:28)

要检索由分隔符String分隔的所有ID组成的",",您首先必须map Person ID&#39}然后您可以应用Collectors.joining新流。

String result = personList.stream().map(Person::getId)
                          .collect(Collectors.joining(","));

如果您的ID字段不是String,而是int或其他原始数字类型,那么您应该使用以下解决方案:

String result = personList.stream().map(p -> String.valueOf(p.getId()))
                          .collect(Collectors.joining(","));

答案 1 :(得分:3)

流映射,并收集到列表!

List<String> myListofPersons = personList.stream()
          .map(Person::getId)
          .collect(Collectors.toList());

如果你在String对象中需要它,那么加入列表

String res = String.join(" , ", myListStringId);
System.out.println(res);

答案 2 :(得分:1)

略微过度设计,但如果更频繁地出现此问题(特别是如果使用默认映射器和分隔符添加委托给此方法的重载方法),则会有所帮助:

/**
 * @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;

答案 3 :(得分:1)

您还可以使用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(","))));