在Java中,如何使用列表中的列表映射和获取类成员列表。
public class CustomerSales {
public List<Product> productList;
....
}
public class Product {
public List<ProductSubItem> productSubItemList
....
}
public class ProductSubItem {
public String itemName;尝试:
然而,这并没有得到itemName。寻找一种干净有效的方法,理想情况下可能要尝试4-5级深度,但是问题只有3种简单性,等等。
List<String> itemNameList = customerSales.productList.stream().map(p -> p.productSubItemList()).collect(Collectors.toList()); 使用Java 8
尝试使用此资源:仍然不是运气,How can I get a List from some class properties with Java 8 Stream?
发布于 2021-09-07 23:23:02
将子列表转换为流,并使用flatMap将元素流转换为元素流。
示例:
package x.mvmn.demo;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
public static class CustomerSales {
public List<Product> productList;
}
public static class Product {
public List<ProductSubItem> productSubItemList;
public List<ProductSubItem> getProductSubItemList() {
return productSubItemList;
}
}
public static class ProductSubItem {
public String itemName;
public ProductSubItem(String itemName) {
this.itemName = itemName;
}
public String getItemName() {
return itemName;
}
}
public static void main(String args[]) throws Exception {
// Setup mock data
CustomerSales customerSales = new CustomerSales();
Product p1 = new Product();
p1.productSubItemList = Arrays.asList(new ProductSubItem("p1 item one"), new ProductSubItem("p1 item two"));
Product p2 = new Product();
p2.productSubItemList = Arrays.asList(new ProductSubItem("p2 item one"), new ProductSubItem("p2 item two"));
customerSales.productList = Arrays.asList(p1, p2);
// Get list of item names
System.out.println(customerSales.productList.stream().map(Product::getProductSubItemList).flatMap(List::stream)
.map(ProductSubItem::getItemName).collect(Collectors.toList()));
// Alternative syntax
System.out.println(customerSales.productList.stream().flatMap(product -> product.productSubItemList.stream())
.map(subItem -> subItem.itemName).collect(Collectors.toList()));
}
}输出:
[p1 item one, p1 item two, p2 item one, p2 item two]
[p1 item one, p1 item two, p2 item one, p2 item two]发布于 2021-09-07 23:37:38
看起来您需要使用flatMap:
https://www.baeldung.com/java-difference-map-and-flatmap
List<String> itemNameList = customerSales.productList.stream().map(p -> p.productSubItemList().stream()).collect(Collectors.toList()); 这里是另一个列表扁平列表的例子,https://www.baeldung.com/java-flatten-nested-collections
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}https://stackoverflow.com/questions/69095381
复制相似问题