Retrieving items from Collection
Retrieving items from Collection
I have a Collection c, which contains 3 items. I want to assign these 3 items to 3 different variables
Collection<Object> c;
var1 = firstItem;
var2 = secondItem;
var3 = thirdItem;
How can I extract the elements of the collection?
2 Answers
2
You can do it as following:
Collection<Object> collection = ...;
Iterator iterator = collection.iterator();
Object firstItem = iterator.next();
Object secondItem = iterator.next();
Object thirdItem = iterator.next();
Update:
This option is fine only if you are sure that collection contains at least 3 items. Otherwise, you need to check whether iterator has next item (method hasNext
) before calling next
.
hasNext
next
Don't forget to check for the existence of a next element, using
iterator.hasNext();
as it may throw a NoSuchElementException
.– chŝdk
Jun 29 at 9:11
iterator.hasNext();
NoSuchElementException
chŝdk, you are right. I have updated my answer. Thanks.
– Timur Levadny
Jun 29 at 9:19
When I do it like this: iterator.next() there is an error When I do it like this: collection.iterator().next() there isn't Can I use the second one?
– ilinq
Jun 29 at 9:34
What is the error? The second option will always provide first item.
– Timur Levadny
Jun 29 at 9:40
Found: 'java.lang.Object' , required 'android.os.Parcelable'
– ilinq
Jun 29 at 9:52
Maybe this can help you :
Object array = c.toArray();
Object var1 = array[0];
Object var2 = array[1];
Object var3 = array[2];
Note toArray()
return an array of Object so in case of another Type you have to cast the result for example or you can use :
toArray()
Collection<String> c = Arrays.asList("a", "b", "c");
String array = c.toArray(new String[c.size()]);
String var1 = array[0];
String var2 = array[1];
String var3 = array[2];
Or with a List
Collection<String> c = Arrays.asList("a", "b", "c");
List<String> list = (List<String>) c;
String var1 = list.get(0);
String var2 = list.get(1);
String var3 = list.get(2);
I think that Invoking
toArray()
for each item is not a good idea from performance perspectives.– Timur Levadny
Jun 29 at 9:11
toArray()
Thank you @TimurLevadny this is correct I just fix it
– YCF_L
Jun 29 at 9:16
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There is no effort from OP.
– pvpkiran
Jun 29 at 9:05