按多个属性对对象列表进行排序

问题描述 投票:0回答:1

我有一个 Java 对象列表,我想根据多个字段对其进行排序。

public class account {
    Long id;
    Long parentId;
}

我想拥有第一名的物品,其中catalogId为空。剩下的我需要按parentId 和id 排序,这意味着。另一个对象的parentId == id 的对象必须位于此项之后。有什么办法可以通过 lambda 函数来做到这一点吗? 响应示例

[
{id: 1, parentId: null},
{id: 2, parentId: null}
{id: 4, parentId: 1},
{id: 3, parentId: 4},
{id: 5, parentId: 3}
]
java sorting
1个回答
0
投票

使用树排序的示例:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Account> accounts = Arrays.asList(
                new Account(1L, null),
                new Account(4L, 1L),
                new Account(3L, 4L),
                new Account(2L, null),
                new Account(5L, 3L)
        );

        AccountTree accountTree = new AccountTree();

        // Add accounts to the tree
        for (Account account : accounts) {
            accountTree.addAccount(account);
        }

        System.out.println(accountTree.getSortedAccounts());
    }
}

class AccountTree {
    private Map<Long, List<Account>> accountMap = new HashMap<>();

    public void addAccount(Account account) {
        accountMap.computeIfAbsent(account.getParentId(), k -> new ArrayList<>()).add(account);
    }

    public List<Account> getSortedAccounts() {
        List<Account> result = new ArrayList<>();
        Queue<Long> queue = new LinkedList<>();

        // Start with the root accounts (parentId == null)
        queue.add(null); // Start from root (null parentId)

        while (!queue.isEmpty()) {
            Long parentId = queue.poll();
            List<Account> children = accountMap.get(parentId);

            if (children != null) {
                for (Account account : children) {
                    result.add(account); // Add the current account to result
                    queue.add(account.getId()); // Enqueue the children
                }
            }
        }

        return result;
    }
}

class Account{
    Long id;
    Long parentId;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public Account(Long id, Long parentId) {
        this.id = id;
        this.parentId = parentId;
    }



    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", parentId=" + parentId +
                '}';
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.