Two lists. How to use stream writing to assign certain attributes in an object in a list based on the attribute values in another list?

Two lists. How to use stream writing to assign certain attributes in an object in a list based on the attribute values ​​in another list?

You can use streams and lambda expressions in Java 8 and above to achieve this requirement. Suppose there are two Lists, one is sourceList, containing objects to which attributes are to be assigned; the other is targetList, containing objects with attribute values. Here is a sample code:

import java.util.*;

class SourceObject {
    private String name;
    private int age;

    // 构造函数、getter和setter方法省略
}

class TargetObject {
    private String name;
    private int age;

    // 构造函数、getter和setter方法省略
}

public class Main {
    public static void main(String[] args) {
        List<SourceObject> sourceList = new ArrayList<>();
        sourceList.add(new SourceObject("John", 25));
        sourceList.add(new SourceObject("Alice", 30));
        sourceList.add(new SourceObject("Bob", 35));

        List<TargetObject> targetList = new ArrayList<>();
        targetList.add(new TargetObject(null, 0));
        targetList.add(new TargetObject(null, 0));
        targetList.add(new TargetObject(null, 0));

        // 使用流的方式将属性赋值
        List<TargetObject> result = IntStream.range(0, sourceList.size())
                .mapToObj(i -> {
                    TargetObject target = targetList.get(i);
                    SourceObject source = sourceList.get(i);
                    target.setName(source.getName());
                    target.setAge(source.getAge());
                    return target;
                })
                .collect(Collectors.toList());

        // 输出结果
        result.forEach(obj -> System.out.println("Name: " + obj.getName() + ", Age: " + obj.getAge()));
    }
}

In this example, we use the range method of IntStream to generate a sequence of numbers, and then use the mapToObj method to map the indexes in the sequence to the objects in the source and target lists one by one. Then, we obtain the objects in the source list and the target list according to the corresponding indexes, and assign the attributes that need to be assigned. Finally, collect the assigned target objects into a new list.

Use streams in Java to turn list into kv structure map?

In Java, you can use the collect method of the stream (Stream) combined with Collectors.toMap to convert the List into a KV structure Map. Here is a sample code:

import java.util.*;
import java.util.stream.Collectors;

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("John", 25));
        personList.add(new Person("Alice", 30));
        personList.add(new Person("Bob", 35));

        // 使用流的方式将List转换为Map
        Map<String, Integer> personMap = personList.stream()
                .collect(Collectors.toMap(Person::getName, Person::getAge));

        // 输出结果
        personMap.forEach((name, age) -> System.out.println("Name: " + name + ", Age: " + age));
    }
}

In this example, we convert the personList into a stream using the stream method of the stream. Then, use the collect method combined with Collectors.toMap to map each element in the stream into a key-value pair and collect them into a Map. In the toMap method, Person::getName means using the name attribute of the Person object as the key, and Person::getAge means using the age attribute of the Person object as the value. Finally, we traverse and output the converted Map results through the forEach method.

Please note that if there are duplicate keys in the List, a java.lang.IllegalStateException will be thrown. In this case, you can use the third parameter mergeFunction to handle duplicate key conflicts, for example:

Map<String, Integer> personMap = personList.stream()
        .collect(Collectors.toMap(Person::getName, Person::getAge, (oldValue, newValue) -> newValue));

In this example, we simply selected the new value as the value of the key, you can handle it appropriately according to your needs.

Guess you like

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