r/javahelp • • Sep 19 '20

Remove a List of items from a List?

Let's say you have

OrderA { int id; ..... }

OrderB { int id; ..... }

(orderA & orderB are different types)

List<OrderA> ordersA... List<OrderB> ordersB...

Is it possible to take out ordersB from ordersA where the id's match in an elegant way with streams? Something like:

ordersA.stream().filter(...some magic...).collect(...

16 Upvotes

12 comments sorted by

7

u/SpoilerAlertsAhead Extreme Brewer:hamster: Sep 19 '20

Look at Collections removeAll.

1

u/stamangu Sep 19 '20

That works only if items are same type and the compareTo method is overridden to only check for "id"

6

u/evils_twin Sep 19 '20 edited Sep 20 '20
interface Order{ public int getId();}
class OrderA implements Order { int id; ..... }
class OrderB implements Order { int id; ..... }

1

u/stamangu Sep 20 '20

Perhaps subclassing would be more appropriated in this case i think.

public class Order {
	
	private int id;
	public Order(int id){
		this.id = id;
	}

	public int getId() {
		return id;
	}
	public String toString(){
		return ""+id;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Order other = (Order) obj;
		if (id != other.id)
			return false;
		return true;
	}
}

public class OrderA extends Order {
	
	public OrderA(int id) {
		super(id);
	}
	
}


public class OrderB extends Order {

	public OrderB(int id) {
		super(id);
	}

}

public class TestOrder {

	public static void main(String[] args) {
		
		List<Order> ordersA = new ArrayList<>();
		ordersA.add(new OrderA(1));
		ordersA.add(new OrderA(2));
		ordersA.add(new OrderA(3));
		ordersA.add(new OrderA(4));
		
		List<Order> ordersB = new ArrayList<>();
		ordersB.add(new OrderB(2));
		ordersB.add(new OrderB(3));
		
		System.out.println("Orders A: " + ordersA);
		System.out.println("Orders B: " + ordersB);
		
		ordersA.removeAll(ordersB);
		
		System.out.println("Orders A: " + ordersA);
		
		System.out.println((new OrderA(1)).getClass());
		System.out.println((new OrderB(1)).getClass());
	}

}

>>>
Orders A: [1, 2, 3, 4]
Orders B: [2, 3]
Orders A: [1, 4]
class OrderA
class OrderB

2

u/evils_twin Sep 20 '20

Yes, or an abstract class. depends on what he is doing. I just wanted to point out that they could be of the same type if they implemented or extended the same class.

I used an interface because I assumed all class names and variable names were simplified in the description and that the field they want to compare might not actually be the same name. With an interface, they could just have the getId() return whatever variable they want from OrderA and OrderB even if they don't have the same name. You actually don't need the setId function, so I took it out. The interface also doesn't require as much changes to the implementing class. This way you can possibly reuse this interface for similar situations by just implementing the interface and adding a getId() implementation.

But it really does depend on what you're trying to accomplish.

7

u/Roachmeister Java Dev Sep 19 '20

I think that since they are different types you can't really do it with streams, at least not in one pass. However, you could first build a Set of all IDs in ordersB:

List<String> ids = ordersB.stream()
    .map(OrderB::getId)
    .collect(Collectors.toSet());

And then you can filter ordersA by that set:

List<OrderA> filtered = ordersA.stream()
    .filter(o -> !ids.contains(o.getId()))
    .collect(Collectors.toList());

3

u/stamangu Sep 20 '20

This is what i was looking for, thank you, and thanx to u/solonovamax and u/Yithar
Was trying to find a oneliner, but this is clean and fast readable.

Thank you!

1

u/solonovamax Sep 21 '20

No problem. In reality, the solution I proposed is a clean one-liner because the IDE will spaces things out and make it nice to read.

Streams are very powerful (and fun to use!), so I'd really recommend you learn them at some point. Need to loop through a list to perform some operation? Use a stream, and slowly learn the API.

(Also, my original comment was incorrect about the time complexity and I've updated it to be correct.)

2

u/solonovamax Sep 19 '20 edited Sep 21 '20

An alternative would be using

List<OrderA> filtered = ordersA.stream().filter( o -> {
ordersB.stream().anyMatch(o2 -> o.getId().equals(o2.getId()))
});

But then it'd be O(n2 ) instead of O(n), because you're looping through ordersB for every time of ordersA. Edit: actually I'm brain dead and both are O(n2 ) because worst case is O(n*m) where n=m, so O(n2 ). It's just that my version is doing an extra operation per loop, but they're still both looping twice, so the time complexity is the same.

(Code might be wrong; I'm on mobile. Also, mobile formatting do be kinda shit.)

1

u/klata Sep 19 '20

Can’t you have one list with both of them?

1

u/stamangu Sep 20 '20

No, ordersA is my managed list of items while ordersB comes from an external system that do certain operations on the item i have tracked on my list ordersA.
One operation is to delete the items in ordersA that comes from the external system ordersB.

2

u/Yithar Intermediate Brewer Sep 19 '20

I would convert OrderB to a HashSet, only because otherwise filter() will have to iterate over the whole OrderB list for every OrderA element which is inefficient. So assuming we now have a HashSet<Integer>, we can do the folllowing:

ordersA.stream().filter(x -> !hashSet.contains(x.id)).collect(Collectors.toList())

Keep in mind things like filter() create a new Stream so it requires extra memory.