![](/img/trans.png)
[英]Java 8 - Lambda Expression Convert List<String> to List<DTO>
[英]How to use a Java 8 Lambda expression to convert a List of one type to a List of its subtype
我似乎只能在C#而不是Java中找到如何做到這一點。
我有一個List<TypeX>
但我知道該列表中的每個元素實際上都是TypeX
Called TypeY
的子類。
如何編寫接受List<TypeX>
並返回List<TypeY>
的Lambda表達式?
對於我的例子,我將使用以下類:
class TypeX {}
class TypeY extends TypeX {}
然后我有一個List<TypeX>
:
final List<TypeX> xList = ...
您需要做的就是使用TypeY.class.cast
的方法引用:
final List<TypeY> yList = xList.stream()
.map(TypeY.class::cast)
.collect(toList());
您還可以filter()
以排除將導致錯誤的項目:
final List<TypeY> yList = xList.stream()
.filter(TypeY.class::isInstance)
.map(TypeY.class::cast)
.collect(toList());
使用示例:
import static java.util.stream.Collectors.toList;
使用map
方法在Java中進行投影:
List<TypeY> res = listTypeX
.stream()
.map((x) -> (TypeY)x)
.collect(Collectors.toList());
只是所有使用lambda的map
都會強制轉換元素:
List<TypeX> list = ...;
List<TypeY> castList =
list.stream().map(x -> (TypeY)x).collect(Collectors.toList());
您可以使用Eclipse Collections中的 selectInstancesOf()
:
MutableList<TypeX> xList = Lists.mutable.empty();
MutableList<TypeY> yList = xList.selectInstancesOf(TypeY.class);
如果您無法從List
更改xList:
List<TypeX> xList = Lists.mutable.empty();
List<TypeY> yList = ListAdapter.adapt(xList).selectInstancesOf(TypeY.class);
注意:我是Eclipse Collections的貢獻者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.