![](/img/trans.png)
[英]How can I call collect(Collectors.toList()) on a Java 8 Stream in Kotlin?
[英]How can I convert ArrayList<String> to ArrayList<Object> using .collect(Collectors.toList() in Java stream
如何在 Java stream 中使用.collect(Collectors.toList()
將ArrayList<String>
轉換為ArrayList<Object>
之前我用過
CommonList = detailUtils.SelectIDValueGetterObservable(getActivity()).stream()
.forEach(i -> CommonList.add(new foo(i));`
但是我遇到了這些副作用
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
這建議.collect(Collectors.toList()
我們該怎么做
這比你想象的要容易。 只需調用addAll
。
List<String> strList = new ArrayList<>();
strList.add("hello");
strList.add("world");
List<Object> genericList =new ArrayList<>();
genericList.addAll(strList);
System.out.println(genericList); //--> [hello,world]
當心,因為這也可能是危險的......
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
genericList.addAll(intList); //yeah, ok
boolean[] boolArray = new boolean[5];
genericList.add(boolArray); //why not
genericList.add(false); //no worries, it will cast it to Boolean
genericList.add(genericList); //so inclusive!
System.out.println(genericList);
//diversity badge achieved!-> [hello,world,1,2,[Z@232204a1,false,(this Collection)]
你不能“轉換”它(即改變它的類型),但你可以:
List<Object> list = new ArrayList<>(myStringList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.