假設我有 2 個帶有 ID 和日期列的檔案
file1:
empid1: date 1
empid1: date 2
empid2: date 3
empid2: date 4
file2:
empid1: date 1
empid2: date 3
empid3: date 5
所以,現在,當我比較 2 個檔案時,我的主要目標是檢索那些不在檔案 2 中的資料,反之亦然。誰能幫助我或指導我如何實作這一目標?
uj5u.com熱心網友回復:
public static void main(String[] args) {
List<String> f = Arrays.asList(new String[] { "A", "B", "D" });
List<String> s = Arrays.asList(new String[] { "A", "B", "C" });
System.out.println(Arrays.toString(nonCommonLines(f, s).toArray()));
}
public static List<String> nonCommonLines(List<String> first, List<String> second) {
List<String> nonCommonReturn = new ArrayList<String>();
if (first != null && second != null) {
for (String firstIterator : first) {
if (Collections.frequency(second, firstIterator) == 0) {
nonCommonReturn.add(firstIterator);
}
}
for (String secondIterator : second) {
if (Collections.frequency(first, secondIterator) == 0) {
nonCommonReturn.add(secondIterator);
}
}
} else {
if (first == null)
nonCommonReturn.addAll(second);
if (second == null)
nonCommonReturn.addAll(first);
}
return nonCommonReturn;
}
uj5u.com熱心網友回復:
7k 條目并不多。當今的計算機擁有數千兆位元組的 RAM,您應該能夠將兩個檔案的全部內容存盤在記憶體中,因此請考慮以下代碼(適用于 Java 8)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Testings {
public static void main(String[] args) {
Path path1 = Paths.get("path-to-first-file");
Path path2 = Paths.get("path-to-second-file");
try {
List<String> lines1 = Files.readAllLines(path1);
// Make copy of 'lines1'.
List<String> org1 = new ArrayList<>(lines1);
List<String> lines2 = Files.readAllLines(path2);
// Now 'lines1' only contains lines that are not in 'lines2'.
lines1.removeAll(lines2);
// Now 'lines2' only contains lines that are not in [original] 'lines1'.
lines2.removeAll(org1);
// 'lines1' now contains lines that were not common in the original lists.
lines1.addAll(lines2);
}
catch (IOException x) {
x.printStackTrace();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341709.html
上一篇:進度條在括號外
