Iterator
Java Iterator is not a collection, it is a method for accessing a collection and can be used for iteration ArrayList and HashSet For a set, the bottom layer of foreach is also an iterator. The deletion operation of a set should be carried out in the iterator. Take ArrayList for example. The bottom layer is an array structure. When deleting elements, the subsequent elements should be moved forward one bit. At this time, the value on the corresponding index changes. As follows, if the deletion operation is carried out in the loop, If the value in the current index position i is deleted, the value in the i+1 index position will automatically move to i, and the value of i+1 will become the value in the i+2 index position. The value in the i+1 index position is deleted from the original i+2 value, and the value in the original i+1 position is already in the original i position, which may cause missing deletion.
ArrayList<String> s = new ArrayList<>(); s.add("1"); s.add("2"); s.add("3"); s.add("4"); s.add("5"); System.out.println(s.get(2));//3 s.remove(2); System.out.println(s.get(2));//4
The two basic operations of iterator it are next, hasNext, and remove.
ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(12); numbers.add(8); numbers.add(2); numbers.add(23); Iterator<Integer> it = numbers.iterator(); while(it.hasNext()) { Integer i = it.next(); if(i < 10) { //Sometimes, the judgment condition of times can be replaced with stream flow it.remove(); // Delete elements less than 10 } } System.out.println(numbers); }
There are two counting variables inside the iterator. The initial position starts at - 1, usually it Hasnext(), if any, it Next(), the return value is an element of the collection. Because it starts from - 1, the element at the next index position of the collection is at the 0 index position, and then it Remove(), delete the element that currently meets the condition.
Stream
Stream is equivalent to the advanced use of Iterator and provides an internal iterative method
It is divided into three parts: create flow, transform flow and aggregation
How to create a stream:
The Collection interface provides a method to build a stream: the stream() method
Static factory method of Stream interface
Conversion flow
distinct:
The elements contained in the Stream are de duplicated (the de duplication logic depends on the equals method of the elements), and there are no duplicate elements in the newly generated Stream
filter:
For the elements contained in the Stream, use the given filter function for filtering. The newly generated Stream contains only qualified elements
map:
For the elements contained in the Stream, use the given conversion function for conversion. The newly generated Stream only contains the elements generated by conversion.
flatMap:
Similar to map, the difference is that each element is converted to a Stream object, which compresses the elements in the child Stream into the parent collection
peek:
Generate a new Stream containing all elements of the original Stream, and provide a consumption function (Consumer instance). When each element of the new Stream is consumed, the given consumption function will be executed;
limit: truncate a Stream to obtain its first n elements. If the number of elements contained in the original Stream is less than N, all its elements will be obtained
skip: returns a new Stream composed of the remaining elements after discarding the first n elements of the original Stream. If the number of elements contained in the original Stream is less than N, an empty Stream is returned
The intermediate transformation flows can be combined continuously
List<Integer> nums = Lists.newArrayList(1,1,null,2,3,4,null,5,6,7,8,9,10); System.out.println("sum is:"+nums.stream().filter(num -> num != null). distinct().mapToInt(num -> num * 2). peek(System.out::println).skip(2).limit(4).sum());
polymerization
There is only one method corresponding to variable aggregation: collect gathers the results of intermediate flows into a container
Tool class of Collector – [collectors]: collectors toCollection()/Collectors. toList()/Collectors. toSet()
For example: collect(Collectors.toList());
Other aggregation reduce methods: the reduce method is very general
ints.stream().reduce((sum, item) -> sum + item).get()
The reduce method accepts a function. The function has two parameters. The first parameter is the return value (also known as the intermediate result) of the last function execution. The second parameter is the element in the stream. The function adds the two values, and the resulting sum will be assigned to the first parameter of the next function execution.
count method: get the number of elements in the Stream
allMatch: whether all elements in the Stream meet the given matching conditions
anyMatch: whether any element in the Stream meets the matching criteria
noneMatch: is it true that all elements in the Stream do not meet the given matching criteria
findFirst: returns the first element in the Stream. If the Stream is empty, it returns null Optional
Summary:
For the example of the combination of Iterator and Stream in the above code:
Two classes are provided: Student and @Data @Getter @Setter public class Student { private String stuName; private int stuAge; public Student(String stuName, int stuAge) { this.stuName = stuName; this.stuAge = stuAge; } public Student() { } } ---------------------------------------------------------- @Data @Getter @Setter public class User { private String name; private int age; private List<Student> stu; // Relationship between two classes public User(String name, int age, List<Student> stu) { this.name = name; this.age = age; this.stu = stu; } public User() { } }
Student stu1 = new Student("Student Xiao Liu", 22); Student stu2 = new Student("Student Xiao Zhang", 23); Student stu3 = new Student("Student Xiao Zhao", 24); Student stu4 = new Student("Student money", 24); Student stu5 = new Student("Student Xiaoqiang", 24); //Simulate the data found in the back-end database (there is an association between students and users) ArrayList<Student> students = new ArrayList<>(); students.add(stu1); students.add(stu2); students.add(stu3); students.add(stu4); User user = new User("Zhang San", 55, students); //Analog front-end incoming data parameters ArrayList<Student> uStudents = new ArrayList<>(); uStudents.add(stu1); uStudents.add(stu3); uStudents.add(stu5); User user2 = new User("Zhao Liu", 57, uStudents); //Assuming that the Spring Data framework adopted by the back-end inherits hiberarate, it can automatically update the relationship between intermediate tables by changing the collection elements //In other words, I want to compare the data found in the simulation database with the data passed in from the front end, and delete the redundant data; If there is no data from the front end, it will be added //Realize the first requirement: delete the data found by the back end that is not transmitted by the front end Iterator<Student> it = user.getStu().iterator(); while (it.hasNext()){ Student next = it.next(); if (user2.getStu().stream().noneMatch(item->next.getStuName().equals(item.getStuName()))) { //Here is the combination of stream stream and Iterator as a deletion condition it.remove(); } } System.out.println(user); //User(name = Zhang San, age=55, stu=[Student(stuName = Xiao Liu, stuAge=22), Student(stuName = Xiao Zhao, stuAge=24)]) //The original stu2 and stu3 are gone and deleted //The second requirement is that the front end transmits a new amount element to the back end for storage // (there is no blank judgment on the object, and we don't know when to use Optional) for (Student student : user2.getStu()) { Optional<Student> first = user.getStu().stream().filter(item -> student.getStuName().equals(item.getStuName())).findFirst(); if (first.isPresent()){ continue; } user.getStu().add(student); } System.out.println(user); //User(name = Zhang San, age=55, stu=[Student(stuName = student Xiao Liu, stuAge=22), Student(stuName = student Xiao Zhao, stuAge=24), Student(stuName = student Xiao Qiang, stuAge=24)]) //Add the parameters newly passed in from the front end and not stored in the back end to the collection, xxxmethod.save(user) //Resave and update intermediate table relationships }
Java 8 Optional detailed usage_ Traveller CSDN blog_ Optional usage