Java 8 stream handles the same part (intersection) and deduplication of the List collection

A new feature of Java8-Stream is often used to process collections. It will not change the original structure of the collection. The advantage is that the code of Stream will be much cleaner than using for loop

This article mainly talks about: Get the intersection, difference, and de-duplication of two List sets

One, the intersection of two sets

For example: find students with the same name in two classes

public class Student {
    
    
	
	private String studentNo;
	//名字
    private String studentName;
	
	public Student(String studentNo, String studentName) {
    
    
        this.studentNo = studentNo;
        this.studentName = studentName;
    }
	
	//对象的比较涉及到equals()的重写, 这里仅仅比较studentName是否相同
	@Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return studentName.equals(student.getStudentName());
    }
	
	// set()和get()方法均省略..
}

The student is an object instance. What we want to compare is whether the names are the same. We only need to rewrite the equals() method.

Find intersection

@Test
public void test(){
    
    
	// 1班的学生
	List<Student> class01=new ArrayList<>();
    class01.add(new Student("1","小明"));
    class01.add(new Student("2","赵铁柱"));	
	
	// 2班的学生
	List<Student> class02=new ArrayList<>();
    class02.add(new Student("1","赵铁柱"));

	// 找两个班名字相同的同学(取交集),比较用的是重写的equals()
	List<Student> sameName=class01.stream().filter(class02::contains).collect(Collectors.toList());
	sameName.stream().forEach(student->System.out.println(student.getStudentName()+" "));
	
	//output : 赵铁柱
}    

Note that:
(1) class01.stream().filter(class02::contains)the filter () will retain the results for expression, content, there is an expression of class 1 and class 2 the name of the same classmates

(2) forEach is to traverse the collection, instead of for loop, the code is more concise

(3) collect(Collectors.toList())、collect(Collectors.toSet())、collect(Collectors.toMap())Collect the data of Stream into collections such as List, Map, Set, etc.

Second, the difference set

Output result: bc

@Test
public void test(){
    
    
	List<String> list01=Arrays.asList("a","b","c");
   	List<String> list02=Arrays.asList("a","e","f");
	
	//list01和list02的差集, 仅保留了 b,c
   	List<String> result=list01.stream().filter(word->!list02.contains(word)).collect(Collectors.toList());
   	result.stream().forEach(word->System.out.print(word+" "));
}

Three, de-duplication

Output result: abc

List<String> list=Arrays.asList("a","b","c","a");
List<String> distinct=list.stream().distinct().collect(Collectors.toList());
distinct.stream().forEach(word->System.out.print(word+" ")); 

Removed the repeated character "a"

Four, list.stream() is the construction method

Some friends may have list.stream()some doubts. It is a method of constructing Stream. The method of constructing Stream is as follows:

(1) Create Stream with collection

List<String> list=Arrays.asList("a","b","c");
//创建顺序流
Stream<String> stream=list.stream();
//创建并行流
Stream<String> parallelStream=list.parallelStream();

(2) Arrays.stream(array)Create Stream with array

int[] array={
    
    1,2,3,4,5};
IntStream stream=Arrays.stream(array);

(3) Stream<T> of(T... values)Create Stream with

Stream<Integer> stream=Stream.of(1,2,3,4,5);

The above three are commonly used. In addition iterate(),generate(), the latter is to generate random numbers, and both construction methods generate infinite streams (that is, the number of elements is infinite) .

If the number of requirements is limited, you need to use limit to limit, such as:

Stream<Integer> stream=Stream.iterate(0,num->num+3).limit(10)

Printed[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

Guess you like

Origin blog.csdn.net/qq_44384533/article/details/113883652