Java Collections -- Traversal of Collections, Iterator, Predicate

The length of the array is immutable and data with mapping relationships cannot be saved. Java provides collections, which are mainly responsible for saving and filling other elements. Therefore, collection classes are also called container classes.

Arrays can hold basic data types and objects, while collections can only hold objects.

The collection of Java classes is mainly derived from two interfaces: Collection and Map. Collection's derived classes Set and List represent disordered and ordered collections; Queue is a Java queue implementation.

Map implementation classes are used to store data with mapping relationships, and each saved data consists of two values, key-value. The key is not repeatable. Set collections can't remember the order of adding this element, so Set collections can't be repeated; List collections are very much like an array, they can remember the order of adding elements each time, and the length of List is variable.

If you access the elements in a List collection, you can access them according to the index of the elements; if you access the elements in a Map collection, you can access them according to the value of the key; and if you access the elements in a Set collection, you can only access them according to the elements themselves.

Traversal sets:
Mode 1 Lambda expression, here is the traversal set
import java.util.Collection;
import java.util.HashSet;
/*
    Java Iterator adds a forEach(Consumer action) method. The type of parameters required by this method is a functional interface.
    The Iterator interface is the parent of Collection, so Collection can call this method directly.
    When Iterator's forEach method is called, the program passes the collection elements in turn to Consumer's accept() method.
*/
public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new HashSet<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        c.forEach(obj -> System.out.println("Iterative elements: " + obj));
    }
}

Mode 2 foreach traversal cycle

import java.util.Collection;
import java.util.HashSet;
//foreach foreach
public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new HashSet<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        for(Object obj : c){
            System.out.println(obj);
        }
    }
}

Mode Three Iterator Method

import java.util.HashSet;
import java.util.Iterator;
//foreach foreach
public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new HashSet<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        Iterator iter = c.iterator();
        while(iter.hasNext()){
            System.out.println(iter.next());
        }
    }
}

Mode 4 for cycle

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
//for Cycle, this way is only right List It works because Set It's out of order, and you can't get elements in an array.
public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new LinkedList<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        for(int i = 0; i < c.length; i++){
            System.out.println(c[i]);
        }
    }
}

Iterator is mainly used to iterate elements in Collection set. Iterator object is also called iterator. Iterator can not change the element itself, but can delete the object returned by the last next method.

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;

public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new LinkedList<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        Iterator iter = c.iterator();
        while(iter.hasNext()){
            String str = (String)iter.next();
            if(str.equals("Lily")){
                iter.remove();
            }
            System.out.println(str);
        }
        //Here Lily Has been deleted, but in iterator Of while The last thing in the loop is output. Lily
        System.out.println(c);
    }
}

Iterator itself does not dress up objects, and Iterator must be attached to Collection objects. When Iterator is used to iterate a set element, Iterator does not pass the set element itself to the iteration variable, but the value of the set element to the iteration variable, so modifying the value of the iteration variable has no effect on the set element itself.

Iterator iterator uses a fail-fast mechanism. Once the set is detected to have been modified during the iteration process, the program will trigger a failure. Deletion during iterations causes exceptions, and exceptions are not raised until specific elements are deleted.

For HashSet, ArrayList, etc., deleting elements during iteration causes exceptions, which are not thrown unless a particular element in the collection is deleted.

Iterative comparison:

1. Traditional for loop traversal based on counter:

Sequential storage: High read performance. Suitable for traversing sequential storage collections.
Chain Storage: The time complexity is too large to be suitable for traversing the collection of chain storage.
2. Iterator traversal:
Sequential Storage: If you don't care too much about time, it's recommended to choose this method. After all, the code is more concise, and it also prevents the problem of Off-By-One.
Chain Storage: It's significant. It's tempting to reduce the average time complexity to O(n), so this traversal method is recommended.
3. foreach loop traversal:
foreach just makes the code more concise, but it has some drawbacks: it can't manipulate data sets (delete, etc.) during traversal, so it's not used in some situations. And it's based on Iterator itself, but because of the problem of type conversion, it's a little slower than using Iterator directly. Fortunately, the time complexity is the same. So how to choose, refer to the above two ways, make a compromise choice.

Iterator iterates over elements in the forEachRemaining way, here is Iterator, the traversal iterator

public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new LinkedList<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        Iterator iter = c.iterator();
        iter.forEachRemaining(obj -> System.out.println("Iterative elements: " + obj));
    }
}

 

New Predicate operation set removeIf(Predicate p) in Java 8

public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new LinkedList<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        c.removeIf(ele -> ele.equals("Jim Green"));
        
        System.out.println(c);
    }
}

Input ele as a parameter (the element of the collection), delete the element that meets the condition.

import java.util.function.Predicate;

public class CollectionClass{
    public static void main(String[] args){
        Collection<String> c = new LinkedList<String>();
        //Adding elements
        c.add("lilei");
        c.add("hanmeimei");
        c.add("Jim Green");
        c.add("Lily");
        c.add("Lucy");
        
        //ele -> ((String)ele).contains("i") Judging conditions, Lambda Expression Writing test()Method realization
        int i = callAll(c, ele -> ((String)ele).contains("i"));
        
        System.out.println(i);
    }
    
    public  static int callAll(Collection c, Predicate p){
        int total = 0;
        for(Object obj : c){
            //Predicate Of test()Method to determine whether the object is satisfied Predicate Specified Conditions
            if(p.test(obj)){
                total++;
            }
        }
        return total;
    }
}

Keywords: Delphi Java Lambda

Added by seb hughes on Wed, 26 Jun 2019 00:12:37 +0300