Java Iterator - In Depth

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in Java an iterator is a component that enables you to iterate through a collection of elements typically a collection of objects the jab iterator interface in the java.util package represents such an iterator typically you will obtain an iterator from a Java collection like a list or a set and I've created two examples here illustrating that the first example here creates a list that's three elements to it and then called list that iterator which returns an iterator that I can now use to iterate the elements stored in the list and I do the same here with a set create a set add three elements to it and then I call the setter iterator which can now be used to this iterator return from list iterator can now be used to iterate the elements store in this set finally it is also possible to obtain an iterator from a map but it works a little bit differently you can either obtain an iterator that can iterate through the set of keys stored in the map or you can have obtain an iterator that can iterate through the values stored in the map or you can obtain an iterator that can iterate through entries stored in the map and an entry consists of a key and a value so either you can get just the keys just the values or key value pairs to iterate the elements available through an iterator you have to use a combination of the iterator hasnext and the iterator next methods and I have created an example here that illustrates that first I create a list and I add three elements to the list and then here I call list an iterator which returns an iterator now I can use this iterator inside of a while loop I keep calling has next and has next will return true if there are more elements left in the iterator and false if not so I keep calling it within this a while loop and inside the while loop I call the next method and the next method will return they're currently the current element that the iterator is pointing to and then advanced the internal pointer in the iterator to the next element and I keep doing that in a while loop and eventually the iterator that next method here will have advanced the internal pointer beyond the last element and then has next will return false and the while loop will end and you can see it is the same that I do down here when I am iterating through the elements of a set there's no difference here now let's try to run this example and see what the output looks like as you can see we iterate through the elements in the list first and we print them out here right and that is Jane Heidi and Hannah and that is the exact same order actually that we added the names to the listing right because and that's something that is determined by the iterator returned by a list that the elements are returned by the iterator in the same order they are stored inside the list however when we iterate through the set you can see that Jane Heidi and Hannah are also added to the set but when we print them out we get them out in a different order it's Heidi Hannah and Jane it looks like almost like a reverse order but that is because a set does not actually guarantee the order in which the elements are stored internally at least a Hester does not if you use a tree set that will actually guarantee some ordering but that is outside the scope of this tutorial if you check out my set tutorial you can see more more about how that works so just to sum it up the order that the elements of the underlying collection is iterated in is determined and by the collection that creates the iterator that you are using to iterate them with it is not guaranteed by the iterator interface in the examples I've shown you so far I am used a generic type for the collections that I've created and therefore also for the iterates is that I have created and I've created an example here that illustrates this again like you can see I create a list and the generic type is set to string and that means that when we call list of iterator it returns an iterator of type iterator with the generic type string it is also possible to create a list here without a generic type and I have an example here and if I call list to hear that iterator then I get an iterator without a generic type as well and as a consequence of that I will have to cast all the objects returned by the iterator next method here because now you you no longer know what type of element is returned by the iterator so you have to cast them yourself if you know the generic type of your collection and thereby of the iterator then it is considered a really good practice to specify it right don't leave it out just because it's seems like it's easier because it's actually easier for the next person reading your code to see what kind of objects are supposed to be stored in this list and also then which are returned by the iterator when the there is a generic type specified for them for the collection and also for the iterator it is not allowed to modify the underlying collection while you are iterating it and if you do that anyways you will get an a concurrent modification exception thrown from the iterator next method and I've created an example here that illustrates that here create a list add three elements to it call list an iterator to obtain an iterator from the list and then I eats right through the elements in the list but notice here that I am actually removing the last element of the list inside this loop that iterates through the elements of the iterator and let's run this example here and see what happens now you can see that the first time we call next it works fine then we modify the the list that actually succeeds as well and then the next time around that we call next you can see here the exception in the exception stack trace it says that the exception comes from the next call the next time we call next the iterates of the text that the list up here has been changed since the iterator was created and thus it throws a concurrent modification exception the name concurrent modification exception might make you think that this means that the underlying list or set or whatever collection you are iterating has been modified concurrently by another thread but that is not what it means it just means that the underlying collection has been modified while the collection has been iterated with an iterator so in other words it means that the the underlying collection has been changed since one of the iterators that you have obtained from that collection has been created so if you see a concurrent modification exception in your code this does not necessarily mean that you have a multi-threading problem in your code unless of course you are actually modifying or accessing the same collection from different threads but as I have shown in this example this concurrent modification exception can be thrown even when you have just a single thread accessing the underlying collection it all it takes is that you modify the underlying collection while you're iterating through the the collection with an iterator and additionally you will only get an a concurrent modification exception if you call next on an iterator that was created before the change now let's imagine that I completely iterate through all the elements in this loop here this while loop everything goes well down here we modify the list and then we obtain another iterator and iterate the elements of the list at that point well since we are no longer accessing the first iterator which was created if you know when the list only had three elements or before the the modification here we will not get an a concurrent modification exception when we use the next one let me just show you here let's just copy this and let me show you now it's rho2 and here let's let's actually modify the the list we say list remove list at size minus one so now we remove the last element and now we obtain another iterator and we iterate through that and you will see now this this will work there's no problem here because the iterator that we created up here we are no longer using after this modification here down here now we obtain a new iterator and that is not a problem to iterate you know the the elements the way they look in the list now let me just try to run the example and I can show you that now it works just fine now you can see in the first iteration we get Jane Heidi Hannah out and in the last one only Jane and Heidi because we just removed Hannah so after the while loop stops here and we kind of throw away this iterator up here we kind of forget about it then we will no longer be in danger of getting concurrent modification exceptions anymore as long as you don't call this iterator again in the future when the underlying collection has been chained then you need to obtain a new iterator and iterate the collection from scratch again it is actually possible to remove elements from the underlying collection while you're iterating it if you call the iterator remove method and not like I did here in this example called the list removed directly let's just try to have a look at how that looks here I just delete all this code now in here I call it's rated R remove and that means that iterator remove now get called for each iteration of the while loop and iterator that removed here will remove the element that was previously returned by the next method so that means that for every iteration through the loop I can obtain the next element I can inspect it and based on the value of this element I can decide if it needs to be removed or not on link you can see here in this case I just removed them always right I don't have any if statements or anything but it would be possible for you to to check it and see if it needs to be removed now after this while loop finishes the list will be empty because we have iterated through all the elements and removed them one point by one and so we expect now that the size of the list is zero let's just run this example here and and see that this is also the case and as you can see we first iterate through all the elements and then the the while loop finishes and then we print them to the size of the list and it's zero because all of the elements were removed during iteration so if you want to remove elements during the iteration of the elements stored in some collection like a list or a set you need to use the iterator to remove method that way the iterator can keep track of which elements are removed so the iteration does not get out of synch with the underlying collection Java also contains a special list iterator which is a slightly more advanced iterator which can be used to iterate the elements of a list in both directions meaning both forward and backwards and I have created an example here that shows you how that works I won't get like into great detail about the list iterator interface it has actually more methods that I am that I'm showing you here but I just want to show you a quick example of how how it works so I create a normal list here and then I call here list is racer instead of iterator and as you can see the type is now a list iterator not a normal iterator and since list iterator extends the normal it it's interface you can use the hands next and next methods and iterate the elements in forward order from the first to the last element but as you can see here when I'm done its rating all the elements all the way to the end I can actually iterate them backwards again using the exact same iterate so here I use the same iterator the list iterator here and I just simply call his previous as long as it has an element that was before the previously returned element I can go backwards to the next one and print that out and now when I run this example you can see that first we get Jane Heidi Hannah from the first iteration that's iterating them in forward direction Jane Heidi Hannah same sequence in which they were were added to the list and then you can see we get you know in during the second iteration when we are iterating you know backwards through the list iterator we're getting the values Hana highly and Jane which is reverse order and in this example here I showed you that you know this example here I show you iterates the iterator all the way to the end before start going backwards but that is not unnecessary you can go both forward and backwards during the same iteration and during the same loop then it is just up to you to find out when to stop the iteration the last thing I want to show you in this Java iterator video is that it is possible to implement the iterator interface yourself imagine you have implemented some kind of collection a tree or some other kind of data structure and you would like that data structure to be iterable through an iterator and you can create your own iterator for that specific collection yourself in this example I'm creating a very simple it's rates are just to show you how it looks and exactly how an an iterator will be implemented completely depends on the underlying collection that it will be iterating through so in this case I'm just creating a very simple list iterator you can see here I have a list a variable here and I have an index which kind of points to the current element that the iterator is pointing to and you can see when I create a list here with the in the my list iterator constructor we take the list in a sauce and you can see here that they has next method that I must implement because that is part of the iterator interface will return whether the index this variable up here is smaller than the size of the list and that means that if the index is smaller than the size of the list that means we still have not returned the last element from the list and then you can see in the next method which I also have to implement I return the element pointed to by index and then I increment the index afterwards after obtaining this element and to use this little iterator here will look just like almost like using a normal iterator you can see I create a list here and I add three elements to it and then I create a new iterator but in this particular case I create a new instance of my own iterate and I pass the list here as parameter to the constructor but the rest is the same right we call the iterator has next in a loop and for each iteration call the next method of the iterator and then print out the value and let's just run this so you can see that this actually works right one two three is what is added to the list and one two three other value is returned by the iterator in that order but wait there's just one more thing that I want to show you about the java iterates interface before I finish up this video and that is that since Java 8 the iterator interface has a new method called for each remaining and you can call this method and pass a lambda expression to it and then that lambda expression gets called one time for each remaining element in the iterator and I have an example here that shows how that works first I create a list add three elements to it and obtain an iterator this is standard and then the example here calls for its remaining and as for ammeter has passed this Java lambda expression and this will get called once for each element in the list and that means the first time that this lambda expression gets called the first element will be passed as the parameter to the lambda expression and first get printed out and the second time this second element will get passed as parameter and the third time the third element will be cast as parameter to the lambda expression let's run this example here and see that this is also what we get and you can see we get Jane Heidi Hannah and that is the elements added up here and in exactly the order they were added in the list and that is of course because this is a list iterator so as you can see we can use the phrase remaining to iterate the elements of an iterator in a slightly more functional manner than the standard while loop with the while heads next call iterator next that pretty much covers the Java iterator interface remember to check out the description below the video for a link to a textual version of this tutorial as well as links to other related tutorials and if you like this video hit the like button and maybe subscribe to my channel if you want to see more videos like this one
Info
Channel: Jakob Jenkov
Views: 8,734
Rating: 4.9693484 out of 5
Keywords: Java, Java Iterator, Java Collections
Id: mzpgeRuYduY
Channel Id: undefined
Length: 19min 12sec (1152 seconds)
Published: Thu May 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.