在Java 8中将对象追加到列表并返回结果? [英] Append object to list and return result in Java 8?

查看:219
本文介绍了在Java 8中将对象追加到列表并返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种将对象附加到列表并以功能非强制性的方式在一行中返回结果的方法? 如果原始列表也不应发生变异,您将如何处理? 允许使用Java 8.

Is there a way of appending an object to a list and returning the result in one line in a functional non-imperative way? How would you do it if also the original list should not be mutated? Java 8 is allowed.

我已经知道如何在一行中合并两个列表. ()

I already know how to concat two lists in one line. (Source)

List listAB = Stream.concat(listA.stream(), listB.stream()).collect(Collectors.toList());

我也知道如何用一行对象列出一个列表.

I also know how to make a list out of objects in one line.

List listO1 = Collections.singletonList(objectA);
List listO2 = Stream.of(objectA, objectB).collect(Collectors.toList());
List listOO = Arrays.asList(objectA, objectB);

有什么比用以下几行替换第一行中的listB好吗?

Is there anything better than replacing listB in the first line with a part of the following lines?

推荐答案

您可以使用

List<Foo> newList = 
    Stream.concat(list.stream(), Stream.of(fooToAdd))
          .collect(Collectors.toList());

我发现这有点令人费解.力求提高可读性,而不是寻找单行,更晦涩的解决方案.另外,切勿像在问题中那样使用原始类型.

Bt I find this a little bit convoluted. Strive for readability rather than finding single-line, more obscure solutions. Also, never use raw types as you're doing in your question.

这篇关于在Java 8中将对象追加到列表并返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