搜索具有指定属性的对象时,对ArrayList进行两次迭代

时间:2018-08-17 09:23:57

标签: java list

我正在尝试遍历列表,并创建两个对象对,它们都存储在window.history.back()中。这两个对象都将具有属性window.close(),一个将属性设置为$(id).on('click', function() { var fd = new FromData(); var count_mac = $('input[name="mac[]"]').length; fd.append('count_mac', count_mac); $('input[name="mac[]"]').each(function(index){ var data = $(this).val(); //Pass to PHP file with $_POST['mac0'],$_POST['mac1'],... fd.append('mac'+ index, data); }); //Ajax code here jQuery.ajax({ url: 'example_file.php', type: 'post', data: fd, contentType: false, processData: false, success: function( results ) { location.reload(); } }); }); ,另一个将属性设置为data

这是我正在使用的代码。

isSuspended

但是,此代码将很慢。它以5000的批量执行。记录总数超过1000万,因此,我正在寻找一种使速度更快的方法。我真的需要2个循环吗?

1 个答案:

答案 0 :(得分:1)

迭代一次列表,过滤出wasProcessed。将条目添加到两个列表之一:isSuspendednotSuspended。现在将每个列表中的条目配对。

List<Market> isSuspended = new ArrayList<>();
List<Market> notSuspended = new ArrayList<>();
for (Market market : data) {
    if (! market.wasProcessed) {
        if (market.getIsSuspended())
            isSuspended.add(market);
        else
            notSuspended.add(market);
    }
}
Iterator iter1 = notSuspended.iterator();
Iterator iter2 = isSuspended.iterator();
while (iter.hasNext() && iter2.hasNext()) {
    Market market1 = iter1.next();
    Market market2 = iter2.next();
    Pair<Market, Market> marketPair = new Pair<>(market1, market2);
    market1.setWasProcessed(true);
    market2.setWasProcessed(true);
    // use marketPair here
}

但是,如果这是一个连续的过程,以5000个批处理,其中可能有一个列表中有翻转条目,请改用Deque

Deque<Market> isSuspended = new ArrayDeque<>();
Deque<Market> notSuspended = new ArrayDeque<>();
for (;;) { // loop forever
    data = /*get next batch here*/;
    if (data.isEmpty())
        break;

    // Find unprocessed
    for (Market market : data) {
        if (! market.wasProcessed) {
            if (market.getIsSuspended())
                isSuspended.add(market);
            else
                notSuspended.add(market);
        }
    }

    // Pair up
    while (! notSuspended.isEmpty() && ! isSuspended.isEmpty()) {
        Market market1 = notSuspended.remove();
        Market market2 = isSuspended.remove();
        Pair<Market, Market> marketPair = new Pair<>(market1, market2);
        market1.setWasProcessed(true);
        market2.setWasProcessed(true);
        // use marketPair here
    }
}