list转map
public static void list2map(){
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setName("Jack");
user1.setMoney(100);
User user2 = new User();
user2.setName("Pony");
user2.setMoney(98);
userList.add(user1);
userList.add(user2);
Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getName, Function.identity()));
System.out.println(map.toString());
}
求和
public static void sumList(){
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setName("Jack");
user1.setMoney(100);
User user2 = new User();
user2.setName("Pony");
user2.setMoney(98);
userList.add(user1);
userList.add(user2);
int count = userList.stream().map( user -> user.getMoney()).reduce(Integer::sum).get();
System.out.println(count);
}
public class User {
public String name;
public int money;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}
}