I have two objects of two different types :
Class1 A
List<Class2> B
And we have -
Class2 C = new Class2();
B.add(C);
I want to get elements of B such as A.fieldX == C.fieldY
.
Is it possible to do so without iterating on the list ?
I have two objects of two different types :
Class1 A
List<Class2> B
And we have -
Class2 C = new Class2();
B.add(C);
I want to get elements of B such as A.fieldX == C.fieldY
.
Is it possible to do so without iterating on the list ?
It is not possible to do this in a list without some form of iteration, but if you change to a mapping you can get around that with the following code:
Map<FieldYType, Class2> B= new HashMap();
B.put(c.fieldY, C);
Class2 D = B.get(A.fieldX);
D==C;//true
D.fieldY==A.fieldX;//true
So here you dont iterate at all, you just use a single get function. You also might want to use a different map type, but thats up to you and your code design.
If the fields don't change for the objects while they're in your list, you can use a map of collections (or lists or sets, depending on what you need) to facilitate this comparison:
Map<Field, List<Class2>> map = new HashMap<>();
To insert:
Class2 c = new Class2();
List<Class2> bucket = map.get(c.fieldY);
if( null == bucket ){
bucket = new ArrayList<>();
map.put( c.fieldY, bucket );
}
bucket.add( c );
To look up:
List<Class2> result = map.get( a.fieldX );
This only works if the fields don't change while the objects are in the map of lists, and it only makes sense to do if you are making these lookups a lot.