有沒有一種速記方法(可能是番石榴或任何庫)來初始化這樣的Java列表?List list = MagicListUtil.newArrayList(firstElement, moreElementsList);
3 回答
HUH函數
如果您有數組,請使用
如果您有列表或其他
TA貢獻1836條經驗 獲得超4個贊
番石榴提供了多種可能性
如果您有數組,請使用Lists.asList(...)
String?first?=?"first";
String[]?rest?=?{?"second",?"third"?};
List<String>?list?=?Lists.asList(first,?rest);如果您有列表或其他Iterables,請使用FluentIterable.of(...).append(...).toList():
String?first?=?"first";
List<String>?rest?=?Arrays.asList("second",?"third");
List<String>?list?=?FluentIterable.of(first).append(rest).toList();但你也可以在 Java 8 中做到這一點
盡管它更加冗長,但仍然......
用數組
String?first?=?"first";
String[]?rest?=?{?"second",?"third"?};
List<String>?list?=?Stream.concat(Stream.of(first),?Arrays.stream(rest))
??.collect(Collectors.toList());帶有收藏
String?first?=?"first";
List<String>?rest?=?Arrays.asList("second",?"third");
List<String>?list?=?Stream.concat(Stream.of(first),?rest.stream())
??.collect(Collectors.toList());
拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
如果你想復制列表,你可以通過這樣的構造函數來完成
List<Float> oldList = new ArrayList<>(); List<Float> newList = new ArrayList<>(oldList);
慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
是的,您可以簡單地將 java.util.Arrays 類用于單個和多個元素。
List<String> strings = Arrays.asList("first", "second", "third");您可以將 java.util.Collections 用于具有單個元素的列表。
List<String> strings = Collections.singletonList("first");添加回答
舉報
0/150
提交
取消
