你如何 return 在 Jersey + Java 来自特定索引的数组列表

How do you return in Jersey + Java an arraylist from a specific index

现在是凌晨 3 点,我正在努力解决这个问题。

我的最终目标是获取发生的交易列表。

我得到:

       /*
   This GET method returns in a JSON format all transaction history of given customer id
   */
   @GET
   @Produces(MediaType.APPLICATION_JSON)
   @Path("/history/{cId}")
   public Object history(@PathParam("cId") int customerId){
         return accountsService.getAllTransfersFromAccount(customerId);
   }

getAllTransfersFromAccount :

    /*
Gets the list of transactions of given customer 
*/
public Object getAllTransfersFromAccount(int cId) {
    for(Transactions history : transactionsHistory) {
        if(history.getTransactions() == cId) {
            return history;
        }
    }
    return null;
}

我的交易class

    public class Transactions {
    /**
     *  TRANS TYPE
     * 0 - Deposit
     * 1 - Withdrawal
     * 2 - Transfer
     * 3 - Transfer Receive
     */
    public int cId, amount, transType;
    public Transactions(int transType, int cId, int amount){
        this.transType = transType;
        this.cId = cId;
        this.amount = amount;
    }

    public int getTransactions(){
        return cId;
    }
}

打印与给定 cId 相关的所有交易的最佳方式是什么?如果我执行 for 循环,它会打印所有交易,只需要 return 某个交易。 抱歉问题格式不好,凌晨 3 点写作不是我的事。

What is the best way to print all transactions related to given cId?

您要找的是 ArrayList。您需要创建一个新的 ArrayList of Transactions 并继续将您想要的所有内容添加到该列表中。

您最终可以 return 此列表包含与给定 cID 相关的交易。

代码段:

public List<Transactions> getAllTransfersFromAccount(final int cId) {
    /* Create List */
    List<Transactions> transactionsList = new ArrayList<>();
    for(Transactions history : transactionsHistory) {
        if(history.getTransactions() == cId) {
            /* Add Items */
            transactionsList.add(history);
        }
    }
    /* Return List */
    return transactionsList;
}

编辑: 谢谢,@nullpointer。在 Java 8 中你可以简单地做:

public List<Transactions> getAllTransfersFromAccount(final int cId) {
    return transactionHistory.stream().filter(t -> t.getTransactions() == cId).collect(Collectors.toList());
}