forEach遍历list集合、map集合


import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* Create by ${邢磊} on 2022/1/11
*/
public class ForEach {
  public static void main(String[] args) {
    list.forEach(obj -> {
      System.out.println(obj);
    });

    Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getAddress));
    collect.forEach((key, value) -> {
      System.out.println("循环map集合" + key);
      for (User user : value) {
        System.out.println(user);
      }
    });
  }

  /**
  * 数据初始化
  */
  private static List<User> list = new ArrayList<>();

  static {
    list = Arrays.asList(
    new User("李星云", null, 0, "渝州", new BigDecimal(1000)),
    new User("陆林轩", 16, 1, "渝州", new BigDecimal(500)),
    new User("姬如雪", 17, 1, "幻音坊", new BigDecimal(800)),
    new User("袁天罡", 99, 0, "藏兵谷", new BigDecimal(100000)),
    new User("张子凡", 0, 0, "天师府", new BigDecimal(900)),
    new User("陆佑劫", 45, 0, "不良人", new BigDecimal(600)),
    new User("张天师", 48, 0, "天师府", new BigDecimal(1100)),
    new User("张天师", 48, 0, "天师府", new BigDecimal(1100)),
    new User("张天师", 48, 0, "天师府", new BigDecimal(1100)),
    new User("蚩梦", 18, 1, "万毒窟", new BigDecimal(800))
    );
  }
}


@Data
class User {
  //姓名
  private String name;
  //年龄
  private Integer age;
  //性别
  private Integer sex;
  //地址
  private String address;
  //赏金
  private BigDecimal money;

  public User(String name, Integer age, Integer sex, String address, BigDecimal money) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.address = address;
    this.money = money;
  }

  @Override
  public String toString() {
    return "User{" +
    "name='" + name + '\'' +
    ", age=" + age +
    ", sex=" + sex +
    ", money=" + money +
    ", address='" + address + '\'' +
    '}';
  }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM