Explanation:
In this blog post, we'll explore how to use Java 8's Stream API and Comparator
to sort a list of Transaction
objects first by their date
attribute and then by their id
attribute in case of a date tie
Sample Code:
javapublic class MultipleComparatorTest { private int id; private String txnType; private String date; public MultipleComparatorTest(int id, String txnType, String date) { this.id = id; this.txnType = txnType; this.date = date; } public int getId() { return id; } public String getDate() { return date; } @Override public String toString() { return "MultipleComparatorTest [id=" + id + ", txnType=" + txnType + ", date=" + date + "]"; } public static void main(String[] args) { List<MultipleComparatorTest> transactions = createTransactionList(); // Create your list of Transaction objects Comparator<MultipleComparatorTest> byDateThenId = Comparator .comparing(MultipleComparatorTest::getDate, (date1, date2) -> date2.compareTo(date1)) .thenComparing(MultipleComparatorTest::getId); List<MultipleComparatorTest> sortedTransactions = transactions.stream() .sorted(byDateThenId) .collect(Collectors.toList()); // Now, sortedTransactions contains the sorted list of Transaction objects sortedTransactions.forEach(System.out::println); } // Utility method to create a list of Transaction objects private static List<MultipleComparatorTest> createTransactionList() { // Add your Transaction objects to this list // For example: List<MultipleComparatorTest> transactions = Arrays.asList( new MultipleComparatorTest(1, "Type1", "2023-10-19"), new MultipleComparatorTest(3, "Type3", "2023-10-18"), new MultipleComparatorTest(2, "Type2", "2023-10-18") // Add more transactions ); return transactions; } }
Sample Output:
outputMultipleComparatorTest [id=1, txnType=Type1, date=2023-10-19]MultipleComparatorTest [id=2, txnType=Type2, date=2023-10-18]MultipleComparatorTest [id=3, txnType=Type3, date=2023-10-18]
Comments
Post a Comment