新建一个User对象
public class User{
private String userId;
private String name;
private String sex;
private String height;
public User(String userId,String name,String sex,String height){
this.userId = userId;
this.name = name;
this.sex = sex;
this.height = height;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", userId=").append(userId);
sb.append(", name=").append(name);
sb.append(", sex=").append(sex);
sb.append(", height=").append(height);
sb.append("]");
return sb.toString();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}
运用
public static void main(String[] args) {
List<User> list = new ArrayList<>();
User user = new User("1","张三","男","173");
list.add(user);
User user1 = new User("2","李四","男","160");
list.add(user1);
User user2 = new User("3","李薇薇","男","169");
list.add(user2);
User user3 = new User("4","李薇薇","女","165");
list.add(user3);
//筛选UserId为1的用户
List<User> filterList = list.stream().filter(o->o.getUserId().equals("1")).collect(Collectors.toList());
log.info("UserId为1的用户:{}",filterList);
//取出所有的用户Id组成一个新数组
List<String> idsList = list.stream().map(User::getUserId).collect(Collectors.toList());
log.info("用户ids:{}",idsList);
//统计名字为李薇薇的用户数量
long count = list.stream().filter(User->User.getName().equals("李薇薇")).count();
log.info("名为李薇薇的用户有:{}个",count);
//按照性别分组
Map<String,List<User>> groupMap = list.stream().collect(Collectors.groupingBy(User -> User.getSex()));
log.info("按照性别分组:{}",groupMap);
//用户Id为key,对象为value
Map<String,User> userMap = list.stream().collect(Collectors.toMap(User::getUserId,User->User));
log.info("用户Map:{}",userMap);
}