I have a List<Pair<String, String>> into which I want to copy the data from a Collection.
What is the best way to read the collection and add items to list?
List<Pair<String, String>> identityMemoPairs = new LinkedList<Pair<String, String>>();
Collection result = handler.getResult();
while(result.iterator().hasNext()){
IdentityM im =(IdentityM) result.iterator().next();
identityMemoPairs.add(Pair.of(im.identity,im.memo));
}
Your code is wrong, because you create a new iterator at each iteration of the while loop (actually you create two of them). Each fresh iterator will point to the beginning of the
resultcollection. Thus you have created an infinite loop.To fix this, call
result.iterator()only once and store the result in a variable.But even better (better to read, less error-prone) would be the for-each loop, which is (almost always) the preferred variant to iterate over collections:
The compiler will automatically transform this into code using the iterator, so no performance difference. Generally, performance is anyway not a problem when iterating over a collection, as long as you avoid a few bad things like calling
get(i)on aLinkedList.Note that the compiler will give you a warning here, which has nothing to do with the iteration, but with the use of the raw type
Collection(instead ofCollection<IdentityM>). Please check ifhandler.getResult()actually returns aCollection<IdentityM>and change the type of theresultvariable to this if possible.Another question is whether you really need that list to be a list of pairs. Usually using plain pair classes is not recommended, because their name does not show the meaning of the object they represent. For example, it is better to use a class
PersonNamewhich has fields for first and last name instead of aPair<String, String>. Why can’t you just use aList<IdentityM>? And if you can use this, are you sure you can’t use aCollection<IdentityM>? (ListandCollectionare often exchangeable.) Then you could avoid the copying altogether.