英文:
Java one liner to create a list of String, add contents of another List<String> and return a List
问题
如何创建一个字符串列表,然后将另一个列表的所有内容添加到其中,然后返回该列表?
考虑一个函数:
public List<String> foo() {
return Arrays.asList("some", "list", "of", "strings", "from", "foo");
}
一个名为MyConstants的类:
public class MyConstants {
public static final String myConst = "String from Constant File";
}
我正在编写一个名为bar()
的函数,需要一个一行代码来返回一个列表:
public List<String> bar() {
List<String> result = new ArrayList<>(Collections.singleton(MyConstants.myConst));
result.addAll(foo());
return result;
}
但是addAll()
方法返回一个布尔值。另外,当我尝试以下代码时:
Arrays.asList(new ArrayList<>(Collections.singleton(MyConstants.myConst)).addAll(foo()));
由于明显的原因,它会返回一个 List<Boolean>
。
如何创建一个列表,将另一个列表添加到其中,然后返回合并后的列表?
英文:
How to create a List of String then add all the contents of another List to it and then return that list??
Consider a function:
public List<String> foo() {
return Arrays.asList("some", "list", "of", "strings", "from", "foo");
}
A Class MyConstants:
public MyConstants {
public static final String myConst = "String from Constant File";
}
I am writing a function bar()
and need a one liner to return a list:
public List<String> bar() {
return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo());
}
But addAll()
returns boolean. Also, when I tried
Arrays.asList(return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo()));
It is List<Boolean>
for pretty obvious reasons.
How can I create a list, add another list to it and then return that combined list?
答案1
得分: 1
为什么地球上会有一行的限制呢?Java集合对于流畅的表达并不是很好。但你可以滥用流(Streams):
public List<String> bar() {
return Stream.concat(Stream.of(MyConstants.myConst), foo().stream()).collect(Collectors.toList());
}
一种不那么糟糕的方法是使用Guava库:
public List<String> bar() {
return ImmutableList.<String>builder().add(MyConstants.myConst).addAll(foo()).build();
}
英文:
Why on earth is there a constraint of one line? Java collections are not great for fluent expressions. But you can abuse streams:
public List<String> bar() {
return Stream.concat(Stream.of(MyConstants.myConst), foo().stream()).collect(toList());
}
A less awful way is to use Guava libraries:
public List<String> bar() {
return ImmutableList.<String>builder().add(MyConstants.myConst).addAll(foo()).build();
}
答案2
得分: 0
多亏了 @gene 的回答,我找到了一个比 Stream 或者 ImmutableList builder 稍微好一些的 apache-commons 方法。在这里是它:
return ListUtils.union(Arrays.asList(MyConstants.myConst), foo());
英文:
Thanks to @gene for the answer, I figured out apache-commons one lesser awful way other than Stream or ImmutableList builder. Here it is
return ListUtils.union(Arrays.asList(MyConstants.myConst), foo());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论