【问题标题】:Need assistance 'combining' partial duplicates in an Java ArrayList需要帮助“组合”Java ArrayList 中的部分重复项
【发布时间】:2015-12-10 21:27:12
【问题描述】:
        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,但还没有到达那里

note2:“lines”是一个 CSV 字符串的数组列表

我需要在注释所在的位置(说这里是我迷路的地方......)根据它们的键和值以及键和值匹配的每个对象将重复项组合在重复项中,合计金额(可能有负数,但如果我们使用 BigDecimal,这无关紧要)。因此,如果我有 3 行具有相同的键和值(不管数量不同),我将以 1 行带有该键和值以及 3 个数量的总和结束。

可能重复的示例数据的想法WithAmounts:

"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;
}
}

【问题讨论】:

  • 您是否针对 java 1.8 进行编译?
  • 这根本行不通,.contains() 调用将始终返回 false,因为您每次都在创建一个新对象。可能会考虑使用具有键/值对的Map 对象。它将使您能够使用 map.containsKey()。
  • 实际上,这里有很多错误......不仅仅是尝试使用新的对象实例作为键......可能希望与您团队中更高级别的开发人员合作。
  • 最大的问题,没有更高级别的开发者......

标签: java list loops arraylist duplicates


【解决方案1】:

不是一个完整的答案,但如果您在 Collections 框架中使用比较方法(例如 List.contains()),那么您正在比较的对象(在您的情况下为 Pair)需要覆盖 equals() 和hashCode(),否则 contains() 可能不会像您预期的那样运行。

在您的 equals() 方法中,比较 key、value 和 amount 的值,如果所有这些值相等,则返回 true。

hashCode 方法可以使用 String.hashCode() 组合键、值和数量。

【讨论】:

  • 感谢您的提醒,但我仍然不知道如何完成逻辑以合并重复项并返回 1 行加总金额。
【解决方案2】:

对于 Java 1.8,我将使用 Stream.collect(Collectors.toMap(....)) 和合并函数对金额求和(我假设您想要转换金额字段加倍):

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 来汇总金额

【讨论】:

  • 这将根据客户要求在 1.6 中编译
  • 我刚刚为 1.6 提供了一些提示
【解决方案3】:

您在正确的轨道上,但您需要了解一些概念才能轻松解决此问题。

首先,不能包含重复项的集合称为集合。这稍后会派上用场,因为我们希望最终得到一个不包含重复项的 Collection。 另一个重要的考虑因素是 List 的 contains 方法效率非常低,因此您应该避免使用它。另一方面,集合能够提供非常有效的 contains 方法实现。

但是要让 Set 在 Java 中工作,您必须提供 equals 方法的实现,否则 Set 将使用来自 Object 的默认实现,它通过引用比较元素。

最常用的 Set 类型是HashSet。 If 使用哈希表来索引元素,这是用于高效查找的主要数据结构(并允许快速contains 实现)。要使用HashSet,还必须实现Object的hashCode方法(实际上需要确保equalshashCode在Object相等或不相等时“同意”,即如果@ 987654330@ 对两个元素返回 true,那么它们的 hashCodes 也必须相等)。

还有其他类型的 Set,例如 TreeSet,不依赖于哈希,如果您对这些感兴趣,请在线查找。

另一件事是,使用我在下面建议的解决方案,您不仅需要查找元素是否存在,还需要能够有效地检索它(因此您可以添加更多“数量”)。为此,您需要Map,而不仅仅是Set

实现此目的的常用技术是创建Map&lt;Pair, Pair&gt;。因此,对于每个 Pair 实例,您可以有效地从 Map 中检查和检索当前元素(就像有一个 HashSet,有一个 HashMap,我们将在此处使用)。

有了这些知识,为您的问题实施解决方案非常简单:

  1. 实现Pairequals 方法(如您所说,如果它们的键和值都相同,则两个Pairs 相等)。
  2. 实现PairhashCode 方法,该方法遵守其合同,如上所述。
  3. 找到一种方法将两个相等的 Pair 组合成一个并将它们的“数量”字段相加以创建一个新的 Pair,它是 2 个元素的“总和”。可能静态工厂方法或复制构造函数都可以,但这取决于你如何做到这一点。
  4. 将您正在查看的当前元素放入地图中。如果它是重复的,则将其替换为通过将元素添加到现有元素而创建的新 Pair(现有元素由 put 操作返回)。请注意,您只需 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);
}

希望你能填补空白!

【讨论】:

  • 由于您的 Pair 是可变的(可以更改),您可能希望避免创建一个新的 Pair 来表示两对的总和,而只需使用 setAmount 方法来添加旧的和当前的数量对....但我建议您避免使用可变数据结构,因为在高级上下文(例如并发)中它们很难正确使用。
【解决方案4】:

您可以使用HashMap&lt;Pair, Pair&gt; 来解决此问题:

    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 必须为 override hashCode and 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;
}

【讨论】:

  • 谢谢!因此,如果我正确理解这一点,mergedPairs 将包含合并的行吗? "0001, test1, 259.00" "0002, test2, 0.00" "0003, test3, 18.00" 而不是原来的8?
  • 我实现了这一点,并在编译后尝试运行测试,但现在我的输出文件中没有记录,而不是我应该有的 10 条记录。你觉得下面的代码有什么问题吗?
  • 抱歉,我无法将代码导入 cmets
  • 我的解决方案中的代码不会将任何内容写回文件,它只会在内存中创建包含合并对的集合。如果您在将数据写回文件时遇到问题,您应该提出一个新问题。
  • 我将我的代码添加到原始主题中,正如您所看到的,我提到所有总数都太大了,好像金额被附加到每条记录并且它只是呈指数增长。我不知道这会发生在哪里。
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 2021-01-16
  • 2021-01-02
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多