Java 8 使用Java8和Stream转换另一个类型中的嵌套列表类型
我有一个嵌套列表Java 8 使用Java8和Stream转换另一个类型中的嵌套列表类型,java-8,java-stream,nested-lists,Java 8,Java Stream,Nested Lists,我有一个嵌套列表 TypeOne有一个方法TypeTwo getTypeTwo(){return TypeTwo;} List<List<TypeOne>> nestedListsTypeOne = someMethodPopulate(); 但是,我不知道怎么做 将嵌套列表类型转换为其他类型的有效方式是什么?您需要的关键概念是 首先,为了获得更易于理解的代码,我将创建一个helper方法来进行内部转换: public class TypeOne { publ
TypeOne
有一个方法TypeTwo getTypeTwo(){return TypeTwo;}
List<List<TypeOne>> nestedListsTypeOne = someMethodPopulate();
但是,我不知道怎么做
将嵌套列表类型转换为其他类型的有效方式是什么?您需要的关键概念是 首先,为了获得更易于理解的代码,我将创建一个helper方法来进行内部转换:
public class TypeOne {
public static List<TypeTwo> convert(List<TypeOne> list) {
return list.stream()
.map(TypeOne::getTypeTwo)
.collect(Collectors.toList());
}
公共类TypeOne{
公共静态列表转换(列表){
return list.stream()
.map(TypeOne::getTypeTwo)
.collect(Collectors.toList());
}
然后将其应用于外部列表:
List<List<Type2>> result = nestedListsTypeOne
.stream()
.map(Type1::convert)
.collect(Collectors.toList());
List result=nestedliststypaune
.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;
}
公共静态列表translateType(列表嵌套ListTypeOne){
List nestedListTypeTwo=nestedListTypeOne
.stream()
.map(listTypeOne->{
返回listTypeOne.stream()
.map(typeOne->typeOne.getTypeTwo())
.collect(Collectors.toList());
})
.collect(Collectors.toList());
返回nestedListTypeTwo;
}
Convert方法应该是public
。而不是private
。是的,一般情况下。更新。nestedListTypeOne.stream().map(listTypeOne->listTypeOne.stream().map(typeOne->typeOne.getTypeTwo()).collect(Collectors.toList()).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;
}