<>JavaSE - Collection class - Tool class

Learning objectives of this section :

* Understand and master the use of iterators ;
* Understand and master the use of comparator ;
* Understand and master the use of selectors ;
* Understand and master Collections Common methods in tool classes .
<>1. Collection tool interface

Java Many tool interfaces are provided for the collection framework , We can implement or use these interfaces to modify and customize the collection .

<>1.1 iterator

<>1. Iterable Interface

Iterable Interface at java.lang Bao Xia , Ergodic .

Collection Interface inherits Iterable Interface , therefore Collection Collections can be traversed using iterators .Iterable Methods provided by the interface :

Method return value function
iterator()Iterator<T> Gets the iterator for the current collection
<>2. Iterator Interface

Iterator Interface at java.util Bao Xia , realization Iterator The class of the interface is called an iterator , You can use iterator pairs Collection Collection for traversal and other operations ,
Iterator Methods provided by the interface :

Method return value function
hasNext()boolean Returns whether an element exists at the next position of the cursor
next()E Returns the element at the next position of the cursor
remove()void Remove element at cursor position
Write code to test :
import java.util.ArrayList; import java.util.Iterator; import java.util.List;
public class TestIterator { public static void main(String[] args) { List<
Integer> list = new ArrayList<>(); list.add(57); list.add(6); list.add(-64);
Iterator<Integer> iterator1 = list.iterator(); while (iterator1.hasNext()) { if
(iterator1.next().equals(6)) { iterator1.remove(); } } Iterator<Integer>
iterator2= list.iterator(); while (iterator2.hasNext()) { System.out.print(
iterator2.next() + " "); } } } // Operation results // 57 -64
Characteristics of iterators :

* The iterator has a cursor , The cursor of the iterator just obtained points to the previous element of the first element in the collection (null);
* call hasNext() Method checks whether an element exists next to the position the cursor points to , Is to return true, No return false, Control conditions available for the cycle .
* call next() Method, the cursor moves back one element first , Then return the element of the cursor position after moving . If the cursor has reached the end of the collection ( Namely hasNext() Method return false
), Call again at this time next() Method will throw NoSuchElementException abnormal ;
* call remove() Method, the cursor removes the element at the current position . If not called at this time next() method , Or already called remove() method , At this time, the element pointed by the cursor is null
. Call again remove() Method is thrown IllegalStateException abnormal ;
* Every call iterator() Method returns a new iterator , Independent of iterators that have been previously acquired , The cursor position is the initial position .
Collection The of a collection can be traversed using iterators , You can also use foreach Circular statement ( Namely enhancement for loop ) Traverse :
public class TestIterator { public static void main(String[] args) { List<
Integer> list = new ArrayList<>(); list.add(57); list.add(6); list.add(-64); for
(Integer i : list) { System.out.println(i); } } } // Operation results // 57 6 -64
<>1.2 comparator

Comparator in use TreeSet and TreeMap Collection is often used , You can sort the keys of elements or key value pairs according to an attribute .

There are two sorting methods :

* Natural sorting : Let the key implementation of an element or key value pair Comparable Interface and override compareTo() method ;
* Custom sorting : Write external comparator , realization Comparator Interface and override compare() method .
<>1. Comparable Interface

Comparable Interface at java.lang Bao Xia , It is called an internal comparator , Define where to sort JavaBean Class interior . It has only one way :

