迭代Java中的Set的最佳方法

时间:2017-09-28 05:04:26

标签: java loops collections iterator set

情况是我必须遍历一个大小最多为5000个元素的集合。目前,我正在使用带迭代器的正常for循环。

for (Iterator iterator = allValues.iterator(); iterator.hasNext();) {

     ListMetadataElem element = (ListMetadataElem) iterator.next(); 
     NameValueObject value = new NameValueObject(); 
     value.setId(element.getListMetadataElemSeqId().toString());    
     value.setValue(element.getListMetadataElemNm());   
     abstractVO.getAllListMetadataElems().add(value);       
}

问题是它需要花费太多时间来迭代6-7秒,我必须多次调用相同的循环。

1 个答案:

答案 0 :(得分:4)

以下是比较:

public class IterateSet {

    public static void main(String[] args) {

        //example Set
        Set<String> set = new HashSet<>();

        set.add("Jack");
        set.add("John");
        set.add("Joe");
        set.add("Josh");

        long startTime = System.nanoTime();
        long endTime = System.nanoTime();

        //using iterator
        System.out.println("Using Iterator");
        startTime = System.nanoTime();
        Iterator<String> setIterator = set.iterator();
        while(setIterator.hasNext()){
            System.out.println(setIterator.next());
        }
        endTime = System.nanoTime();
        long durationIterator = (endTime - startTime);


        //using lambda
        System.out.println("Using Lambda");
        startTime = System.nanoTime();
        set.forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationLambda = (endTime - startTime);


        //using Stream API
        System.out.println("Using Stream API");
        startTime = System.nanoTime();
        set.stream().forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationStreamAPI = (endTime - startTime);


        //using Split Iterator (not recommended)
        System.out.println("Using Split Iterator");
        startTime = System.nanoTime();
        Spliterator<String> splitIterator = set.spliterator();
        splitIterator.forEachRemaining((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationSplitIterator = (endTime - startTime);


        //time calculations
        System.out.println("Iterator Duration:" + durationIterator);
        System.out.println("Lamda Duration:" + durationLambda);
        System.out.println("Stream API:" + durationStreamAPI);
        System.out.println("Split Iterator:"+ durationSplitIterator);
    }
}

代码是自我解释的。 持续时间的结果是:

Iterator Duration:495287
Lamda Duration:50207470
Stream API:2427392
Split Iterator:567294

我们可以看到Lambda最长,而Iterator最快。 除此之外,还有传统的古老增强型循环。