使用Java 8从另一个列表中获取对象列表

时间:2019-01-25 06:32:51

标签: java

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实现相同的目的?

5 个答案:

答案 0 :(得分:5)

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

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

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

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

答案 1 :(得分:0)

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

customers
    .stream()
    .map(Customer::getState)
    .forEach(states::add);

答案 2 :(得分:0)

使用Lambda和forEach

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

答案 3 :(得分:0)

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());

答案 4 :(得分:0)

值得一提的是,如果state实际上是List<state>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());