-5

How can i get List<Object> filteredList whose id (Object.id) contains in a given List<id> idsList from another List<Object>allObjects. what will be the effective and efficient way in terms of time to solve this considering a moderate data volume.

I am using java6

Krishna Kant
  • 105
  • 9

1 Answers1

6

I don't want to iterate both the list so many times

Why? Premature optimisation is a bad thing. Test it first, measure whether it is efficient enough, and address the problem if it exists.

You can accomplish this with streams using a simple filter:

class Student
{
    long id;
}

final List<Student> students = /*something*/;
final List<Long> rollNoList = /*something*/;

List<Student> newStudents = students.stream()
                                    .filter(student -> rollNoList.contains(student.id))
                                    .collect(Collectors.toList());

The advantage of doing it with streams is that you may be able to parallelise it later.


An additional optimisation would be to examine your use of data structures. As Seelenvirtuose points out, using something like a HashSet will reduce the complexity of contains from O(n) to O(1):

final Set<Long> rollNoList = new HashSet<>();

If you can't do this, you may also see some performance gain, at the cost of increased memory usage, by copying the List into a HashSet before filtering:

final Set<Long> rollNumbers = new HashSet<>(rollNoList);

but if you have control over the data structure, just use HashSet from the beginning.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • 1
    In fact, it makes more sense to convert the `List` to a `Set` first. This way the call to `ids.contains` will be O(1) and not O(n) in costs. Not doing that is obviously more inefficient. – Seelenvirtuose Jul 14 '17 at 14:14
  • This is gonna be funny when he turns in this assignment using this code and he tries to explain what it's doing. – Rabbit Guy Jul 14 '17 at 14:17
  • 1
    @rabbitguy I'm generally against suggesting stream-based answers to beginners, but I'd hope it's pretty obvious what this is doing. – Michael Jul 14 '17 at 14:18
  • @Michael Yeah, well, I have a feeling that turning in this code will clue the professor into the fact that he didn't do the work himself – Rabbit Guy Jul 14 '17 at 14:20
  • @rabbitguy Then that's his problem. My answers on this website are not meant to be blindly copied and pasted anywhere. They are intended to aid people's understanding. – Michael Jul 14 '17 at 14:23
  • @Seelenvirtuose Good optimisation. I'll edit it in. – Michael Jul 14 '17 at 14:25