Search code examples
javalistloopsset-difference

List substraction with indices


Let's say I have a List A like that:

line value
0    Object0
1    Object1
2    Object2
3    Object3
4    Object4
5    Object5

Now, I've another List B containing [0,2,3] (only Integer) which basically contains the indices of objects I've already looked at.

I'd like to get the List C (it's the indices [0,1,2,3,4,5]-[0,2,3]=[1,4,5]):

line value
1    Object1
4    Object4
5    Object5

Btw : I need the original list to stay the same.

I could create the list of indices and then remove the B list to get the C list but is there an easy and efficient way to get directly the object?


Solution

  • EDIT : (because I forget that you want the original list not changed) :
    So a ONE-LINE operation is usefull :

    //I recreate your scenario to test
    List<Object> list = new ArrayList<>();
    list.add("Object0"); list.add("Object1"); list.add("Object2");
    list.add("Object3"); list.add("Object4"); list.add("Object5");
    List<Integer> indexesToAvoid = Arrays.asList(0, 2, 3);
    

    The principe is this : iterate over your objects, and keep the ones which index not appears into indexesToAvoid, and then collect them into a new List :

    List<Object> resultList = list.stream()
            .filter(obj -> !indexesToAvoid .contains(list.indexOf(obj)))
            .collect(Collectors.toList());