如何基于两个数组计算的总票价对RecyclerView数据排序
Ah, I see the core issue here — right now you’re only sorting the departList, but your arriveList stays in its original order. This means after sorting, the position of items in departList no longer matches their corresponding pairs in arriveList, leading to incorrect total fare calculations for most entries.
The solution is to bundle your depart and return journey data into a single combined class, so you can sort the list of these paired objects while keeping each depart-arrive pair linked. Here's a complete implementation:
Step 1: Create a Combined Pair Class
First, make a simple class to hold each depart-arrive journey pair, and add a method to calculate the total fare safely (handling nulls to avoid crashes):
public class JourneyPair { private LstJourneyOneWay departJourney; private LstJourneyReturn arriveJourney; public JourneyPair(LstJourneyOneWay depart, LstJourneyReturn arrive) { this.departJourney = depart; this.arriveJourney = arrive; } // Getters public LstJourneyOneWay getDepartJourney() { return departJourney; } public LstJourneyReturn getArriveJourney() { return arriveJourney; } // Safely calculate total fare (handles empty lists/null fares) public float getTotalFare() { // Calculate depart fare float departFare = 0f; if (departJourney.getLstItinerary() != null && !departJourney.getLstItinerary().isEmpty()) { LstItinerary departItin = departJourney.getLstItinerary().get(0); departFare = departItin.getCustomerFare() != null ? departItin.getCustomerFare() : 0f; } // Calculate return fare float arriveFare = 0f; if (arriveJourney.getLstItinerary() != null && !arriveJourney.getLstItinerary().isEmpty()) { LstItinerary arriveItin = arriveJourney.getLstItinerary().get(0); arriveFare = arriveItin.getCustomerFare() != null ? arriveItin.getCustomerFare() : 0f; } return departFare + arriveFare; } }
Step 2: Update Your Adapter's Data Source
Replace your two separate lists with a single list of JourneyPair objects, and adjust the adapter to use this paired data:
// Inside your Adapter class private List<JourneyPair> journeyPairList; // Update constructor to accept the paired list public YourAdapter(List<JourneyPair> journeyPairList) { this.journeyPairList = journeyPairList; } // Modify onBindViewHolder to use the paired data @Override public void onBindViewHolder(@NonNull MyViewAdapter.ViewHolder holder, int position) { JourneyPair currentPair = journeyPairList.get(position); // You can still access individual depart/return data if needed LstJourneyOneWay departJourney = currentPair.getDepartJourney(); LstJourneyReturn arriveJourney = currentPair.getArriveJourney(); // Use the safe total fare calculation from the JourneyPair class float totalFare = currentPair.getTotalFare(); holder.txt_TotalFare.setText("₹ " + totalFare); }
Step 3: Implement the Total Fare Sort
Now you can sort the entire list of JourneyPair objects based on their total fare, keeping each pair intact:
// Inside your Adapter class public void sortByTotalFare(boolean isAscending) { Collections.sort(journeyPairList, new Comparator<JourneyPair>() { @Override public int compare(JourneyPair pair1, JourneyPair pair2) { float totalFare1 = pair1.getTotalFare(); float totalFare2 = pair2.getTotalFare(); // Use Float.compare() for safe floating-point comparison (avoids precision issues) if (isAscending) { return Float.compare(totalFare1, totalFare2); } else { return Float.compare(totalFare2, totalFare1); } } }); notifyDataSetChanged(); Log.d("suraj", isAscending ? "Sorted ascending by total fare" : "Sorted descending by total fare"); }
Step 4: Prepare the Paired List Before Setting the Adapter
When initializing your adapter, combine your original lists into JourneyPair objects (make sure both lists are the same length first!):
// In your Activity/Fragment List<JourneyPair> pairedJourneys = new ArrayList<>(); for (int i = 0; i < departList.size(); i++) { pairedJourneys.add(new JourneyPair(departList.get(i), arriveList.get(i))); } // Set up the adapter with the paired list YourAdapter adapter = new YourAdapter(pairedJourneys); recyclerView.setAdapter(adapter);
Key Notes:
- Avoids Position Mismatch: By pairing the data, you ensure depart and return journeys stay linked after sorting.
- Null Safety: The
getTotalFare()method handles empty itineraries and null fare values to preventNullPointerException. - Floating-Point Safety: Using
Float.compare()instead of direct>/<comparisons avoids issues with floating-point precision.
内容的提问来源于stack exchange,提问作者suraj

