Search code examples
javacollectionscomparisonjava-6

Get All object from a list <object> which id contains in List<long>


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


Solution

  • 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.