需要帮助';合并';Java ArrayList中的部分重复项
//创建交易行需要帮助';合并';Java ArrayList中的部分重复项,java,list,loops,arraylist,duplicates,Java,List,Loops,Arraylist,Duplicates,//创建交易行 fileLines.add("0 " + formatField(pp.getBank(), 21, RIGHT_JUSTIFIED, BLANK_FILLED) + " " + formatField(pp.getNameOfUser(), 26, LEFT_JUSTIFIED, BLANK_FILLED) + formatField(pp.getNumberOf
fileLines.add("0 " +
formatField(pp.getBank(), 21, RIGHT_JUSTIFIED, BLANK_FILLED) +
" " +
formatField(pp.getNameOfUser(), 26, LEFT_JUSTIFIED, BLANK_FILLED) +
formatField(pp.getNumberOfUser(),6,LEFT_JUSTIFIED,BLANK_FILLED) +
formatField(pp.getDescription(),12,LEFT_JUSTIFIED,BLANK_FILLED) +
MakeSapolRMH.getDate() +
formatField("",40,true,true));
//做预告片记录
String offset = new String();
offset += "1";
offset += pp.getAccountNumber(); // ###-### ######## (or else they will have to use spaces (###-### ######)) 16 chars total
offset += " ";
if (pp.isCredit()){
offset += "50";
} else {
offset += "13";
}
offset += formatField(totals.toString(), 10, RIGHT_JUSTIFIED, ZERO_FILLED);
offset += formatField(pp.getNameOfRemitter(), 16, LEFT_JUSTIFIED, BLANK_FILLED);
offset += " " +
formatField(pp.getInternalDescription(), 28, RIGHT_JUSTIFIED, BLANK_FILLED) +
" ";
offset += pp.getAccountNumber(); // ###-### ######## (or else they will have to use spaces (###-### ######)) 16 chars total
offset += formatField(pp.getNameOfRemitter(), 16, LEFT_JUSTIFIED, BLANK_FILLED);
offset += "00000000";
fileLines.add(offset);
这不是一个完整的答案,但是如果您在Collections框架中使用比较方法(例如
List.contains()
),那么您正在比较的对象(在您的例子中,Pair
)需要超越equals()和hashCode(),否则contains()可能不会像您预期的那样工作
在equals()方法中,比较key、value和amount的值,如果所有这些值都相等,则返回true
hashCode方法可以将String.hashCode()用于键、值和金额的组合。不是一个完整的答案,但是如果您在集合框架中使用比较方法(例如
List.contains()
),那么您正在比较的对象(在您的情况下,Pair
)需要超越equals()和hashCode(),否则,contains()的行为可能与预期不符
在equals()方法中,比较key、value和amount的值,如果所有这些值都相等,则返回true
hashCode方法可以使用String.hashCode()组合键、值和金额。在Java 1.8中,我将使用Stream.collect(收集器(…)和合并函数对金额进行求和(我假设您希望将金额字段转换为双倍):
List lst=。。。
Map Map=lst.stream().collect(
Collectors.toMap(p->p.getKey()+p.getValue(),Function.identity(),(p1,p2)->新对(p1.getKey(),p1.getValue(),p1.getAmount()+p2.getAmount());
收集结果=map.values();
在Java1.6中根据要求,我会选择番石榴,然后选择地图。要使用Java 1.8对金额进行求和,我将使用Stream.collect(收集器(..)和合并函数对金额进行求和(我假设您希望将金额字段转换为两倍):
List lst=。。。
Map Map=lst.stream().collect(
Collectors.toMap(p->p.getKey()+p.getValue(),Function.identity(),(p1,p2)->新对(p1.getKey(),p1.getValue(),p1.getAmount()+p2.getAmount());
收集结果=map.values();
在Java1.6中根据要求,我会选择番石榴,然后选择地图。要计算金额,您的思路是正确的,但您需要先了解一些概念,然后才能轻松解决此问题 首先,不能包含重复项的集合称为集合。这将在以后派上用场,因为我们希望最终得到一个不包含重复项的集合。 另一个重要的考虑因素是列表的
contains
方法效率非常低,因此您可能应该避免使用它。另一方面,集合能够提供非常有效的contains方法实现
但是,要使集合在Java中工作,必须提供equals
方法的实现,否则集合将使用Object
中的默认实现,该实现通过引用比较元素
最常用的集合类型是HashSet
。If使用哈希表对元素进行索引,这是高效查找的主要数据结构(并允许快速contains
实现)。要使用HashSet
,还必须实现Object的hashCode
方法(事实上,当一个对象等于或不等于时,需要确保等于和hashCode
“同意”,即如果等于
对两个元素返回true,那么它们的hashCode也必须相等)
还有其他类型的集合,例如TreeSet
,它们不依赖散列,如果您对这些集合感兴趣,请在线查找
另一件事是,使用下面我建议的解决方案,您不仅需要找到元素是否存在,还需要能够高效地检索它(这样您就可以向它添加更多的“数量”)。为此,您需要一个映射
,而不仅仅是一个集合
实现这一点的常用技术是创建地图
。因此,对于每个Pair实例,您可以从映射中高效地检查和检索当前元素(就像有一个HashSet
,有一个HashMap
,我们将在这里使用)
有了这些知识,实施问题的解决方案是非常简单的:
执行Pair
的equals
方法(根据您所说,如果两个对的键和值相同,则两个对是相等的)
如上文所述,执行符合其合同的hashCode
方法Pair
找到一种方法,将两个相等的对合并为一个,并对其“数量”字段求和,以创建一个新的对,即两个元素的“和”。可能一个静态工厂方法或一个复制构造函数就可以了,但这取决于您如何做到这一点
将当前正在查看的元素放入地图中。如果它是重复的,则将其替换为通过将元素添加到现有元素而创建的新对(现有元素由put操作返回)。请注意,您只需放置
新元素,无需删除旧元素李>
如果顺序对您很重要(即,您关心哪个元素排在第一位、第二位等等),请使用LinkedHashMap
而不是HashMap
(它不关心顺序)
以下是解决方案的一部分:
List<Pair> lst = ...
Map<String, Pair> map = lst.stream().collect(
Collectors.toMap(p -> p.getKey() + p.getValue(), Function.identity(), (p1, p2) -> new Pair(p1.getKey(), p1.getValue(), p1.getAmount() + p2.getAmount())));
Collection<Pair> result = map.values();
Map pairs=newlinkedhashmap();
....
//put将currentPair添加到映射并返回现有对
//如果已存在,则为空,否则为空。
Pair oldPair=pairs.put(currentPair,currentPair);
如果(oldPair!=null){//重复
Pair sumPair=Pair.sumOf(oldPair,currentPair);
pairs.put(sumPair,sumPair);
}
希望你能填空 您走的是正确的道路,但您需要先了解一些概念,然后才能轻松解决此问题
冷杉
public static ArrayList<String> makeWestPacDirectEntry(ArrayList<String> lines, ParametersParser pp){
ArrayList<String> fileLines = new ArrayList<String>();
fileLines.add("0 " +
formatField(pp.getBank(), 21, RIGHT_JUSTIFIED, BLANK_FILLED) +
" " +
formatField(pp.getNameOfUser(), 26, LEFT_JUSTIFIED, BLANK_FILLED) +
formatField(pp.getNumberOfUser(),6,LEFT_JUSTIFIED,BLANK_FILLED) +
formatField(pp.getDescription(),12,LEFT_JUSTIFIED,BLANK_FILLED) +
MakeSapolRMH.getDate() +
formatField("",40,true,true));
BigDecimal totals = new BigDecimal(0);
HashMap<String, WDETotalsByDescription> tempList = new HashMap<String, WDETotalsByDescription>();
//find duplicates
Map<Pair, Pair> pairMap = new HashMap<Pair, Pair>();
for (String line : lines) {
String[] lineparts = line.split(",");
if (line.startsWith("Date") || lineparts[3].equals("0.00") || lineparts[3].equals("-0.00")
|| lineparts[3].equals("000") || lineparts[3].equals("0000") || lineparts[3].equals("00000")) {
continue;
}
String description = lineparts[4];
String acct = lineparts[2];
String amt = lineparts[3];
Pair newPair = new Pair(description, acct, amt);
if (!pairMap.containsKey(newPair)) {
pairMap.put(newPair, newPair);
} else {
Pair existingPair = pairMap.get(newPair);
BigDecimal mergedAmount = new BigDecimal(existingPair.getAmount()).movePointRight(2).add((new BigDecimal(newPair.getAmount()).movePointRight(2)));
existingPair.setAmount(mergedAmount.toString());
}
}
Set<Pair> mergedPairs = pairMap.keySet();
////////////////////
for (String linefromFile:lines){
String[] lineparts = linefromFile.split(",");
if ( linefromFile.startsWith("Date") || lineparts[3].equals("0.00") || lineparts[3].equals("-0.00") || lineparts[3].equals("000") || lineparts[3].equals("0000") || lineparts[3].equals("00000") ) {
continue;
}
for(Pair p:mergedPairs) {
WDETotalsByDescription wde = new WDETotalsByDescription();
String line = new String("1");
line += formatField (lineparts[1], 7, RIGHT_JUSTIFIED, BLANK_FILLED);
line += formatField (lineparts[2], 9, RIGHT_JUSTIFIED, BLANK_FILLED);
line += " " + formatField(pp.getTransactionCode(),2,LEFT_JUSTIFIED,ZERO_FILLED);
wde.setStart(line);
wde.setAmount(new BigDecimal(p.getAmount()));
line = formatField (lineparts[4], 32, LEFT_JUSTIFIED, BLANK_FILLED);
line += formatField (pp.getExernalDescription(), 18, LEFT_JUSTIFIED, BLANK_FILLED);
line += formatField (lineparts[5], 7, RIGHT_JUSTIFIED, BLANK_FILLED);
line += formatField (lineparts[6], 9, RIGHT_JUSTIFIED, BLANK_FILLED);
line += formatField (pp.getNameOfRemitter(), 16, LEFT_JUSTIFIED, BLANK_FILLED);
line += formatField ("", 8, RIGHT_JUSTIFIED, ZERO_FILLED);
wde.setEnd(line);
wde.setAccount(lineparts[4]);
if(!tempList.containsKey(wde.getAccount())){
tempList.put(wde.getAccount(), wde);
}
else{
WDETotalsByDescription existingWDE = tempList.get(wde.getAccount());
existingWDE.setAmount(existingWDE.getAmount().add(wde.getAmount()));
tempList.put(existingWDE.getAccount(), existingWDE);
}
}
}
for(WDETotalsByDescription wde:tempList.values()){
String line = new String();
line = wde.getStart()
+ formatField(wde.getAmount().toString(), 10, RIGHT_JUSTIFIED, ZERO_FILLED)
+ wde.getEnd();
if (formatField(wde.getAmount().toString(), 10, RIGHT_JUSTIFIED, ZERO_FILLED) != "0000000000") {
totals = totals.add(wde.getAmount());
fileLines.add(line);
}
}
String offset = new String();
offset += "1";
offset += pp.getAccountNumber(); // ###-### ######## (or else they will have to use spaces (###-### ######)) 16 chars total
offset += " ";
if (pp.isCredit()){
offset += "50";
} else {
offset += "13";
}
offset += formatField(totals.toString(), 10, RIGHT_JUSTIFIED, ZERO_FILLED);
offset += formatField(pp.getNameOfRemitter(), 16, LEFT_JUSTIFIED, BLANK_FILLED);
offset += " " +
formatField(pp.getInternalDescription(), 28, RIGHT_JUSTIFIED, BLANK_FILLED) +
" ";
offset += pp.getAccountNumber(); // ###-### ######## (or else they will have to use spaces (###-### ######)) 16 chars total
offset += formatField(pp.getNameOfRemitter(), 16, LEFT_JUSTIFIED, BLANK_FILLED);
offset += "00000000";
fileLines.add(offset);
String trailerRecord = "7999-999 ";
trailerRecord += formatField("", 10, RIGHT_JUSTIFIED, ZERO_FILLED);
trailerRecord += formatField(totals.toString(), 10, RIGHT_JUSTIFIED, ZERO_FILLED);
trailerRecord += formatField(totals.toString(), 10, RIGHT_JUSTIFIED, ZERO_FILLED);
trailerRecord += formatField("", 24, RIGHT_JUSTIFIED, BLANK_FILLED);
trailerRecord += formatField(Integer.toString(fileLines.size()-1), 6, RIGHT_JUSTIFIED, ZERO_FILLED);
trailerRecord += formatField("", 40, RIGHT_JUSTIFIED, BLANK_FILLED);
fileLines.add(trailerRecord);
return fileLines;
}
}
List<Pair> lst = ...
Map<String, Pair> map = lst.stream().collect(
Collectors.toMap(p -> p.getKey() + p.getValue(), Function.identity(), (p1, p2) -> new Pair(p1.getKey(), p1.getValue(), p1.getAmount() + p2.getAmount())));
Collection<Pair> result = map.values();
Map<Pair, Pair> pairs = new LinkedHashMap<>();
....
// put adds the currentPair to the Map and returns the existing Pair
// if it already exists, or null otherwise.
Pair oldPair = pairs.put(currentPair, currentPair);
if (oldPair != null) { // duplicate
Pair sumPair = Pair.sumOf(oldPair, currentPair);
pairs.put(sumPair, sumPair);
}
Map<Pair, Pair> pairMap = new HashMap<Pair, Pair>();
for (String line : lines) {
String[] lineparts = line.split(",");
if (line.startsWith("Date") || lineparts[3].equals("0.00") || lineparts[3].equals("-0.00")
|| lineparts[3].equals("000") || lineparts[3].equals("0000") || lineparts[3].equals("00000")) {
continue;
}
String description = lineparts[4];
String acct = lineparts[2];
String amt = lineparts[3];
Pair newPair = new Pair(description, acct, amt);
if (!pairMap.containsKey(newPair)) {
pairMap.put(newPair, newPair);
} else {
Pair existingPair = pairMap.get(newPair);
String mergedAmount = existingPair.getAmount() + newPair.getAmount();
existingPair.setAmount(mergedAmount);
}
}
Set<Pair> mergedPairs = pairMap.keySet();
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Pair other = (Pair) obj;
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}