繁体   English   中英

基于另一个 ArrayList 创建一个 ArrayList

[英]Create an ArrayList based on another ArrayList

我做了一些搜索,到目前为止找不到答案。 我正在尝试根据用户输入过滤现有的 ArrayList,用户输入有关事件和日期的详细信息,我想过滤与提供的日期匹配的所有项目的现有列表。

//code where I ask for the date
System.out.println("Enter Event Date and Time: eg. DD/MM/YYYY 6pm");
            String userEventDate = inFromUser.readLine();
//etc...

然后在代码的其他地方我们这样做

ArrayList<String> allEvents = new ArrayList<String>(); //List of all Events
                //Populate the list with some sample events
                allEvents.add("02/12/2021 1pm, Lunch w/ mother, City1.");
                allEvents.add("02/12/2021 5pm, Dinner w/ girlfriend, Pub1.");
                allEvents.add("02/12/2021 9pm, Drinks w/ wife, Pub2.");
                allEvents.add("25/12/2021 5pm, Visit Family, Cousin's House.");
                String userEvent = new String(receivePacket.getData());
                allEvents.add(userEvent);

如果用户在 ArrayList 中输入了一个日期,例如。 02/12/2021,程序应在同一天重复输入的事件和所有其他事件。 我有这个字符串,它可以从用户输入中提取日期,但从那里我很挣扎。

//This is used as a few strings are concatenated elsewhere
String extractDate = new String(userEvent.substring(0, 10));

//ArrayList to be populated with events from inputted date:
ArrayList<String> filtered = new ArrayList<String>();

我创建了一个新的过滤 ArrayList,但我正在努力寻找一种方法来根据用户的输入过滤原始列表,然后从那里添加到 ArrayLis。 上面使用的一些代码是相关的,因为这是简单的 UDP 客户端 + 服务器设置的一部分。

任何帮助或指导将不胜感激。

编辑:我应该添加一些我尝试过的更好或更坏的东西:)

//Previous attempt to loop through the arraylist:
     for (int i = 0; i < allEvents.size(); i++){
         if (allEvents.get(i).contains(extractDate) == true){
                filtered.add(i, null); //I thought I was doing great until this line, not sure if this technique is even possible.


           }
}

          


//I started going down this route but again I think it's most likely just not sensical. 
if(allEvents.contains(extractDate))
     filtered.add

使用流并根据输入对其进行过滤

// given 
List<String> allEvents = new ArrayList<>(); 
// add data

System.out.println("Enter Event Date and Time: eg. DD/MM/YYYY 6pm");
String userEventDate = inFromUser.readLine(); // e.g. '02/12/2021'

List<String> filtered = allEvents.stream()
  .filter(s -> s.startsWith(userEventDate))
  .collect(Collectors.toList());

您可以遍历现有列表并仅复制与您的条件匹配的元素。

for(String s : allEvents) {
    if(s.contains(extractDate)) {
        filtered.add(s);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM