1

I am working on an android project in java. I have an array of objects that looks like this

Agenda = [{id: 1, sessionName: Some name, sessionLocation: Some place},
         {id: 2, sessionName: Some name, sessionLocation: Some place},
         {id: 3, sessionName: Some name, sessionLocation: Some place}]

I also have an array of strings that is dynamic, so it can have several values... looks like this:

sessionID = {1, 3}

How can I check for these sessionIDs within the "id" field in the Agenda array and pull only these objects where the ids match into a new array.

Note:

  • This is java not javascript
  • "id" in the Agenda array objects is an int
  • sessionID array is an array of string

I tried several examples but none of them worked!

2
  • filter is your friend - take a look at stackoverflow.com/questions/47787247/… Commented Jun 7, 2019 at 7:58
  • Hi @user2637293, can you give me a update to see if this solves. Commented Jun 14, 2019 at 14:39

1 Answer 1

1

[UPDATED] Example for Arraylist:

If you are using Java 8, consider the following setup:

List<Agenda> agenda = new ArrayList<Agenda>();
agenda.add(new Agenda(1));
agenda.add(new Agenda(2));
agenda.add(new Agenda(3));

String[] sessionID = new String[] {"1", "3"};

You can do:

List<Agenda> agendaFiltered = agenda.stream()
        .filter(agendaObj -> Arrays.binarySearch(sessionID, Integer.toString(agendaObj.getId())) >= 0)
        .collect(Collectors.toList());

Then if you run:

agendaFiltered.forEach(System.out::println);

It will print only:

Agenda{id=1}
Agenda{id=3}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the comment! My Agenda is an ArrayList. Will this example still work?
updated @user11527839. As you were saying array, I did it with array. Now Agenda is a List.
hi @user11527839 can you accept it this solves the issue, thanks.
The naming is little bit confusing. .filter() runs on objects, not filters. List<Agenda> agendaFiltered = agenda.stream() .filter(agendaObj -> sessionIdsArray.contains(agendaObj.id)) .collect(Collectors.toList());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.