1. 程式人生 > 其它 >forEach遍歷list集合、map集合

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 + '\'' +
    '}';
  }
}