You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将存储自定义User对象的List按日期拆分为两个子列表?

Split User List by Day (Monday/Tuesday)

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 true maps to all users with day "Monday"
    • The key false maps to all users with day "Tuesday" (and any other days, though your sample only includes these two)
  • We extract the two sublists directly from the map using get(true) and get(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:05:04