[Java 8 New Features] Get a list of attributes in the object list

Get a list of a property in the object list

1. Example of usage

Get a property of all objects in the list

List<UserEntity> users = new ArrayList<>();
users.add(new UserEntity(1,"张三","18399990000"));
List<String> courseIds =  users.stream().map(UserEntity::getUserName).collect(Collectors.toList());

2. Detailed case

UserEntity.java

import java.io.Serializable;

/**
 * @author: shipleyleo
 * @create: 2023-06-03 15:22:54
 */
public class UserEntity implements Serializable {
    
    
    private Integer id;
    private String userName;
    private String phone;

    public UserEntity(Integer id, String userName, String phone) {
    
    
        this.id = id;
        this.userName = userName;
        this.phone = phone;
    }

    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }

    public String getPhone() {
    
    
        return phone;
    }

    public void setPhone(String phone) {
    
    
        this.phone = phone;
    }
}

Test.java

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

/**
 * @author: shipleyleo
 * @create: 2023-06-03 15:51:03
 */
public class Test {
    
    
    public static void main(String args[]){
    
    
        List<UserEntity> users = new ArrayList<>();
        users.add(new UserEntity(1,"张三","18399990000"));
        users.add(new UserEntity(2,"王五","18399990023"));
        users.add(new UserEntity(3,"里斯","18399990005"));
        // 获取list中所有对象的某个属性
        List<String> courseIds =  users.stream().map(UserEntity::getUserName).collect(Collectors.toList());
        System.out.println(courseIds); //[张三, 王五, 里斯]
    }
}

Output result:
insert image description here

Appendix: Basic usage of Java 8 Stream

1. Basic introduction to Java 8 Stream

The Java 8 API adds a new abstraction called stream Stream, which allows you to process data in a declarative way.

Stream provides a high-level abstraction for Java collection operations and representations in an intuitive way similar to querying data from a database with SQL statements.

Stream API can greatly improve the productivity of Java programmers, allowing programmers to write efficient, clean and concise code.

This style regards the collection of elements to be processed as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.

The element flow is processed by the intermediate operation in the pipeline, and finally the result of the previous processing is obtained by the terminal operation.

+--------------------+       +------+   +------+   +---+   +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+       +------+   +------+   +---+   +-------+

The above process is converted to Java code as:

List<Integer> transactionsIds = 
widgets.stream()
             .filter(b -> b.getColor() == RED)
             .sorted((x,y) -> x.getWeight() - y.getWeight())
             .mapToInt(Widget::getWeight)
             .sum();


2. Generate streams

In Java 8, the collection interface has two methods to generate streams:

  • stream() − Creates a serial stream for a collection.
  • parallelStream() − Creates a parallel stream for a collection.

1、map

The map method is used to map each element to the corresponding result. The following code snippet uses map to output the square number corresponding to the element:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

2、filter

The filter method is used to filter out elements by setting conditions. The following code snippet uses the filter method to filter out empty strings:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.stream().filter(string -> string.isEmpty()).count();

3、forEach

Stream provides a new method 'forEach' to iterate over each item in the stream. The following code snippet uses forEach to output 10 random numbers:

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

4、limit

The limit method is used to get the specified number of streams. The following code snippet uses the limit method to print out 10 pieces of data:

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

5、sorted

The sorted method is used to sort the stream. The following code snippet uses the sorted method to sort the output of 10 random numbers:

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

6. Parallel programs

parallelStream is an alternative to stream parallel handlers. In the following example we use parallelStream to output the number of empty strings:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

We can easily switch between running sequentially and running in parallel.

7、Collectors

The Collectors class implements many reduction operations, such as converting streams into collections and aggregating elements. Collectors can be used to return lists or strings:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

8. Statistics

In addition, some collectors that produce statistical results are also very useful. They are mainly used on basic types such as int, double, long, etc., and they can be used to generate statistical results similar to the following.

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
 
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
 
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());

References

Guess you like

Origin blog.csdn.net/Shipley_Leo/article/details/131022164