[英]Need assistance 'combining' partial duplicates in an Java ArrayList
public class Pair{
public String key;
public String value;
public String amount;
public Pair(String key, String value, String amount){
this.key = key;
this.value = value;
this.amount = amount;
}
public Pair(String key, String value){
this.key = key;
this.value = value;
}
public String getKey(){
return key;
}
public String getValue(){
return value;
}
public String getAmount(){
return amount;
}
public void setAmount(String amount){
this.amount = amount;
}
}
List<Pair> pairs = new ArrayList<Pair>();
List<Pair> duplicates = new ArrayList<Pair>();
List<Pair> duplicatesWithAmounts = new ArrayList<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 pair = new Pair(description, acct);
Pair pair2 = new Pair(description, acct, amt);
if(!pairs.isEmpty() && pairs.contains(pair)) {
duplicates.add(pair);
duplicatesWithAmounts.add(pair2);
}
pairs.add(pair);
}
for (String linefromFile:lines){
String[] lineparts = linefromFile.split(",");
String description = lineparts[4];
String acct = lineparts[2];
String amt = lineparts[3];
Pair pair = new Pair(description, acct);
Pair pair2 = new Pair(description, acct, amt);
if(!duplicates.contains(pair)){
continue;
}
duplicates.remove(pair);
//Here is where I'm lost....
}
注意:数量目前是字符串,将它们加在一起将传递给新的BigDecimal,但尚未到达
注意2:“行”是CSV字符串的数组列表
我需要在注释所在的地方做些什么(说这是我迷路的地方...),是根据重复项的键和值将重复项组合到plicatesWithAmounts中,并对键和值匹配的每个对象求和金额(可能有负数,但如果使用BigDecimal则无关紧要)。 因此,如果我有3行具有相同的键和值(不管数量不同),我将以1行包含该键和值以及3个值的总和结束。
可能重复重复的示例数据的想法:
“ 0001,test1,147.00”
“ 0001,test1,129.00”
“ 0001,test1,-17.00”
“ 0002,test2,7.00”
“ 0002,test2,-7.00”
“ 0003,test3、30.00”
“ 0003,test3,-12.00”
我要结束的是:
“ 0001,test1,259.00”
“ 0002,test2,0.00”
“ 0003,test3,18.00”
非常感谢您的帮助,我是一名初级开发人员,并且一直在为这个时间敏感的项目而苦苦挣扎。 我敢肯定,从一开始,没有我的Pair类等,也没有我的数组对,这是一个更好的方法,所以如果有人也向我展示这一点就很好了。但是我也很想知道如何出于学习目的,用我目前拥有的东西获得所需的东西。 所有这些都在“进行交易行”部分中。
好的,所以我尝试了Stefan的方法,虽然我以为我已经弄明白了。 我正在纠正输出中的行数,没有重复行,但是每行的所有行数似乎都很大。 比他们应该的大得多。
package src;
import java.math.BigDecimal;
public class WDETotalsByDescription{
public String start;
public String end;
public String account;
public BigDecimal amount = new BigDecimal(0);
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public WDETotalsByDescription(){
}
}
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);
}
}
//制作抵消记录,要求2012年11月。
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;
}
}
这不是一个完整的答案,但是如果您在Collections框架中使用比较方法(例如List.contains()
), List.contains()
比较的对象(在您的情况下为Pair
)需要覆盖equals()和hashCode() ,否则contains()可能无法按预期运行。
在equals()方法中,比较键,值和金额的值,如果所有这些值都相等,则返回true。
hashCode方法可以将String.hashCode()用于组合的键,值和数量。
使用Java 1.8时 ,我将Stream.collect(Collectors。toMap(....))与合并函数合计金额(我假设您希望将amount字段转换为double):
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();
在Java 1.6中,我会按照要求选择Guava的Multimap ,然后再选择Maps。 将值相加的transformValues
您走在正确的道路上,但是您需要了解一些概念,才能轻松解决此问题。
首先,不能包含重复项的Collection称为Set。 稍后将派上用场,因为我们希望得到一个不包含重复项的Collection。 另一个重要的考虑因素是List的contains
方法效率很低,因此您可能应该避免使用它。 另一方面,集合能够提供contains方法的非常有效的实现。
但是,为了让Sets在Java中工作,必须提供equals
方法的实现,否则Set将使用Object
的默认实现,该默认实现将按引用比较元素。
最常用的Set类型是HashSet
。 If使用哈希表为元素建立索引,这是用于高效查找的主要数据结构(并允许快速contains
实现)。 要使用HashSet
,还必须实现Object的hashCode
方法(实际上,当对象相等或不相等时,您需要确保equals
和hashCode
“ agree”,即,如果equals
对两个元素返回true,则它们的equals
hashCodes也必须相等)。
还有其他类型的Set,例如TreeSet
,它们不依赖于哈希,如果您对此感兴趣,可以在线查找。
另一件事是,使用我在下面建议的解决方案,您不仅需要查找元素是否存在,而且还需要能够高效地检索它(以便可以向其中添加更多的“数量”)。 为此,您需要一个Map
,而不仅仅是Set
。
一种常见的实现方法是创建Map<Pair, Pair>
。 因此,对于每个Pair实例,您都可以从Map中有效地检查和检索当前元素(就像有一个HashSet
,还有一个HashMap
,我们将在这里使用它)。
掌握了这些知识,为您的问题实施解决方案就很简单了:
equals
的方法Pair
(两对都是平等的,如果他们都键和值是相同的,从你说的话)。 Pair
遵守其合约的hashCode
方法。 put
新元素,而无需删除旧元素! 如果顺序对您很重要(例如,您关心哪个元素排在第一,第二等等),则使用LinkedHashMap
而不是HashMap
(后者不关心顺序)。
这是解决方案的一部分:
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);
}
希望你能填补空白!
您可以使用HashMap<Pair, Pair>
解决此问题:
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();
为此, Pair
必须重写hashCode
和equals
,以便两个不同的Pair
实例被认为是相等的,前提是键和值相等。 这是由Eclipse生成的示例实现:
@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.