使用Java 8将列表中的两个元素合并为一个元素。

huangapple go评论90阅读模式
英文:

Merge two elements of List into one element using Java 8

问题

我有一个List<Customer>,其中可能有两个相同的Customer对象。一个对象可能有一些属性填充,而另一个对象可能有其他属性填充。在Java 8中,是否有一种方法可以将这两个对象合并为一个对象,其中所有属性都填充,并且在最终的列表中只添加该对象。我已经编写了下面的代码,它能够满足我的需求,但我想使用Java 8的更简洁的方法。

List<Customer> list = entry.getValue();
if (StringUtils.hasLength(list.get(1).getID())) {
    list.get(0).setID(list.get(1).getID());
}
if (BigDecimal.ZERO.compareTo(list.get(1).getCreditAmount()) != 0) {
    list.get(0).setCreditAmount(list.get(1).getCreditAmount());
}
processedChargeTransactions.add(list.get(0));

我会尽力为您提供更简洁的Java 8解决方案。

英文:

I have a List<Customer> where I can have 2 objects of same Customer. One object can have few attributes populated while another object has some other attributes populated . Is their any way using Java 8 where I can merge 2 objects into 1 object which all attributes populated and in final list add only that object. I have written below code it is serving my purpose but I want some more cleaner approach using Java 8.

       List&lt;Customer&gt; list = entry.getValue();
			if (StringUtils.hasLength(list.get(1).getID())) {
				list.get(0).setID(list.get(1).getID());
			}
			if (BigDecimal.ZERO.compareTo(list.get(1).getCreditAmount()) != 0) {
				list.get(0).setCreditAmount(list.get(1).getCreditAmount());
			}
			processedChargeTransactions.add(list.get(0));

答案1

得分: 1

使用Java 8:

逻辑:

在这里,我使用Collectors.toMap函数将列表转换为Map,并使用合并函数。该合并函数将检查每个属性对应的键的值,如if-else块所示,如果值为null或未分配,则将值设置为与每个属性对应的另一个键的值。

***注意:***它也适用于具有相同id的多个对象,并且可以具有任意数量的属性,您只需要更新与每个属性对应的if-else块。

代码:

public class Test {
    public static void main(String[] args) {

        List<Customer> customers = new ArrayList<>();

        Customer c1 = new Customer();
        c1.setId(1);
        c1.setGender("Male");

        Customer c2 = new Customer();
        c2.setId(1);
        c2.setAddress("aaa");

        Customer c3 = new Customer();
        c3.setId(1);
        c3.setCreditAmount(100);

        customers.add(c1);
        customers.add(c2);
        customers.add(c3);

        System.out.println("合并前的列表:: " + customers);

        List<Customer> mergeList = customers.stream()
                .collect(Collectors.toMap(Customer::getId, Function.identity()
           ,(a, b) -> {
            if(a.getAddress() == null){
                a.setAddress(b.getAddress());
            }
            if(a.getCreditAmount() == 0.0){
                a.setCreditAmount(b.getCreditAmount());
            }
            if(a.getGender() == null){
                a.setGender(b.getGender());
            }
            return a;
        })).values().stream().toList();

        System.out.println("合并后的列表:: " + mergeList);
    }
}

输出:

合并前的列表:: [
Customer{id=1, creditAmount=0.0, address=null, gender=Male},
Customer{id=1, creditAmount=0.0, address=aaa, gender=null},
Customer{id=1, creditAmount=100.0, address=null, gender=null}
]
合并后的列表:: [Customer{id=1, creditAmount=100.0, address=aaa, gender=Male}]
英文:

Using Java 8:

Logic:

Here, I have converted the list into Map using Collectors.toMap function with the merger function. This merger function will check the value corresponding to the key for each attribute as shown in the if-else block and if value is null or not assigned, it will set the value from another key corresponding to each attribute.

Note: It will also work with multiple objects with same id and can have any number of attributes, you just need to update the if-else block corresponding to each attribute.

Code:

public class Test {
    public static void main(String[] args) {

        List&lt;Customer&gt; customers = new ArrayList&lt;&gt;();

        Customer c1 = new Customer();
        c1.setId(1);
        c1.setGender(&quot;Male&quot;);

        Customer c2 = new Customer();
        c2.setId(1);
        c2.setAddress(&quot;aaa&quot;);

        Customer c3 = new Customer();
        c3.setId(1);
        c3.setCreditAmount(100);

        customers.add(c1);
        customers.add(c2);
        customers.add(c3);

        System.out.println(&quot;list before merging:: &quot; + customers);

        List&lt;Customer&gt; mergeList = customers.stream()
                .collect(Collectors.toMap(Customer::getId, Function.identity()
           ,(a, b) -&gt; {
            if(a.getAddress() == null){
                a.setAddress(b.getAddress());
            }
            if(a.getCreditAmount() == 0.0){
                a.setCreditAmount(b.getCreditAmount());
            }
            if(a.getGender() == null){
                a.setGender(b.getGender());
            }
            return a;
        })).values().stream().toList();

        System.out.println(&quot;list after merging:: &quot; + mergeList);
    }
}

Output:

list before merging:: [
Customer{id=1, creditAmount=0.0, address=null, gender=Male},
Customer{id=1, creditAmount=0.0, address=aaa, gender=null},
Customer{id=1, creditAmount=100.0, address=null, gender=null}
]
list after merging:: [Customer{id=1, creditAmount=100.0, address=aaa, gender=Male}]

答案2

得分: 0

使用Stream的reduce方法来合并两个Customer对象的属性。

使用一个新的Customer对象初始化reduction,然后使用reduce方法遍历列表。

对于列表中的每个元素,检查属性是否存在,然后将它们合并到初始的Customer对象中。reduce操作的最终结果将是合并后的Customer对象。

List<Customer> list = entry.getValue();
if (list.size() == 2) {
    Customer mergedCustomer = list.stream()
            .reduce(new Customer(), (customer1, customer2) -> {
                if (StringUtils.hasLength(customer2.getID())) {
                    customer1.setID(customer2.getID());
                }
                if (BigDecimal.ZERO.compareTo(customer2.getCreditAmount()) != 0) {
                    customer1.setCreditAmount(customer2.getCreditAmount());
                }
                return customer1;
            });
    processedChargeTransactions.add(mergedCustomer);
}
英文:

Use the Stream's reduce method to merge the attributes of the two Customer objects.

Initialize the reduction with a new Customer object, and then iterate through the list using reduce.

For every element in the list, check if the attributes are present then merge them into the initial Customer object. The final result of the reduce operation will be the merged Customer object.

List&lt;Customer&gt; list = entry.getValue();
if (list.size() == 2) {
    Customer mergedCustomer = list.stream()
            .reduce(new Customer(), (customer1, customer2) -&gt; {
                if (StringUtils.hasLength(customer2.getID())) {
                    customer1.setID(customer2.getID());
                }
                if (BigDecimal.ZERO.compareTo(customer2.getCreditAmount()) != 0) {
                    customer1.setCreditAmount(customer2.getCreditAmount());
                }
                return customer1;
            });
    processedChargeTransactions.add(mergedCustomer);
}

huangapple
  • 本文由 发表于 2023年7月27日 14:38:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定