java - 如何在2个不同类型的列表中查找元素匹配并使用java 8流连接它们?

标签 java java-8 java-stream

我有两个不同类型的员工和贷款列表

List<CsvVo> csv1Records = CsvParser.getRecodrsFromACsv(csv1, csv1Headers, "employee");
List<CsvVo> csv2Records = CsvParser.getRecodrsFromACsv(csv2, csv2Headers, "loan");

我想知道 csv1Records 列表中是否存在与 csv2Records 贷款列表中具有相同 empid 的员工。

这是我对此的最佳尝试之一,

List<OutputData> result = csv1Records.stream().flatMap(x -> csv2Records.stream().filter(y -> x.get(CsvParser.key1).getProprieties().get("empid").equals(y.get(CsvParser.key2).getProprieties2().get("empid"))).map(y -> new OutputData(x.get(CsvParser.key1).getNameOfEmployee(),
                                                                                                                                                                                                                                               x.get(CsvParser.key1).getProprieties(),
                                                                                                                                                                                                                                               y.get(CsvParser.key2).getNameOfLoan(),
                                                                                                                                                                                                                                               y.get(CsvParser.key2).getProprieties2()))).collect(Collectors.toList());

mergingresults.csv 中的结果如下:

nameOfEmployee,proprieties,nameOfLoan,proprieties
Kevin,{"empid":1,"age":50,"education":"abc college"},pc,{"loan":4777.00,"balance":280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},home,{"loan":140000.00,"balance":60080.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},kitchen,{"loan":4000.00,"balance":3280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},car,{"loan":140000.00,"balance":60080.0,"empid":1}
Carole,{"empid":2,"age":25,"education":"koala college"},health,{"loan":1400,"balance":2800.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},trip,{"loan":14000.00,"balance":6080.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},food,{"loan":400.00,"balance":328.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},education,{"loan":14000.00,"balance":60080.0,"empid":2}

上面的结果与我想要的和我的需求不同,如下所述:

nameOfEmployee,proprieties,nameOfLoan,proprieties
Kevin,{"empid":1,"age":50,"education":"abc college"},pc,{"loan":4777.00,"balance":280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},home,{"loan":140000.00,"balance":60080.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},kitchen,{"loan":4000.00,"balance":3280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},car,{"loan":140000.00,"balance":60080.0,"empid":1}
Carole,{"empid":2,"age":25,"education":"koala college"},health,{"loan":1400,"balance":2800.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},trip,{"loan":14000.00,"balance":6080.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},food,{"loan":400.00,"balance":328.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},education,{"loan":14000.00,"balance":60080.0,"empid":2}
Sebastian,{"empid":3,"age":47,"education":"Rubbits college"},null,null
Daniel,{"empid":4,"age":30,"education":"Pencil college"},null,null
David,{"empid":5,"age":20,"education":"Kodi college"},null,null
Michael,{"empid":6,"age":19,"education":"red college"},null,null
Alain,{"empid":7,"age":35,"education":"green college"},null,null
Rachel,{"empid":8,"age":55,"education":"white college"},null,null

有关更多信息、完整说明和完整代码,请参阅下文

我有两个 csv 文件employee.csv 和loan.csv。

在employee.csv中我有两列,即

nameOfEmployee(String)
{"empid":empid(Integer),"age": age(Integer),"education": "education(String)"}

注意:第二列作为 json 属性列。

在loan.csv中我有两列,即

nameOfLoan(String)
{"loan":loan(Double),"balance":balance(Double),"empid":empid(Integer)}

注意:第二列作为 json 属性列

现在,我想通过 empid json 属性列将这两个 csv 文件合并为一个 csv 文件。

因此,在 mergingresults.csv 文件中,4 列应如下所示,

nameOfEmployee(String)
{"empid":empid(Integer),"age": age(Integer),"education": "education(String)"},nameOfLoan(String),{"loan":loan(Double),"balance":balance(Double),"empid":empid(Integer)}

一个 nameOfEmployee 可能与多个 nameOfLoans 相关。

我只能通过使用 java 流使用纯 java-8 来实现这一点。 有人可以帮我吗?

例如员工.csv:

nameOfEmployee,proprieties
Kevin,{"empid":1,"age":50,"education":"abc college"}
Carole,{"empid":2,"age":25,"education":"koala college"}
Sebastian,{"empid":3,"age":47,"education":"Rubbits college"}
Daniel,{"empid":4,"age":30,"education":"Pencil college"}
David,{"empid":5,"age":20,"education":"Kodi college"}
Michael,{"empid":6,"age":19,"education":"red college"}
Alain,{"empid":7,"age":35,"education":"green college"}
Rachel,{"empid":8,"age":55,"education":"white college"}

贷款.csv

nameOfLoan,proprieties
pc,{"loan":4777.00,"balance":280.0,"empid":1}
home,{"loan":140000.00,"balance":60080.0,"empid":1}
kitchen,{"loan":4000.00,"balance":3280.0,"empid":1}
car,{"loan":140000.00,"balance":60080.0,"empid":1}
health,{"loan":1400,"balance":2800.0,"empid":2}
trip,{"loan":14000.00,"balance":6080.0,"empid":2}
food,{"loan":400.00,"balance":328.0,"empid":2}
education,{"loan":14000.00,"balance":60080.0,"empid":2}

所需的 results.csv 应如下所示:

nameOfEmployee,proprieties,nameOfLoan,proprieties
Kevin,{"empid":1,"age":50,"education":"abc college"},pc,{"loan":4777.00,"balance":280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},home,{"loan":140000.00,"balance":60080.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},kitchen,{"loan":4000.00,"balance":3280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},car,{"loan":140000.00,"balance":60080.0,"empid":1}
Carole,{"empid":2,"age":25,"education":"koala college"},health,{"loan":1400,"balance":2800.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},trip,{"loan":14000.00,"balance":6080.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},food,{"loan":400.00,"balance":328.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},education,{"loan":14000.00,"balance":60080.0,"empid":2}
Sebastian,{"empid":3,"age":47,"education":"Rubbits college"},null,null
Daniel,{"empid":4,"age":30,"education":"Pencil college"},null,null
David,{"empid":5,"age":20,"education":"Kodi college"},null,null
Michael,{"empid":6,"age":19,"education":"red college"},null,null
Alain,{"empid":7,"age":35,"education":"green college"},null,null
Rachel,{"empid":8,"age":55,"education":"white college"},null,null

注意:最后六行空值不存在于我的 result.csv 中(两个 csv 的合并应该像两个列表的左连接一样)。

完整代码MergeCSVs.java

import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.stream.Collectors;

    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;

    class OutputData {

      public OutputData(String nameOfEmployee, JsonObject proprieties, String nameOfLoan, JsonObject proprieties2) {
        super();
        this.nameOfEmployee = nameOfEmployee;
        this.proprieties = proprieties;
        this.nameOfLoan = nameOfLoan;
        this.proprieties2 = proprieties2;
      }

      public String getNameOfEmployee() {
        return nameOfEmployee;
      }

      public void setNameOfEmployee(String nameOfEmployee) {
        this.nameOfEmployee = nameOfEmployee;
      }

      public JsonObject getProprieties() {
        return proprieties;
      }

      public void setProprieties(JsonObject proprieties) {
        this.proprieties = proprieties;
      }

      public String getNameOfLoan() {
        return nameOfLoan;
      }

      public void setNameOfLoan(String nameOfLoan) {
        this.nameOfLoan = nameOfLoan;
      }

      public JsonObject getProprieties2() {
        return proprieties2;
      }

      public void setProprieties2(JsonObject proprieties2) {
        this.proprieties2 = proprieties2;
      }

      private String nameOfEmployee;

      private JsonObject proprieties;

      private String nameOfLoan;

      private JsonObject proprieties2;

    }

    class Loan {

      public Loan(String nameOfLoan, JsonObject proprieties2) {
        super();
        this.nameOfLoan = nameOfLoan;
        this.proprieties2 = proprieties2;
      }

      public String getNameOfLoan() {
        return nameOfLoan;
      }

      public void setNameOfLoan(String nameOfLoan) {
        this.nameOfLoan = nameOfLoan;
      }

      public JsonObject getProprieties2() {
        return proprieties2;
      }

      public void setProprieties2(JsonObject proprieties2) {
        this.proprieties2 = proprieties2;
      }

      private String nameOfLoan;

      private JsonObject proprieties2;

    }

    class Employee {
      public Employee(String nameOfEmployee, JsonObject proprieties) {
        super();
        this.nameOfEmployee = nameOfEmployee;
        this.proprieties = proprieties;
      }

      public String getNameOfEmployee() {
        return nameOfEmployee;
      }

      public void setNameOfEmployee(String nameOfEmployee) {
        this.nameOfEmployee = nameOfEmployee;
      }

      public JsonObject getProprieties() {
        return proprieties;
      }

      public void setProprieties(JsonObject proprieties) {
        this.proprieties = proprieties;
      }

      private String nameOfEmployee;

      private JsonObject proprieties;

    }

    class Key<T> {

      final String identifier;

      final Class<T> type;

      public Key(String identifier, Class<T> type) {
        this.identifier = identifier;
        this.type = type;
      }

      public static <T> Key<T> key(String identifier, Class<T> type) {
        return new Key<>(identifier, type);
      }
    }

    class CsvVo {

      private final Map<Key<?>, Object> keyVal;

      public CsvVo(String id) {
        keyVal = new LinkedHashMap<>();// you may also use HashMap if you don't need
                                       // to keep order
      }

      public <T> void put(Key<T> key, T value) {
        keyVal.put(key, value);
      }

      public <T> T get(Key<T> key) {
        return key.type.cast(keyVal.get(key));
      }
    }

    class CsvParser {
      public static Key<Employee> key1 = new Key<>("id1", Employee.class);

      public static Key<Loan> key2 = new Key<>("id2", Loan.class);

      public static List<CsvVo> getRecodrsFromACsv(File file, List<String> keys, String name) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        List<CsvVo> records = new ArrayList<>();
        boolean isHeader = true;
        String line = null;
        while((line = br.readLine()) != null) {
          if(isHeader) {// first line is header
            isHeader = false;
            continue;
          }
          CsvVo record = new CsvVo(file.getName());
          if(name == "employee") {

            String[] lineSplit = line.split(",", 2);

            Employee employee = new Employee(lineSplit[0], new JsonParser().parse(lineSplit[1]).getAsJsonObject());

            record.put(key1, employee);

          }
          else {

            String[] lineSplit = line.split(",", 2);

            Loan loan = new Loan(lineSplit[0], new JsonParser().parse(lineSplit[1]).getAsJsonObject());

            record.put(key2, loan);

          }
          records.add(record);
        }
        br.close();
        return records;
      }

      public static List<String> getHeadersFromACsv(File file) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        List<String> headers = null;
        String line = null;
        while((line = br.readLine()) != null) {
          String[] lineSplit = line.split(",");
          headers = new ArrayList<>(Arrays.asList(lineSplit));
          break;
        }
        br.close();
        return headers;
      }

      public static void writeToCsv(final File file,
                                    final Set<String> headers,
                                    final List<OutputData> records) throws IOException {
        FileWriter csvWriter = new FileWriter(file);
        // write headers
        String sep = "";
        String[] headersArr = headers.toArray(new String[headers.size()]);
        for(String header : headersArr) {
          csvWriter.append(sep);
          csvWriter.append(header);
          sep = ",";
        }
        csvWriter.append("\n");
        // write records at each line
        for(OutputData record : records) {
          sep = "";
          for(int i = 0; i < headersArr.length; i++) {
            csvWriter.append(sep);
            String s = headersArr[i];

            if(s.equalsIgnoreCase("nameOfEmployee")) {
              csvWriter.append(record.getNameOfEmployee().toString());
            }
            else if(s.equalsIgnoreCase("proprieties")) {
              csvWriter.append(record.getProprieties().toString());
            }
            else if(s.equalsIgnoreCase("nameOfLoan")) {
              csvWriter.append(record.getNameOfLoan().toString());
            }
            else if(s.equalsIgnoreCase("proprieties2")) {
              csvWriter.append(record.getProprieties2().toString());
            }
            sep = ",";
          }
          csvWriter.append("\n");
        }
        csvWriter.flush();
        csvWriter.close();
      }
    }

    public class MergeCSVs {

      public static void main(String[] args) throws IOException {

        String fullpath = System.getProperty("user.dir") + "/" + "employee.csv";
        String fullpath2 = System.getProperty("user.dir") + "/" + "loan.csv";
        File csv1 = new File(fullpath);
        File csv2 = new File(fullpath2);
        List<String> csv1Headers = CsvParser.getHeadersFromACsv(csv1);
        // csv1Headers.forEach(h -> System.out.print(h + " "));
        // System.out.println();
        List<String> csv2Headers = CsvParser.getHeadersFromACsv(csv2);
        // csv2Headers.forEach(h -> System.out.print(h + " "));
        // System.out.println();
        List<String> allCsvHeaders = new ArrayList<>();
        allCsvHeaders.addAll(csv1Headers);
        allCsvHeaders.addAll(csv2Headers);
        // allCsvHeaders.forEach(h -> System.out.print(h + " "));
        // System.out.println();
        Set<String> uniqueHeaders = new LinkedHashSet<>(allCsvHeaders);
        // uniqueHeaders.forEach(h -> System.out.print(h + " "));
        // System.out.println();
        List<CsvVo> csv1Records = CsvParser.getRecodrsFromACsv(csv1, csv1Headers, "employee");
        List<CsvVo> csv2Records = CsvParser.getRecodrsFromACsv(csv2, csv2Headers, "loan");

        List<OutputData> result = csv1Records.stream().flatMap(x -> csv2Records.stream().filter(y -> x.get(CsvParser.key1).getProprieties().get("empid").equals(y.get(CsvParser.key2).getProprieties2().get("empid"))).map(y -> new OutputData(x.get(CsvParser.key1).getNameOfEmployee(),
                                                                                                                                                                                                                                               x.get(CsvParser.key1).getProprieties(),
                                                                                                                                                                                                                                               y.get(CsvParser.key2).getNameOfLoan(),
                                                                                                                                                                                                                                               y.get(CsvParser.key2).getProprieties2()))).collect(Collectors.toList());

        List<OutputData> allCsvRecords = new ArrayList<>();
        allCsvRecords.addAll(result);
        String fullpath3 = System.getProperty("user.dir") + "/" + "mergingresults.csv";
        CsvParser.writeToCsv(new File(fullpath3), uniqueHeaders, allCsvRecords);

      }
    }

非常感谢。

最佳答案

这是一种可能对其他人将来有帮助的解决方案。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.google.common.base.Supplier;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

class MultimapCollector<T, K, V> implements Collector<T, Multimap<K, V>, Multimap<K, V>> {

  private final Function<T, K> keyGetter;

  private final Function<T, V> valueGetter;

  public MultimapCollector(Function<T, K> keyGetter, Function<T, V> valueGetter) {
    this.keyGetter = keyGetter;
    this.valueGetter = valueGetter;
  }

  public static <T, K, V> MultimapCollector<T, K, V> toMultimap(Function<T, K> keyGetter, Function<T, V> valueGetter) {
    return new MultimapCollector<>(keyGetter, valueGetter);
  }

  public static <T, K, V> MultimapCollector<T, K, T> toMultimap(Function<T, K> keyGetter) {
    return new MultimapCollector<>(keyGetter, v -> v);
  }

  @Override
  public Supplier<Multimap<K, V>> supplier() {
    return ArrayListMultimap::create;
  }

  @Override
  public BiConsumer<Multimap<K, V>, T> accumulator() {
    return (map, element) -> map.put(keyGetter.apply(element), valueGetter.apply(element));
  }

  @Override
  public BinaryOperator<Multimap<K, V>> combiner() {
    return (map1, map2) -> {
      map1.putAll(map2);
      return map1;
    };
  }

  @Override
  public Function<Multimap<K, V>, Multimap<K, V>> finisher() {
    return map -> map;
  }

  @Override
  public Set<Characteristics> characteristics() {
    return ImmutableSet.of(Characteristics.IDENTITY_FINISH);
  }
}

class OutputData {

  public OutputData(String nameOfEmployee, JsonObject proprieties, String nameOfLoan, JsonObject proprieties2) {
    super();
    this.nameOfEmployee = nameOfEmployee;
    this.proprieties = proprieties;
    this.nameOfLoan = nameOfLoan;
    this.proprieties2 = proprieties2;
  }

  public String getNameOfEmployee() {
    return nameOfEmployee;
  }

  public void setNameOfEmployee(String nameOfEmployee) {
    this.nameOfEmployee = nameOfEmployee;
  }

  public JsonObject getProprieties() {
    return proprieties;
  }

  public void setProprieties(JsonObject proprieties) {
    this.proprieties = proprieties;
  }

  public String getNameOfLoan() {
    return nameOfLoan;
  }

  public void setNameOfLoan(String nameOfLoan) {
    this.nameOfLoan = nameOfLoan;
  }

  public JsonObject getProprieties2() {
    return proprieties2;
  }

  public void setProprieties2(JsonObject proprieties2) {
    this.proprieties2 = proprieties2;
  }

  private String nameOfEmployee;

  private JsonObject proprieties;

  private String nameOfLoan;

  private JsonObject proprieties2;

}

class Loan {

  public Loan(String nameOfLoan, JsonObject proprieties2) {
    super();
    this.nameOfLoan = nameOfLoan;
    this.proprieties2 = proprieties2;
  }

  public String getNameOfLoan() {
    return nameOfLoan;
  }

  public void setNameOfLoan(String nameOfLoan) {
    this.nameOfLoan = nameOfLoan;
  }

  public JsonObject getProprieties2() {
    return proprieties2;
  }

  public void setProprieties2(JsonObject proprieties2) {
    this.proprieties2 = proprieties2;
  }

  private String nameOfLoan;

  private JsonObject proprieties2;

  private String loanId;

  public String getLoanId() {
    String el = this.proprieties2.get("empid").toString();
    return el;
  }

  public void setLoanId(String loanId) {
    this.loanId = loanId;
  }

}

class Employee {
  public Employee(String nameOfEmployee, JsonObject proprieties) {
    super();
    this.nameOfEmployee = nameOfEmployee;
    this.proprieties = proprieties;
  }

  public String getNameOfEmployee() {
    return nameOfEmployee;
  }

  public void setNameOfEmployee(String nameOfEmployee) {
    this.nameOfEmployee = nameOfEmployee;
  }

  public JsonObject getProprieties() {
    return proprieties;
  }

  public void setProprieties(JsonObject proprieties) {
    this.proprieties = proprieties;
  }

  private String employeeId;

  public String getEmployeeId() {
    String el = this.proprieties.get("empid").toString();
    return el;
  }

  public void setEmployeeId(String employeeId) {
    this.employeeId = employeeId;
  }

  private String nameOfEmployee;

  private JsonObject proprieties;

}

class Key<T> {

  final String identifier;

  final Class<T> type;

  public Key(String identifier, Class<T> type) {
    this.identifier = identifier;
    this.type = type;
  }

  public static <T> Key<T> key(String identifier, Class<T> type) {
    return new Key<>(identifier, type);
  }
}

class CsvVo {

  private final Map<Key<?>, Object> keyVal;

  public CsvVo(String id) {
    keyVal = new LinkedHashMap<>();// you may also use HashMap if you don't need
                                   // to keep order
  }

  public <T> void put(Key<T> key, T value) {
    keyVal.put(key, value);
  }

  public <T> T get(Key<T> key) {
    return key.type.cast(keyVal.get(key));
  }
}

class CsvParser {
  public static Key<Employee> key1 = new Key<>("id1", Employee.class);

  public static Key<Loan> key2 = new Key<>("id2", Loan.class);

