简体   繁体   English

更新list1中的参数 <object> 来自list2 <object> 通过使用java 8

[英]Update param in list1<object> from list2<object> by using java 8

I have two list of objects accounts and salaries and I need to iterate the list of objects. 我有两个对象帐户和工资列表,我需要迭代对象列表。 If the id matches I need to update the account object. 如果id匹配,我需要更新帐户对象。

I have list1 and list2 these two objects are different object type. 我有list1和list2这两个对象是不同的对象类型。 we need to update the object(param) in list1 with list2 object(param). 我们需要使用list2对象(param)更新list1中的对象(param)。

Example

if(accounts !=null && salaries!=null) { // checking for nulls
    for (Account obj1 : accounts) {// iterating objects
        for (Salary obj2 : salaries) {
            String id = ibj2.getId();
            if (id.equals(obj1.getId())) {// id checks  
                obj1.setxxxx(obj2.getxxxx());// set the value
            }
        }
    }
}  

I tried: 我试过了:

list1.stream().flatMap(x -> list2 .stream() .filter(y -> x.getId().equals(y.getId())));

Your flatMap (suggested in the comment), will produce a Stream<Salary> , which won't allow you do modify the corresponding Account instances. 您的flatMap (在评论中建议)将生成Stream<Salary> ,这将不允许您修改相应的Account实例。

You can create a Stream of Account s and their corresponding Salary and run forEach on that Stream : 您可以创建一个Account Stream及其相应的Salary并在该Stream上运行forEach

accounts.stream()
        .flatMap(a->salaries.stream()
                            .filter(s -> s.getID().equals(a.getID())
                            .map(s -> new SimpleEntry<Account,Salary)(a,s)))
        .forEach(e -> e.getKey().setxxxx(e.getValue().getxxxx()));

The final operation, obj1.setxxxx(obj2.getxxxx()); 最后的操作, obj1.setxxxx(obj2.getxxxx()); requires to have both obj1 and obj2 . 需要同时拥有obj1obj2 that dictates the item that is streamed from both lists 它决定了从两个列表中流式传输的项目

list1.stream()
    .forEach(obj1 -> 
        list2.stream()
            .filter(obj2 -> obj1.getId().equals(obj2.getId()))
            .findFirst()
            .ifPresent(obj2 -> obj1.setxxxx(obj2.getxxxx()))
    );

I would always suggest to create a Map since the lookup cost will decrease and it will become more readable. 我总是建议创建一个Map,因为查找成本会降低,并且会变得更具可读性。

Map<String, List<Salary>> salaryById = salaries.stream().collect(Collectors.groupingBy(Salary::getId));
accounts.forEach(a -> CollectionUtils.emptyIfNull(salaryById.get(a.getId())).forEach(s -> s.setxxxx(..)));

In case Account Salary <-> Account is One to One you change grouping to Collectors.toMap(..) 如果帐户薪水< - >帐户是一对一,您将分组更改为Collectors.toMap(..)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM