简体   繁体   中英

Java8 Collections Merge two different list with different objects and a common field

I have two classes with one common field in it. Basing on the common field department it need get the list of all the records and total amount

What is the best way to merge the records basing on the department id and sum the amount for each department id?

// "ABC",(sum(1234.00f+1000.00f))
// "pqr",(sum(1200.00f+500.00f)))
    // Expecting result as line 33, 34
package com.coll.java8.foreach;

public class Plist {
    private String department;
    private String posiName;
    private  double amount;
    


}
package com.coll.java8.foreach;

public class MList {
    
    private String nameString;
    private int id;
    private String department;

    

}
package com.coll.java8.foreach;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.maxBy;

import java.math.MathContext;

public class Managers {
    
    public static void main(String args[]) {
    
    
    List<MList> manList = new ArrayList<MList>();

    manList.add(new MList("Test1",123,"ABC"));
    manList.add(new MList("Test2",134,"pqr"));
    manList.add(new MList("Test3",456,"xyz"));
    
    List<Plist> posslist = new ArrayList<Plist>();
    
    posslist.add(new Plist("ABC","555",1234.00f));
    posslist.add(new Plist("pqr","444",1200.00f));
    posslist.add(new Plist("ABC","555",1000.00f));
    posslist.add(new Plist("xyz","555",25.00f));
    posslist.add(new Plist("pqr","444",500.00f));

    // "ABC",(sum(1234.00f+1000.00f))
    // "pqr",(sum(1200.00f+500.00f)))
    // Expecting result as line 33, 34

}

I have two classes with one common field in it.

No, you don't. You have two classes that each have a field that happens to have the same name. Java does not treat that as a "common field" since there is no inheritance or shared interface.

What you need to do is something like this:

public abstract class BaseRecord {
  protected String department;

  public String getDepartment() { return department; }
}

public class PList extends BaseRecord {
...
}

Some of your request is a little hard to follow, but if you want to sum the amount for PList you can do it something like this with a List :

double total = myList.stream()
  .map(item -> item.getAmount())
  .sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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