Java:获取class个成员列表,用于多级嵌套列表中的列表

Java: Obtain class member list, for a list within multilevel nested list

在 Java 中,如何使用列表中的列表映射和获取 class 成员列表。

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

尝试使用此资源:仍然不走运,

将子列表转换为流并使用 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]

看来您需要使用 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());    
}