List with object and index filtering out the object depends upon the index present at list I have a following list which indicates the indexes.

 List&lt;Integer&gt; integerList = Arrays.asList(1, 3, 5, 6); // index


I have the following collection of objects.

Collection&lt;Test&gt; testCollection = new ArrayList&lt;&gt;();

Test test01 = new Test(0, "A"); // 0
Test test02 = new Test(1, "B"); // 1
Test test03 = new Test(2, "C"); // 2
Test test04 = new Test(3, "D"); // 3
Test test05 = new Test(4, "E"); // 4
Test test06 = new Test(5, "F"); // 5

testCollection.add(test01);
testCollection.add(test02);
testCollection.add(test03);
testCollection.add(test04);
testCollection.add(test05);
testCollection.add(test06);


The integerList has indexes which are present on testCollection. I want to filter out the testCollection which will have object consisting the index 1, 3, 5. Index 6 is not present on object collection.

I wrote the code as below example. Is there any better as like Java 8 way?

List&lt;Test&gt; testList = new ArrayList&lt;&gt;(testCollection);
List&lt;Test&gt; newTestList = new ArrayList&lt;&gt;();

for (Integer integer : integerList) {

  for (int j = 0; j &lt; testList.size(); j++) {

    if (integer == j) {
      newTestList.add(testList.get(j));
    }
  }
}
System.out.println(newTestList);


It will have the following output as result:

[Test{id=1, name='B'}, Test{id=3, name='D'}, Test{id=5, name='F'}]


The class Test has following information.

class Test {
  private int id;
  private String name;
}
It seems to me that your solution is basically O(n*m),the size of the unfiltered list times the number of filter indexes.  I think you can get O(n+mlogm),the size of the unfiltered list plus sorting the filtered indexes, by using a combination of indexes and iterators and iterating through both lists at the same time.  It could look something like this:

public static List&lt;Test&gt; getFilteredList(Collection&lt;Test&gt; unfilteredList, List&lt;Integer&gt; filterIndexes) {
    if(filterIndexes == null || filterIndexes.size() == 0){
        return new ArrayList&lt;Test&gt;(unfilteredList);
    }
    Collections.sort(filterIndexes);        
    List&lt;Test&gt; newTestList = new ArrayList&lt;&gt;();
    Iterator uIterator = unfilteredList.iterator();
    Iterator fIterator = filterIndexes.iterator();
    Integer fIndex = (Integer)fIterator.next();
    for (Integer uIndex = 0;uIterator.hasNext();++uIndex) {
        Test nextTest = (Test)uIterator.next();
        if (uIndex == fIndex) {
            newTestList.add(nextTest);
            if(!fIterator.hasNext()){
               break;
            }else{
                fIndex = (Integer)fIterator.next();
                if(fIndex &gt;= unfilteredList.size()){
                    break;
                }
            }
        }
    }
    return newTestList;
}