如何将存储自定义User对象的List按日期拆分为两个子列表?
Got it, let's solve this problem of splitting your userList into two groups based on the day value. Here are two practical approaches in Java:
1. Using Java Streams (Concise & Modern)
Java 8+ streams make this task clean and readable with Collectors.partitioningBy(), which divides the list into two groups based on a boolean condition.
import java.util.List; import java.util.Map; import java.util.stream.Collectors; // First, ensure your User class has a getDay() method to access the day field Map<Boolean, List<User>> partitionedUsers = userList.stream() .collect(Collectors.partitioningBy(user -> user.getDay().equals("Monday"))); List<User> mondayUsers = partitionedUsers.get(true); List<User> tuesdayUsers = partitionedUsers.get(false);
Breakdown:
partitioningBy(user -> user.getDay().equals("Monday"))creates a map where:- The key
truemaps to all users with day "Monday" - The key
falsemaps to all users with day "Tuesday" (and any other days, though your sample only includes these two)
- The key
- We extract the two sublists directly from the map using
get(true)andget(false)
2. Iterative Approach (Beginner-Friendly & Explicit)
If you prefer a more straightforward loop-based method, you can manually sort users into separate lists:
List<User> mondayUsers = new ArrayList<>(); List<User> tuesdayUsers = new ArrayList<>(); for (User user : userList) { String day = user.getDay(); if ("Monday".equals(day)) { mondayUsers.add(user); } else if ("Tuesday".equals(day)) { tuesdayUsers.add(user); } // Add an else clause here if you need to handle users with other days }
Important Note:
Make sure your User class includes a getter method for the day field (e.g., public String getDay() { return day; })—this is required to access the day value in both solutions. Both methods will correctly preserve duplicate entries from your original list.
内容的提问来源于stack exchange,提问作者user8212013

