我正在构建一些用于比较 2 哈希集的简短代码。
SET 1 = noRek : [1234567892, 1234567891, 1234567890]
SET 2 = Source : [1234567890U0113, 1234567894B0111, 1234567890U0112, 1234567891B0111, 1234567890U0115, 1234567890U0114, 1234567892B0113, 1234567893B0111, 1234567890U0111, 1234567890B0111, 1234567892B0112, 1234567892B0111]
public class diff {
public static void main(String args[]) {
String filename = "C:\\abc.txt";
String filename2 = "C:\\xyz.txt";
HashSet<String> al = new HashSet<String>();
HashSet<String> al1 = new HashSet<String>();
HashSet<String> source = new HashSet<String>();
HashSet<String> noRek = new HashSet<String>();
HashSet<String> diff1 = new HashSet<String>();
HashSet<String> diff2 = new HashSet<String>();
String str = null;
String str2 = null;
Integer digitRek = 10;
Integer digitTransaksi = 15;
//GET REKDATA FROM TARGET
try {
String message = new Scanner(new File(filename2)).useDelimiter("\\Z").next();
for (int i = 0; i < message.length(); i += digitRek) {
noRek.add(message.substring(i, Math.min(i + digitRek, message.length())));
}
System.out.println("noRek : " + noRek);
} catch (Exception e) {
e.printStackTrace();
}
try {
String message2 = new Scanner(new File(filename)).useDelimiter("\\Z").next();
for (int i = 0; i < message2.length(); i += digitTransaksi) {
source.add(message2.substring(i, Math.min(i + digitTransaksi, message2.length())));
}
System.out.println("Source : " + source);
} catch (Exception e) {
e.printStackTrace();
}
for (String str3 : source) {
if (source.contains(noRek.substring(digitRek)) {
diff1.add(str3);
}
}
System.out.println("Final : " + diff1);
}
我期望set diff1的输出是这样的
SET 3 = [1234567890U0111, 1234567890U0112, 1234567890U0113,1234567890U0114, 1234567890U0115, 1234567890B0111, 1234567891B0111, 1234567892B0113, 1234567892B0112, 1234567892B0111]
但实际输出与 SET 2 相同。
简单来说,我需要将 SET 2 与组合进行比较,前 10 位数字是帐号,然后下一个字符 1 位数字是代码,然后其余数字是自动生成的。这意味着长度组合SET 2是15位,组合SET 1是10位,那么集合1是帐号数据,我需要从集合2中的帐号获取所有交易。
SET 1 是帐户的所有数据, SET 2为交易组合数据
最佳答案
您可以通过使用流和过滤器
来解决这个问题
Set<String> diff1 = source.stream().filter(str -> {
if (str.length() > 10) {
String account = str.substring(0, 10);
return noRek.contains(account);
}
return false;
}).collect(Collectors.toSet());
关于java - 如何比较两个集合然后使用组合字符串过滤到新集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57055414/