如何在Jersey + Java中返回特定索引的数组列表

时间:2018-12-19 01:04:05

标签: java arraylist jersey

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

我的最终目标是获取发生的交易清单。

我的GET:

       /*
   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;
}

我的交易类

    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循环,它将打印所有事务,只想返回某些事务。 很抱歉遇到一个格式错误的问题,我凌晨3点不是我的事。

1 个答案:

答案 0 :(得分:2)

  

打印与给定cId相关的所有交易的最佳方法是什么?

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

然后您可以最终返回此列表,以获取与给定的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());
}