What is the difference Java are several ways to traverse the set

  • for i traversal

      This traversal is implemented RandomAccess traverse the set of choice, (1) and get (10000) for such a speed as to get set, very fast, set is an array of such bottom, can know the address set in accordance with the subscript calculated shift amount quickly find the elements

     mybait returned by the query list type ArrayList oh

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>(10_000);
        for (int i = 0; i < 10_000; i++) {
            list.add(i);
        }
        int size = list.size();
        for (int i = 0; i < size; i++) {
            handleSomeThing();
        }
    }

    public static void handleSomeThing() {
     
    }
  • Iterates over

      Not implemented RandomAccess set for the interface, can not be used for i traversed above, because of poor performance, which is the bottom of a list List get (0), and get (10000) will be much difference in speed only by 0 1 found, 1 to find 2, ... and then find the location of elements 10000  

     Use iterates over time, you can not use the Delete method of collection, otherwise it will throw an exception

 

 public static void main(String[] args) {

        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < 10_000; i++) {
            list.add(i);
        }

        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            handleSomeThing();
        }
    }

    public static void handleSomeThing() {

    }
  • Super for traversal

  The bottom is achieved with iterators

   public static void main(String[] args) {
 
        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < 10_000; i++) {
            list.add(i);
        }

        for (Integer i : list) {
            handleSomeThing();
        }
    }

    public static void handleSomeThing() {

    }
  • java8 traverse the stream

     This will open traverse multi-threaded, try the following code bar

 public static void main(String[] args) {

        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < 10_000; i++) {
            list.add(i);
        }

        long startTime = System.currentTimeMillis();
        list.parallelStream().forEach(integer -> {
            handleSomeThing();
        });
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }

    public static void handleSomeThing() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

 

Guess you like

Origin www.cnblogs.com/yangmingzi/p/11199075.html