使用 Java 8,使用 Stream 将类型嵌套列表转换为另一种类型
convert type Nested List in another type using Java 8, using Stream
我有一个嵌套列表
TypeOne
有一个方法 TypeTwo getTypeTwo() { return typeTwo;}
List<List<TypeOne>> nestedListsTypeOne = someMethodPopulate();
我要获得List<List<typeTwo>>
如何翻译?
nestedListsTypeOne.stream()
.foreach(listTypeOne -> map(TypeOne -> TypeOne::getTypeTwo))
.HereIHavingProblem
但是,我不知道该怎么做。
将嵌套列表类型转换为另一种类型的有效方式是什么?
您需要的关键概念是Collectors。
首先为了更容易理解的代码,我会制作一个辅助方法来进行内部转换:
public class TypeOne {
public static List<TypeTwo> convert(List<TypeOne> list) {
return list.stream()
.map(TypeOne::getTypeTwo)
.collect(Collectors.toList());
}
然后你将它应用到你的外部列表:
List<List<Type2>> result = nestedListsTypeOne
.stream()
.map(Type1::convert)
.collect(Collectors.toList());
尝试...
public static List<List<TypeTwo>> translateType(List<List<TypeOne>> nestedListTypeOne) {
List<List<TypeTwo>> nestedListTypeTwo = nestedListTypeOne
.stream()
.map(listTypeOne -> {
return listTypeOne.stream()
.map(typeOne -> typeOne.getTypeTwo())
.collect(Collectors.toList());
})
.collect(Collectors.toList());
return nestedListTypeTwo;
}
我有一个嵌套列表
TypeOne
有一个方法 TypeTwo getTypeTwo() { return typeTwo;}
List<List<TypeOne>> nestedListsTypeOne = someMethodPopulate();
我要获得List<List<typeTwo>>
如何翻译?
nestedListsTypeOne.stream()
.foreach(listTypeOne -> map(TypeOne -> TypeOne::getTypeTwo))
.HereIHavingProblem
但是,我不知道该怎么做。
将嵌套列表类型转换为另一种类型的有效方式是什么?
您需要的关键概念是Collectors。
首先为了更容易理解的代码,我会制作一个辅助方法来进行内部转换:
public class TypeOne {
public static List<TypeTwo> convert(List<TypeOne> list) {
return list.stream()
.map(TypeOne::getTypeTwo)
.collect(Collectors.toList());
}
然后你将它应用到你的外部列表:
List<List<Type2>> result = nestedListsTypeOne
.stream()
.map(Type1::convert)
.collect(Collectors.toList());
尝试...
public static List<List<TypeTwo>> translateType(List<List<TypeOne>> nestedListTypeOne) {
List<List<TypeTwo>> nestedListTypeTwo = nestedListTypeOne
.stream()
.map(listTypeOne -> {
return listTypeOne.stream()
.map(typeOne -> typeOne.getTypeTwo())
.collect(Collectors.toList());
})
.collect(Collectors.toList());
return nestedListTypeTwo;
}