【问题标题】:Fetch List of object from another list using java 8 [duplicate]使用java 8从另一个列表中获取对象列表[重复]
【发布时间】:2019-06-18 23:31:23
【问题描述】:
List<Customer> customers = findAllCustomer();   

public class Customer implements Serializable {

    private State state;

    //getter and setter

我在下面使用 jdk 7 接近

List<State> states = new ArrayList<>();

for (Customer customer : customers) {
    states.add(customer.getState());
}   

如何使用 jdk 8 实现相同的功能?

【问题讨论】:

  • 此外,原始代码并不糟糕,在 JDK8+ 上仍然可以正常工作...

标签: java


【解决方案1】:

值得一提的是,如果state 实际上是List&lt;state&gt; (states)

public class Customer implements Serializable {
private List<State> states;//Important note: I changed State to a List<State> here

//getter and setter

在这里获取states 的列表会有点棘手

List<State> states = customers.stream()
    .map(Customer::getStates)
    .filter(Objects::nonNull)//null check
    .flatMap(Collection::stream)
    .collect(Collectors.toList());

【讨论】:

  • 如果 state 已经是一个 List,那么 states.add 就不会起作用。 OP应该使用addAll
  • @user7 抱歉,我没有收到您的评论?我的回答提到了 OP 可能需要的另一种情况。我没说addaddAll
  • 如果是另一种情况,那就没问题了。但在 OP state 中不能是列表。所以,这并不能回答 当前 问题
  • @user7 你有没有看我的回答?我具体说Worth to mentions that if...,实际上我确实在第一个代码部分定义了List&lt;State&gt; states?还不够吗?
【解决方案2】:
List<State> states = customers.stream()
                              .map(Customer::getState)
                              .collect(Collectors.toList());

此外,您可以将此问题包装到 静态方法

public static List<State> getCustomerStates(List<Customer> customers) {
   return customers.stream()
                   .map(Customer::getState)
                   .collect(Collectors.toList());
}

...或函数

private static final Function<List<Customer>, List<State>> getCustomerStates =
        customers -> customers.stream()
                              .map(Customer::getState)
                              .collect(Collectors.toList());

【讨论】:

  • function 声明中有语法错误:将getCustomerStates 之后的 lambda 运算符替换为赋值运算符。
【解决方案3】:

使用 Lambda 和 forEach

customers.forEach(p -> {
        states.add(p.getState())  
      }
    );

【讨论】:

    【解决方案4】:
    List<State> states = new ArrayList<>();
    
    customers
        .stream()
        .map(Customer::getState)
        .forEach(states::add);
    

    【讨论】:

    • "List states = new ArrayList(); "如果您使用的是 java 8,为什么要声明数组列表?你不应该这样做。始终使用收集和收集器。这很糟糕。
    • @ABHISHEKHONEY 这还不错。那只是另一种方式。
    • @ABHISHEKHONEY 他们说“那更可取”还不错:) 因为它不需要改变集合并且它是可读的。
    【解决方案5】:

    流式传输内容,映射以获取状态并将其收集为列表。

    customers.stream()
        .map(Customer::getState)
        .collect(Collectors.toList());
    

    如果您需要 ArrayList 作为结果列表

    customers.stream()
        .map(Customer::getState)
        .collect(Collectors.toCollection(ArrayList::new));
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2019-04-09
      • 2021-10-05
      • 1970-01-01
      相关资源
      最近更新 更多