[英]How to populate an ArrayList<String> from ArrayList<Object>
Is there a smarter way to populate this list of strings by getting the collection of gameList and converting the Game objects to strings? 通过获取gameList的集合并将Game对象转换为字符串,是否有更聪明的方法来填充此字符串列表?
ArrayList<Game> gameList = getAllGames();
ArrayList<String> stringList = new ArrayList<String>();
for (Game game : gameList) {
stringList.add(game.toString());
}
Using Java 8: 使用Java 8:
ArrayList<String> stringList = gameList.stream().map(Object::toString).collect(Collectors.toCollection(ArrayList::new));
(Note: I haven't yet tested this.) (注意:我尚未对此进行测试。)
You could use new Java 8 lambdas and streams : 您可以使用新的Java 8 lambda和流 :
List<String> stringList = getAllGames().stream()
.map(game -> game.toString())
.collect(Collectors.toList());
Look at that, wonderful! 看着那,太好了!
Well, I would prefer to use the List
interface, that way you can swap the List
implementation out without changing caller code. 好吧,我更喜欢使用
List
接口,这样您可以在不更改调用者代码的情况下换出List
实现。 Also, you could use the diamond operator . 另外,您可以使用diamond运算符 。 Finally, you could construct the new
ArrayList
with an optimal initial capacity - 最后,您可以使用最佳初始容量构造新的
ArrayList
List<Game> gameList = getAllGames();
List<String> stringList = new ArrayList<>(gameList.size());
for (Game game : gameList) {
stringList.add(game.toString());
}
Or a new helper method like, 或新的辅助方法,例如
public static List<String> getStringList(List<?> in) {
List<String> al = new ArrayList<>(in != null ? in.size() : 0);
for (Object obj : in) {
al.add(obj.toString());
}
return al;
}
then 然后
List<String> stringList = getStringList(gameList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.