📜  Java迭代器和拆分器的区别

📅  最后修改于: 2021-09-14 02:07:00             🧑  作者: Mango

Java Iterator接口表示一个对象,该对象能够遍历一组Java对象,一次一个对象。 Iterator 接口是Java用于迭代对象集合的最古老的机制之一(尽管不是最古老的——Enumerator 早于 Iterator)。

此外,迭代器在两个方面不同于枚举:

1.迭代器允许调用者在元素迭代期间从指定集合中移除给定元素。

2.方法名称已得到增强。

Java
// Java program to illustrate Iterator interface
  
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JavaIteratorExample1 {
    public static void main(String[] args)
    {
  
        // create a linkedlist
        List list = new LinkedList<>();
  
        // Add elements
        list.add("Welcome");
        list.add("to");
        list.add("our");
        list.add("website");
  
        // print the list to the console
        System.out.println("The list is given as : "
                           + list);
  
        // call iterator on the list
        Iterator itr = list.iterator();
  
        // itr.hasNext() returns true if there
        // is still an element next to the current
        // element pointed by iterator
        while (itr.hasNext()) {
  
            // Returns the next element.
            System.out.println(itr.next());
        }
  
        // Removes the last element.
        itr.remove();
  
        // print the list after removing an
        // element
        System.out.println(
            "After the remove() method is called : "
            + list);
    }
}


Java
// Java program to illustrate a Spliterator
  
import java.util.*;
import java.util.stream.Stream;
  
public class InterfaceSpliteratorExample {
  
    public static void main(String args[])
    {
  
        // Create an object of array list
        ArrayList list = new ArrayList<>();
  
        // Add elements to the array list
        list.add(101);
        list.add(201);
        list.add(301);
        list.add(401);
        list.add(501);
  
        // create a stream on the list
        Stream str = list.stream();
  
        // Get Spliterator object on stream
        Spliterator splitr = str.spliterator();
  
        // Get size of the list
        // encountered by the
        // forEachRemaining method
        System.out.println("Estimate size: "
                           + splitr.estimateSize());
  
        // Print getExactSizeIfKnown
        // returns exact size if finite
        // or return -1
        System.out.println("Exact size: "
                           + splitr.getExactSizeIfKnown());
  
        // Check if the Spliterator has all
        // the characteristics
        System.out.println("Boolean Result: "
                           + splitr.hasCharacteristics(
                                 splitr.characteristics()));
  
        System.out.println("Elements of ArrayList :");
  
        // print elements using forEachRemaining
        splitr.forEachRemaining(
            (n) -> System.out.println(n));
  
        // Obtaining another Stream to the array list.
        Stream str1 = list.stream();
  
        splitr = str1.spliterator();
  
        // Obtain spliterator using     trySplit() method
        Spliterator splitr2 = splitr.trySplit();
  
        // If splitr can be partitioned use splitr2 first.
        if (splitr2 != null) {
  
            System.out.println("Output from splitr2: ");
            splitr2.forEachRemaining(
                (n) -> System.out.println(n));
        }
  
        // Now, use the splitr
        System.out.println("Output from splitr1: ");
        splitr.forEachRemaining(
            (n) -> System.out.println(n));
    }
}


输出
The list is given as : [Welcome, to, our, website]
Welcome
to
our
website
After the remove() method is called : [Welcome, to, our]

迭代器ListIterator,Spliterator 是一个Java Iterator,用于从 List 实现的对象中一个一个地迭代元素。

Spliterator的主要功能是:

  • 拆分源数据
  • 处理源数据

Interface Spliterator 包含在 JDK 8 中,除了顺序遍历之外,还可以利用并行性的优势。它被设计为迭代器的并行模拟。

Java

// Java program to illustrate a Spliterator
  
import java.util.*;
import java.util.stream.Stream;
  
public class InterfaceSpliteratorExample {
  
    public static void main(String args[])
    {
  
        // Create an object of array list
        ArrayList list = new ArrayList<>();
  
        // Add elements to the array list
        list.add(101);
        list.add(201);
        list.add(301);
        list.add(401);
        list.add(501);
  
        // create a stream on the list
        Stream str = list.stream();
  
        // Get Spliterator object on stream
        Spliterator splitr = str.spliterator();
  
        // Get size of the list
        // encountered by the
        // forEachRemaining method
        System.out.println("Estimate size: "
                           + splitr.estimateSize());
  
        // Print getExactSizeIfKnown
        // returns exact size if finite
        // or return -1
        System.out.println("Exact size: "
                           + splitr.getExactSizeIfKnown());
  
        // Check if the Spliterator has all
        // the characteristics
        System.out.println("Boolean Result: "
                           + splitr.hasCharacteristics(
                                 splitr.characteristics()));
  
        System.out.println("Elements of ArrayList :");
  
        // print elements using forEachRemaining
        splitr.forEachRemaining(
            (n) -> System.out.println(n));
  
        // Obtaining another Stream to the array list.
        Stream str1 = list.stream();
  
        splitr = str1.spliterator();
  
        // Obtain spliterator using     trySplit() method
        Spliterator splitr2 = splitr.trySplit();
  
        // If splitr can be partitioned use splitr2 first.
        if (splitr2 != null) {
  
            System.out.println("Output from splitr2: ");
            splitr2.forEachRemaining(
                (n) -> System.out.println(n));
        }
  
        // Now, use the splitr
        System.out.println("Output from splitr1: ");
        splitr.forEachRemaining(
            (n) -> System.out.println(n));
    }
}
输出
Estimate size: 5
Exact size: 5
Boolean Result: true
Elements of ArrayList :
101
201
301
401
501
Output from splitr2: 
101
201
Output from splitr1: 
301
401
501

JavaIterator和Spliterator的区别:

Iterator 

Spliterator

Introduced in Java 1.2 Introduced in Java 1.8
Iterator only iterates elements individually Spliterator traverse elements individually as well as in bulk
It is an iterator for whole collection API It is an iterator for both Collection and Stream API, except Map implementation classes 
It uses external iteration It uses internal iteration. 
It is a Universal iterator  It is Not a Universal iterator 
It does not support parallel programming It supports parallel programming by splitting the given element set so that each set can be processed individually.