如何迭代过大的ArrayList <string>?

时间:2016-04-25 14:40:59

标签: java

我有两个ArrayList sourceMessageList和TargetMessageList。我需要比较两个消息列表数据。

现在让我们说List1 - 100条记录。 List2 - 1000条记录 从List1-第一条记录与list2中的每条记录进行比较,然后将List1-第二条记录与list2中的每条记录进行比较。

但是list2将list1中的第一个源数据的值hasNext()设置为true。

private void compareMessageList(ArrayList<String> source_messageList, ArrayList<String> target_messageList)
            throws Exception {
        // TODO Auto-generated method stub
        Iterator<String> sourceMessageIterator = source_messageList.iterator();
        Iterator<String> targetMessageIterator = null;

        while (sourceMessageIterator.hasNext()) {
            String sourceMessage = (String) sourceMessageIterator.next();

            targetMessageIterator = target_messageList.iterator();
            while (targetMessageIterator.hasNext()) {
                String targetMessage = (String) targetMessageIterator.next();
                if (getCorpValue(sourceMessage).equalsIgnoreCase(getCorpValue(targetMessage))) {
                    assertXMLEquals(convertSwiftMessageToXML(sourceMessage), convertSwiftMessageToXML(targetMessage));
                }
            }
        }

        if (buffer.toString().length() > 0) {

            writeDifferenceTofile(buffer.toString());
            buffer.delete(0, buffer.length());
            throw new CatsException("There are some differences in the files.");
        }

        System.out.println("Exiting now ...");
    } 

上面的代码执行时间太长。

1 个答案:

答案 0 :(得分:1)

加快速度:

HashMap<String, String> lowers = new HashMap<String, String>();
for (String source : source_messageList) {
    lowers.put(getCorpValue(source).toLowerCase(), source);
}
for (String target : target_messageList) {
    final String corpTarget = getCorpValue(target).toLowerCase();
    if(lowers.containsKey(corpTarget)) {
        assertXMLEquals(
            convertSwiftMessageToXML(lowers.get(corpTarget)),
            convertSwiftMessageToXML(target)
        );
    }
}