I did some searching and couldn't find the answer to this so far. I'm trying to filter an existing ArrayList based on user input, the user enters details about an event and a date, I want to filter an existing list for all items that match the date provided.
//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...
Then elsewhere in the code we do this
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);
If a user inputs a date already in the ArrayList, eg. 02/12/2021, the program should repeat back the inputted event and all other events on that same day. I have this String which can extract the date from the user input but from there I am struggling.
//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>();
I have a new filtered ArrayList created but I'm struggling to find a way to filter the original one based on the user's input and then add to the ArrayLis from there. Some of the code used above is relevant as this is part of a simple UDP client server setup.
Any help or guidance would be much appreciated.
EDIT: I should add some things I have tried for better or worse :)
//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
CodePudding user response:
Use a stream and filter it based on the input
// 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());
CodePudding user response:
You could loop through your existing list and copy only the elements matching your condition.
for(String s : allEvents) {
if(s.contains(extractDate)) {
filtered.add(s);
}
}