Method return value function
compareTo(T o)int Internal comparison method , Compare the current object with the parameter object
The key of element and key value pair can be implemented Comparable Interface , rewrite compareTo() method , To achieve natural sorting :
public class Person implements Comparable<Person> { private Integer age;
private String name; @Override public int compareTo(Person o) { if (o == null) {
throw new IllegalArgumentException(); } // yes age Sort // Return if equal 0 if (this.age.
equals(o.getAge())) { return 0; // age Sort from small to large // If current age Returns a positive number larger than the parameter (1) } else if (
this.age > o.getAge()) { return 1; // If current age Returns a negative number than the parameter (-1) } else { return -1;
} } // Omit other codes }
Write code to test :
import java.util.Set; import java.util.TreeSet; public class TestComparable {
public static void main(String[] args) { Set<Person> set = new TreeSet<>(); set.
add(new Person().setAge(32).setName(" Zhang San ")); set.add(new Person().setAge(24).
setName(" Li Si ")); set.add(new Person().setAge(35).setName(" Wang Wu ")); set.add(new
Person().setAge(18).setName(" Zhao Liu ")); for (Person p : set) { System.out.println(p)
; } } } /* Operation results Person{age=18, name=' Zhao Liu '} Person{age=24, name=' Li Si '}
Person{age=32, name=' Zhang San '} Person{age=35, name=' Wang Wu '} */
<>2. Comparator Interface

Comparator Interface at java.util Bao Xia , It is called an external comparator , Defined in JavaBean Outside of class , Is a separate class ( Most use the form of internal classes ).

It was @FunctionalInterface Annotation , So you can use lambda Expression implementation . Its main method :

Method return value function
compare(T o1, T o2)int External comparison method , object o1 And objects o2 Compare
Implementation of external comparator Comparator Interface , And rewrite compare() method , Then let the collection use , To achieve custom sorting :
public class TestComparable { public static void main(String[] args) { //
Write an external comparator using an internal class // lambda Expression writing : // Comparator<Person> comparator = (o1, o2) -> {
// if (o1 == null || o2 == null) { // throw new IllegalArgumentException(); // }
// if (o1.getAge().equals(o2.getAge())) { // return 0; // } else if
(o1.getAge() > o2.getAge()) { // return -1; // } else { // return 1; // } // };
Comparator<Person> comparator = new Comparator<Person>() { @Override public int
compare(Person o1, Person o2) { if (o1 == null || o2 == null) { throw new
IllegalArgumentException(); } // yes age Sort // Return if equal 0 if (o1.getAge().equals(o2.
getAge())) { return 0; // age Sort from large to small // If o1 of age than o2 Large returns a negative number (-1) } else if (o1.
getAge() > o2.getAge()) { return -1; // If o1 of age than o2 Small returns a positive number (1) } else { return 1;
} } }; // Parametric construction method using set , Pass in comparator for custom sorting Set<Person> set = new TreeSet<>(comparator);
set.add(new Person().setAge(32).setName(" Zhang San ")); set.add(new Person().setAge(24).
setName(" Li Si ")); set.add(new Person().setAge(35).setName(" Wang Wu ")); set.add(new
Person().setAge(18).setName(" Zhao Liu ")); for (Person p : set) { System.out.println(p)
; } } } /* Operation results Person{age=35, name=' Wang Wu '} Person{age=32, name=' Zhang San '}
Person{age=24, name=' Li Si '} Person{age=18, name=' Zhao Liu '} */
<>1.3 filter (Predicate Interface )

Predicate Interface at java.util.function Bao Xia , It can be used to filter the data in the collection with a certain condition , So it is called filter .

It was @FunctionalInterface Annotation , Therefore, you can use lambda Expression implementation . Its main methods :

Method return value function
test(T t)boolean test method , If return true Then it meets the conditions , return false Unqualified
use 1.2 Stanza Person class , Write code to test :
public class TestPredicate { public static void main(String[] args) { // filter
// lambda Expression writing : // Predicate<Person> filter = person -> { // return
person.getAge() > 30; // }; Predicate<Person> filter = new Predicate<Person>() {
@Override public boolean test(Person person) { // screen age greater than 30 of person object return
person.getAge() > 30; } }; Set<Person> set = new TreeSet<>(); set.add(new Person
().setAge(32).setName(" Zhang San ")); set.add(new Person().setAge(24).setName(" Li Si "));
set.add(new Person().setAge(35).setName(" Wang Wu ")); set.add(new Person().setAge(18).
setName(" Zhao Liu ")); // Remove the filter that meets the filter conditions person object set.removeIf(filter); for (Person p : set)
{ System.out.println(p); } } } /* Operation results Person{age=18, name=' Zhao Liu '} Person{age=24,
name=' Li Si '} */
<>2. Collections Tool class

Collections The tool class is located in java.util Bao Xia , It provides a number of static methods for Collection Set and Map Various operations of the collection .

<>2.1 Query method

Collections Query method provided by tool class :

Method return value function
max(Collection<? extends T> coll)T Return in natural order Collection aggregate coll Maximum element in
max(Collection<? extends T> coll, Comparator<? super T> comp)T Incoming comparator comp Sort by custom
return Collection aggregate coll Maximum element in
min(Collection<? extends T> coll)T Return in natural order Collection aggregate coll Minimum element in
min(Collection<? extends T> coll, Comparator<? super T> comp)T Incoming comparator comp Sort by custom
return Collection aggregate coll Minimum element in
frequency(Collection<?> c, Object o)int Return element o stay Collection aggregate c Number of occurrences in
<>2.2 Operation method

Collections Operation methods provided by tool classes :

Method return value function
addAll(Collection<? super T> c, T... elements)boolean towards Collection aggregate c Add element to , You can add more than one
element
copy(List<? super T> dest, List<? extends T> src)void take List aggregate src Copy elements from to List aggregate
desc in ,
The index of the copied element remains unchanged ,desc Length at least equal to src Same length
fill(List<? super T> list, T obj)void take obj Fill to List aggregate list in
replaceAll(List<T> list, T oldVal, T newVal)boolean take List aggregate list All elements in oldVal Replace with element
newVal
swap(List<?> list, int i, int j)void take List aggregate list Index in is i and j Element exchange of location
<>2.3 Sorting method

Collections Sorting method provided by tool class :

Method return value function
reverse(List<?> list)void take List aggregate list The elements in are inverted
shuffle(List<?> list)void take List aggregate list Random sorting of elements in
shuffle(List<?> list, Random rnd)void Use specified random number generator rnd yes List aggregate list Random sorting of elements in
sort(List<T> list)void According to an attribute of an element List aggregate list Natural ordering of elements in
sort(List<T> list, Comparator<? super T> c)void Incoming comparator c yes List aggregate list Custom sorting of elements in
<>2.4 Singleton set method

These methods return an immutable collection with only one element , And the length is only 1, Save memory space :

Method return value function
singleton(T o)Set<T> Returns an element with only o Immutability of Set aggregate
singletonList(T o)List<T> Returns an element with only o Immutability of List aggregate
singletonMap(K key, V value)Map<K,V> Returns an immutable with only one key value pair Map aggregate ,
The key of the key value pair is key, The value of the key value pair is value
<>2.5 Empty set method

These methods return an empty immutable collection , Save memory space :

Method return value function
emptyList()List<T> Returns an immutable null List aggregate
emptySet()Set<T> Returns an immutable null Set aggregate
emptyMap()Map<K,V> Returns an immutable null Map aggregate
<>2.6 Synchronous set method

These methods wrap the incoming collection as a thread safe collection , For multithreaded environments :

Method return value function
synchronizedList(List<T> list)List<T> take List aggregate list Wrapped as thread safe List aggregate
synchronizedSet(Set<T> s)Set<T> take Set aggregate s Wrapped as thread safe Set aggregate
synchronizedSortedSet(SortedSet<T> s)SortedSet<T> take SortedSet aggregate s Package as
Thread safe SortedSet aggregate
synchronizedNavigableSet(NavigableSet<T> s)NavigableSet<T> s) take NavigableSet aggregate s
Wrapped as thread safe NavigableSet aggregate
synchronizedMap(Map<K,V> m)Map<K,V> take Map aggregate m Wrapped as thread safe Map aggregate
synchronizedSortedMap(SortedMap<K,V> m)SortedMap<K,V> take SortedMap aggregate m Wrap as thread safe
of SortedMap aggregate
synchronizedNavigableMap(NavigableMap<K,V> m)NavigableMap<K,V> take NavigableMap aggregate m
Package as
Thread safe NavigableMap aggregate

Technology