  public static List<CsvVo> getRecodrsFromACsv(File file, List<String> keys, String name) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    List<CsvVo> records = new ArrayList<>();
    boolean isHeader = true;
    String line = null;
    while((line = br.readLine()) != null) {
      if(isHeader) {// first line is header
        isHeader = false;
        continue;
      }
      CsvVo record = new CsvVo(file.getName());
      if(name == "employee") {

        String[] lineSplit = line.split(",", 2);

        Employee employee = new Employee(lineSplit[0], new JsonParser().parse(lineSplit[1]).getAsJsonObject());

        record.put(key1, employee);

      }
      else {

        String[] lineSplit = line.split(",", 2);

        Loan loan = new Loan(lineSplit[0], new JsonParser().parse(lineSplit[1]).getAsJsonObject());

        record.put(key2, loan);

      }
      records.add(record);
    }
    br.close();
    return records;
  }

  public static List<String> getHeadersFromACsv(File file) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    List<String> headers = null;
    String line = null;
    while((line = br.readLine()) != null) {
      String[] lineSplit = line.split(",");
      headers = new ArrayList<>(Arrays.asList(lineSplit));
      break;
    }
    br.close();
    return headers;
  }

  public static void writeToCsv(final File file,
                                final Set<String> headers,
                                final List<OutputData> records) throws IOException {
    FileWriter csvWriter = new FileWriter(file);
    // write headers
    String sep = "";
    String[] headersArr = headers.toArray(new String[headers.size()]);
    for(String header : headersArr) {
      csvWriter.append(sep);
      csvWriter.append(header);
      sep = ",";
    }
    csvWriter.append("\n");
    // write records at each line
    for(OutputData record : records) {
      sep = "";
      for(int i = 0; i < headersArr.length; i++) {
        csvWriter.append(sep);
        String s = headersArr[i];

        if(s.equalsIgnoreCase("nameOfEmployee")) {
          csvWriter.append(record.getNameOfEmployee().toString());
        }
        else if(s.equalsIgnoreCase("proprieties")) {
          csvWriter.append(record.getProprieties().toString());
        }
        else if(s.equalsIgnoreCase("nameOfLoan")) {
          if(record.getNameOfLoan() != null)
            csvWriter.append(record.getNameOfLoan().toString());
          else
            csvWriter.append("null");

        }
        else if(s.equalsIgnoreCase("proprieties2")) {
          if(record.getProprieties2() != null)
            csvWriter.append(record.getProprieties2().toString());
          else
            csvWriter.append("null");

        }
        sep = ",";
      }
      csvWriter.append("\n");
    }
    csvWriter.flush();
    csvWriter.close();
  }
}

public class MergeCSVs {

