Java 8如何操作一个列表中的对象并将其收集到另一个列表中?

时间:2018-02-27 18:58:32

标签: java lambda foreach java-8 java-stream

我是Java8的新手。我需要按照特定条件将POJO列表转换为组,并在UI上显示。

  • 将属于Children类别的对象列表转换为Person 类别。
  • 返回列表。

    Children.java
    private String firstName;
    private String lastName;
    private String school;
    private String personId;
    // Setters and getters.
    
    Person.java
    private String fullName;
    private String address;
    // Setters and Getters.
    
    private Person convertChildToPerson(Children child) {
             Person person = new Person();
             person.setFullName(child.getLastName() + ", " + child.getFirstName());
              ..
              return person;
     } 
    

    ..     主要代码..    ..

    List<Person> personList;  // Is populated by other functions.
    
    // Connect to DB and gets the output
    List<Children> childrenList = (Children) criteria.list();  
    
    for(Children children: childrenList) {
         personList.add(convertChildToPerson(children));
    }
    return personList; 
    

    上面的 FOR-LOOP 是否可以被Java 8 Streams取代?

1 个答案:

答案 0 :(得分:4)

@property int idCell;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.idCell = indexPath.row
    [self performSegueWithIdentifier:@"detailViewController" sender:sender];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"detailViewController"]) {
        SecondVC *vc = [segue destinationViewController];
        vc.idDetail = idCell;
    }
}

如Holger所建议的那样更短(更好):

 List<Person> newList = childrenList.stream()
             .map(this::convertChildToPerson)
             .collect(Collectors.toList());

 personList.addAll(newList);