代码之家  ›  专栏  ›  技术社区  ›  Erent

更改列表中的项目,然后排序列表

  •  0
  • Erent  · 技术社区  · 7 年前

    我想访问对象列表并更改列表中的一些值。之后,我想根据日期对列表进行排序。有可能做到这一点吗?我该怎么做?

    这是我的代码:

    public class AccountTransactions {
        private int transactionID;
        private int transactionCode;
        private String transactionDate;
        private String transactionType;
        private String transactionTime;
        private String transactionAmount;
        private String transactionTo;
        private String transactionFrom;
    
        ... // for bravety
    
    }
    

    Transactions.java :

      public  ListtransactionsObjects getUserTransactions(SearchbyPublicKeyObject publicKeyObject){
    
            List<AccountTransactions> transactionFrom =  TransactionsRepository.findByTransactionFrom(publicKeyObject.getPublicKey());
            List<AccountTransactions> transactionTo = TransactionsRepository.findByTransactionTo(publicKeyObject.getPublicKey());
    
    
    
      //sudo code
      // loop through list 
      // transactionTo.transactionAmount = "+" + transactionAmount
    
    
    
            List<AccountTransactions> AllTransactions = Stream.concat(transactionFrom.stream(), transactionTo.stream())
                                 .collect(Collectors.toList());
        }
    
    
    
     // sort AllTransactions by transactionDate which is of type 05/06/2018
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Suvansh    7 年前

    遍历循环中的对象并设置值。然后使用比较器。

    Collections.sort(list, new Comparator<AccountTransactions>() {
    
            @Override
            public int compare(AccountTransactions o1, AccountTransactions o2) {
    
              return o1.getTransactionDate().compareTo(o2.getTransactionDate());
            }  
        });
    

    将transactionDate设置为日期类型。

        2
  •  2
  •   Shanu Gupta    7 年前

    使用 Collections.sort

    // sort AllTransactions by transactionDate which is of type 05/06/2018
    Collections.sort(AllTransactions, AccountTransactions::getTransactionDate);
    

    假设你应该 getTransactionDate 在里面 AccountTransactions 返回您的交易 date (不是 string 您拥有的)。 您可能需要转换 一串 date.