How to use two lists to filter out the attributes that are not included in the other list based on the attributes in one list, using streams to implement

Insert image description here

You can use Java 8 streams to achieve this functionality. Suppose you have two Lists containing objects, each object has an attribute, and you want to filter out objects that do not contain this attribute value in the other List based on the attribute value in one List. Here's a way to do this using streams

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class MyClass {
    private String property;

    public MyClass(String property) {
        this.property = property;
    }

    public String getProperty() {
        return property;
    }
}

public class Main {
    public static void main(String[] args) {
        List<MyClass> list1 = new ArrayList<>();
        list1.add(new MyClass("A"));
        list1.add(new MyClass("B"));
        list1.add(new MyClass("C"));
        
        List<String> list2 = new ArrayList<>();
        list2.add("A");
        list2.add("B");
        
        List<MyClass> filteredList = list1.stream()
                .filter(obj -> list2.contains(obj.getProperty()))
                .collect(Collectors.toList());

        filteredList.forEach(obj -> System.out.println(obj.getProperty()));
    }
}

In the above example, we have two Lists: list1 contains MyClass objects, each object has an attribute property; list2 contains some property values. We use the stream to filter the objects in list1, keep only those objects whose property values ​​exist in list2, and finally collect the filtered results into filteredList.

The output will be:

A
B

This is to filter out objects in list1 that do not contain this part of the attribute based on the attribute values ​​in list2. You can modify the code according to your actual needs to adapt to different data types and attribute names.

What should I write if there are many attributes in the class?

If there are many attributes in the class, you can write appropriate filtering conditions as needed to filter out objects that do not meet the requirements. Below is an example that demonstrates how to filter based on multiple properties in a class.

Suppose you have a class called Person that has multiple properties, including name, age, and gender. You want to filter Person objects based on a set of criteria, including age greater than or equal to 18 and gender being "male". Here is a sample code using streams:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Person {
    private String name;
    private int age;
    private String gender;

    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getGender() {
        return gender;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 28, "female"));
        personList.add(new Person("Bob", 20, "male"));
        personList.add(new Person("Charlie", 25, "male"));
        personList.add(new Person("Diana", 16, "female"));

        List<Person> filteredList = personList.stream()
                .filter(person -> person.getAge() >= 18 && person.getGender().equals("male"))
                .collect(Collectors.toList());

        filteredList.forEach(person -> System.out.println(person.getName()));
    }
}

In the above example, we defined a Person class with three attributes: name, age, and gender. We use the filter operation of the stream to filter the objects in the personList, and only keep those objects whose age is greater than or equal to 18 and whose gender is "male". Finally, we collect the filtered results into a filteredList and print the name property of each object.

The output will be:

Bob
Charlie

This is to filter out Person objects that do not meet the requirements in personList based on the defined conditions. You can modify the code according to your actual needs and add or modify filter conditions to adapt to different attributes and values.

If the element objects in the two lists have multiple attributes. How to filter elements of a collection based on a certain attribute of an object in a list?

If the element objects in the two collections have multiple attributes, and you want to filter the elements in the other collection based on a certain attribute value of the object in one collection, you can use streams and conditional predicates to achieve. The following is a sample code that demonstrates how to filter elements in one collection based on a property value of objects in another collection:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Element {
    private int id;
    private String name;

    public Element(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Element> list1 = new ArrayList<>();
        list1.add(new Element(1, "A"));
        list1.add(new Element(2, "B"));
        list1.add(new Element(3, "C"));

        List<Element> list2 = new ArrayList<>();
        list2.add(new Element(1, "X"));
        list2.add(new Element(2, "Y"));
        list2.add(new Element(3, "Z"));

        List<Element> filteredList = list2.stream()
                .filter(obj -> list1.stream()
                        .map(Element::getId)
                        .collect(Collectors.toList())
                        .contains(obj.getId()))
                .collect(Collectors.toList());

        filteredList.forEach(obj -> System.out.println(obj.getName()));
    }
}

In the above example, we have two collections list1 and list2. Each collection contains Element objects. Each object has two attributes: id and name. We use the stream to filter the elements in list2, keep only those elements whose id values ​​exist in list1, and finally collect the filtered results into filteredList.

The output will be:

X
Y
Z

This is to filter out elements in list2 that do not contain this part of the attribute based on the id attribute value of the element in list1. You can modify the code according to your actual needs to adapt to different data types and attribute names.

How to write if you want to retain the entire object in the collection after filtering?

If you want to keep the entire object in the collection after filtering, not just the attribute value, you can use the anyMatch() method when filtering to determine whether a certain attribute value exists in another collection, and then pass the judged object Keep it. Here is a sample code:

import java.util.ArrayList;
import java.util.List;

class Element {
    private int id;
    private String name;

    public Element(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Element> list1 = new ArrayList<>();
        list1.add(new Element(1, "A"));
        list1.add(new Element(2, "B"));
        list1.add(new Element(3, "C"));

        List<Element> list2 = new ArrayList<>();
        list2.add(new Element(1, "X"));
        list2.add(new Element(2, "Y"));
        list2.add(new Element(3, "Z"));

        List<Element> filteredList = new ArrayList<>();

        for (Element obj2 : list2) {
            if (list1.stream().anyMatch(obj1 -> obj1.getId() == obj2.getId())) {
                filteredList.add(obj2);
            }
        }

        filteredList.forEach(obj -> System.out.println(obj.getName()));
    }
}

In the above example, we have two collections list1 and list2, which contain Element objects and have corresponding properties. We traverse the elements in list2 and use the anyMatch() method to check whether the id attribute of the element exists in any element in list1. If present, the object is added to the filteredList collection. Finally, we print out the name attribute of the elements in the filteredList.

The output will be:

X
Y
Z

In this way, elements in list2 that do not contain this part of the attribute are filtered out according to a certain attribute value of the object in list1, and the entire object is retained. You can modify the code to accommodate different data types and property names according to your specific needs.

Guess you like

Origin blog.csdn.net/weixin_50503886/article/details/132310089