Java8 extracts an attribute operation of T in the Listless thanTgreater than collection using a stream

  • 2021-08-12 02:47:40
  • OfStack

In java development, we often encounter the need to extract a certain attribute of the elements in a collection from a collection. Before java8, we usually use for loop to get it, but after java8, we have a new method, that is stream.

Don't say much, just go to the code


import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author lanfangyi
 * @version 1.0
 * @since 2019/5/12 13:22
 */
@Data
@AllArgsConstructor
public class User {
  private Long id;
  private String name;
}
class TestMainService {
  public static void main(String[] args) {
    List<User> userList = new ArrayList<>();
    User user = new User(1L, "zhangsan");
    User user1 = new User(2L, "lisi");
    userList.add(user);
    userList.add(user1);
    List<Long> userIds = new ArrayList<>();
    // No. 1 1 A kind of way 
    userList.forEach(user2 -> {
      userIds.add(user2.getId());
      // You can do more here 
    });
    System.out.println(userIds);
    // No. 1 2 A kind of way 
    List<Long> userIds2 = userList.stream().map(User::getId).collect(Collectors.toList());
    System.out.println(userIds2);
  }
}

Print results:


[1, 2]
[1, 2]

Addition: Java finds an object from a collection that is equal to a class attribute based on its value

Method

Use CollectionUtils and BeanPropertyValueEqualsPredicate provided by common-utils package

For example, find a user whose id attribute value is 9587


Object obj = CollectionUtils.find(UserList.get(), 
new BeanPropertyValueEqualsPredicate("id", "9587"));
if(obj == null){
  log.info("not found");
}else{
  //do your thing
}

Approach to the Implementation of find Method


public static <T> T findElementByPropertyValue(List<T> list, String propertyName, Object value) throws Exception {
  if(list == null || list.isEmpty()) {
    return null;
  }
  PropertyDescriptor pd = new PropertyDescriptor(propertyName, list.get(0).getClass());
  for (T t : list) {
    Object obj = pd.getReadMethod().invoke(t);
    if(StringUtils.equals(String.valueOf(value), String.valueOf(obj))) {
      return t;
    }
  }
  return null;
}

Related articles: