• 效果
    Java根据对象属性合并_其他
  • 代码实现
import java.util.ArrayList;
import java.util.List;

public class TestDemo {

    public static void main(String[] args) {
        User user1 = new User();
        user1.setName("Jack");
        user1.setMoney(100);

        User user2 = new User();
        user2.setName("Jack");
        user2.setMoney(100);

        User user3 = new User();
        user3.setName("Bruce");
        user3.setMoney(100);


        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        System.out.println("合并前:" + userList.toString());

        List<User> mergeUserList = mergeUserList(userList);

        System.out.println("合并后:" + mergeUserList.toString());
    }

    public static List<User> mergeUserList(List<User> userList) {
        List<User> result = new ArrayList<>();
        for (User user : userList) {
            boolean add = true;
            for (User item : result) {
                if (item.getName().equals(user.getName())) {
                    item.setMoney(item.getMoney() + user.getMoney());
                    add = false;
                    break;
                }
            }
            if (add) {
                result.add(user);
            }
        }
        return result;
    }
}
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 +
                '}';
    }
}