如何用Java8按Group的最高discount对Response列表升序排序?
Solution: Sorting Response List by Highest Group Discount
Absolutely! Java 8's streams and comparator APIs make this task straightforward. Here's how you can sort your List<Response> based on the highest discount value from each Response's groupList:
Step-by-Step Breakdown
- Safely Handle Null/Empty Groups: Use
Optional.ofNullable()to avoidNullPointerExceptionifgroupListis null, replacing it with an empty list. - Extract Valid Discounts: Stream through the groups, pull out their
discountvalues, and filter out any nulls to prevent errors. - Find Maximum Discount: Convert the valid discounts to integers, then use
max()to get the highest value (returns anOptionalIntto handle empty cases). - Set a Default for Missing Discounts: Use
orElse()to define a fallback value if there are no valid discounts (like 0, or adjust to control where these responses appear in the sorted list). - Sort the List: Pass this logic into
Comparator.comparingInt()to create a sorting rule, then apply it to yourresponseList.
Complete Code Example
import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Optional; // Your existing class definitions class Response { List<Group> groupList; Integer sequenceNo; // Required getter for stream operations public List<Group> getGroupList() { return groupList; } } class Group { Integer discount; List<String> rates; // Required getter for stream operations public Integer getDiscount() { return discount; } } // Sorting implementation public class ResponseSorter { public static void sortByMaxDiscount(List<Response> responseList) { responseList.sort(Comparator.comparingInt(response -> Optional.ofNullable(response.getGroupList()) .orElse(Collections.emptyList()) .stream() .map(Group::getDiscount) .filter(Objects::nonNull) .mapToInt(Integer::intValue) .max() .orElse(0) // Adjust default value as needed )); } }
Additional Tips
- Reverse the Order: To sort in descending order (highest discount first), append
.reversed()to the comparator:responseList.sort(Comparator.comparingInt(...).reversed()); - Adjust Default Behavior: If you want responses with no valid discounts to appear at the end of the sorted list, use
Integer.MAX_VALUEas the default. For the start, useInteger.MIN_VALUE. - Getter Methods: Make sure your
ResponseandGroupclasses have proper getters—stream operations depend on accessing these values.
内容的提问来源于stack exchange,提问作者Amit
相关产品推荐
相关产品推荐

