Reputation: 2716
I have a java object that has the following fields -
public class Fruit {
private String name;
private String type;
private String color;
private String category;
private String description;
}
Now I have a set of fruits sold by vendor A, and vendor B. Both are hashsets.
Set<Fruit> vendorA = new HashSet<Fruit>();
Set<Fruit> vendorB = new HashSet<Fruit>();
I want to check in vendor A's fruits if it has a specific type of that of vendor B. In the fruit class, I've overridden hashcode and equals by the type field. I know how to use the contains method on a set. That's not my question. But if that type is present in vendor B, I need to get the fruit object of vendor B. How can I achieve this? The below part here is a pseudo code of my question -
for(Fruit fruits : fruit) {
String type = fruits.getType();
if(vendorB.contains(type)) {
//get me the vendor B fruit object of that type
}
}
Upvotes: 2
Views: 628
Reputation: 340178
Following your approach, nest another loop.
for( Fruit fruitA : vendorA ) {
String typeA = fruitA.getType() ; // Use singular, not your plural.
for( Fruit fruitB : vendorB ) {
if( fruitB.getType().equals( typeA ) { … } // We have a hit.
}
}
A better way might be to implement a Comparator
. Redefining equals
as solely examining your type
member is not wise if your real business scenario semantics are similar to your example here.
Upvotes: 3
Reputation: 347
You should reverse the problem.
You want the intersection of A and B but fruits of B then
You loop on vendorB
and check if each fruit is in A.
List<Fruit> fruits = vendorB.stream().filter(x->vendorA.contains(x)).collect(Collectors.toList());
You will have some problem if you use Set, because Set can have one instance of each type because you defined equals and the hashcode to this single type. Which is useful for your feature but sementically wrong. So you should find something.
that's why I used a List.
Upvotes: 2
Reputation: 3430
I would suggest using a nested loop:
for(Fruit fruit1 : fruit) {
String type = fruit1.getType();
for(Fruit fruit2 : vendorB){
if(fruit2.getType().equals(type)) return fruit2;
}
}
//return null?
Upvotes: 0