  public static void main(String[] args) throws IOException {

    String fullpath = System.getProperty("user.dir") + "/" + "employee.csv";
    String fullpath2 = System.getProperty("user.dir") + "/" + "loan.csv";
    File csv1 = new File(fullpath);
    File csv2 = new File(fullpath2);
    List<String> csv1Headers = CsvParser.getHeadersFromACsv(csv1);
    // csv1Headers.forEach(h -> System.out.print(h + " "));
    // System.out.println();
    List<String> csv2Headers = CsvParser.getHeadersFromACsv(csv2);
    // csv2Headers.forEach(h -> System.out.print(h + " "));
    // System.out.println();
    List<String> allCsvHeaders = new ArrayList<>();
    allCsvHeaders.addAll(csv1Headers);
    allCsvHeaders.addAll(csv2Headers);
    // allCsvHeaders.forEach(h -> System.out.print(h + " "));
    // System.out.println();
    Set<String> uniqueHeaders = new LinkedHashSet<>(allCsvHeaders);
    // uniqueHeaders.forEach(h -> System.out.print(h + " "));
    // System.out.println();
    List<CsvVo> csv1Records = CsvParser.getRecodrsFromACsv(csv1, csv1Headers, "employee");
    List<CsvVo> csv2Records = CsvParser.getRecodrsFromACsv(csv2, csv2Headers, "loan");

    List<Employee> allEmployees = new ArrayList<>();
    for(int i = 0; i < csv1Records.size(); i++) {
      allEmployees.add(csv1Records.get(i).get(CsvParser.key1));
      System.out.println(csv1Records.get(i).get(CsvParser.key1));
    }
    List<Loan> allLoans = new ArrayList<>();
    for(int i = 0; i < csv1Records.size(); i++) {
      allLoans.add(csv2Records.get(i).get(CsvParser.key2));

    }

    Multimap<String, Loan> loansByID = allLoans.stream().collect(MultimapCollector.toMultimap(Loan::getLoanId));

    List<OutputData[]> result = allEmployees.stream().map(emp -> {
      OutputData[] p = new OutputData[1];
      p[0] = new OutputData(emp.getNameOfEmployee(), emp.getProprieties(), null, null);
      String z = emp.getProprieties().get("empid").toString().replace("\"", "");
      emp.setEmployeeId(z);
      Collection<Loan> loan = loansByID.get(z);

      int size = loan.size();
      if(size > 0) {
        p = new OutputData[size];
        for(int j = 0; j < p.length; j++) {
          p[j] = new OutputData(emp.getNameOfEmployee(), emp.getProprieties(), null, null);
        }
      }

      int index = 0;
      for(Loan oneloan : loan) {
        if(oneloan != null) {

          // now set all the OutputData fields based on the properties
          // of the Employees instance (emp) and the Loans instance (oneloan)
          // (if available)
          // String nameOfEmployee, JsonObject proprieties, String nameOfLoan,
          // JsonObject proprieties2
          p[index].setNameOfEmployee(emp.getNameOfEmployee());
          p[index].setProprieties(emp.getProprieties());
          p[index].setNameOfLoan(oneloan.getNameOfLoan());
          p[index].setProprieties2(oneloan.getProprieties2());
        }
        index++;
      }

      return p;
    }).collect(Collectors.toList());

    List<OutputData> allCsvRecords = new ArrayList<>();
    List<OutputData> lresult = result.stream().flatMap(Stream::of).collect(Collectors.toList());
    allCsvRecords.addAll(lresult);
    String fullpath3 = System.getProperty("user.dir") + "/" + "mergingresults.csv";
    CsvParser.writeToCsv(new File(fullpath3), uniqueHeaders, allCsvRecords);

  }
}

这会产生所需的输出:

nameOfEmployee,proprieties,nameOfLoan,proprieties2
Kevin,{"empid":1,"age":50,"education":"abc college"},pc,{"loan":4777.00,"balance":280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},home,{"loan":140000.00,"balance":60080.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},kitchen,{"loan":4000.00,"balance":3280.0,"empid":1}
Kevin,{"empid":1,"age":50,"education":"abc college"},car,{"loan":140000.00,"balance":60080.0,"empid":1}
Carole,{"empid":2,"age":25,"education":"koala college"},health,{"loan":1400,"balance":2800.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},trip,{"loan":14000.00,"balance":6080.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},food,{"loan":400.00,"balance":328.0,"empid":2}
Carole,{"empid":2,"age":25,"education":"koala college"},education,{"loan":14000.00,"balance":60080.0,"empid":2}
Sebastian,{"empid":3,"age":47,"education":"Rubbits college"},null,null
Daniel,{"empid":4,"age":30,"education":"Pencil college"},null,null
David,{"empid":5,"age":20,"education":"Kodi college"},null,null
Michael,{"empid":6,"age":19,"education":"red college"},null,null
Alain,{"empid":7,"age":35,"education":"green college"},null,null
Rachel,{"empid":8,"age":55,"education":"white college"},null,null

关于java - 如何在2个不同类型的列表中查找元素匹配并使用java 8流连接它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60588488/

相关文章:

java - 使 JTextArea 的一部分不可编辑(而不是整个 JTextArea!)

java - SimpleJdbcCall 中的多个输出参数

java - 搜索 anchor 标记时,Selenium findElement(s) 出现问题

java - 实现效果不佳

java - java中的比较器链

java - 为什么具有短路操作的并行 Java Stream 会评估 Stream 的所有元素,而顺序 Stream 则不会?

java 8 : Change value inside stream

Java 8 Stream——聚合和返回聚合步骤

带有 Function.apply 的 Java 泛型

java - 如何使用 Java 8 收集器对三重嵌套映射求和