{"id":2970,"date":"2024-01-19T16:05:43","date_gmt":"2024-01-19T16:05:43","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=2970"},"modified":"2025-07-07T10:57:23","modified_gmt":"2025-07-07T10:57:23","slug":"java-iterator","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-iterator\/","title":{"rendered":"Java design pattern Iterator"},"content":{"rendered":"<p>Today we will look at another <strong>Java<\/strong> <strong>design pattern<\/strong> from the category of <strong>behavioural patterns<\/strong> &#8211; Iterator. Design patterns in this category deal with the <strong>interaction<\/strong> between objects and their <strong>responsibility<\/strong>.<\/p>\n<h2>What is the Iterator design pattern?<\/h2>\n<p>The Iterator design pattern in object-oriented programming provides a way to systematically access and traverse the elements of an object stored in a container without knowing its internal representation. It also separates the algorithms that apply to the elements from the container.<\/p>\n<h2>What problem does the Iterator design pattern solve?<\/h2>\n<p>It solves the problem of efficiently accessing items in a collection while hiding the structure of that collection. Its main goal is to provide a consistent way to navigate through different types of collections without having to know their internal structure. <\/p>\n<p>This pattern defines the Iterator interface, which by default includes methods such as <em>next()<\/em>, <em>hasNext()<\/em>, etc. Specific implementations of this interface are provided by classes that implement collections, such as lists, sets, arrays, and so on.<\/p>\n<h2>Example of an Iterator implementation in Java<\/h2>\n<p>We&#8217;ll create a program to add notes and use the <strong>Iterator<\/strong> design pattern to show how we can easily access and navigate through them. We will create the interface as a template so that it can be used for any data type.<\/p>\n<p><strong><u>Iterator.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\n\/\/ Rozhranie pre iterator\npublic interface Iterator&lt;T&gt; {\n    boolean hasNext();\n    T next();\n}<\/code><\/pre>\n<p>The <strong>Iterator <\/strong> interface defines the methods <em>hasNext()<\/em> and <em>next()<\/em>. The first method should check if there is another element, the second should then return the next element. <\/p>\n<p><strong><u>ListIterator.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\nimport java.util.List;\n\n\/\/ Konkretny iterator pre zoznam (List)\npublic class ListIterator&lt;T&gt; implements Iterator&lt;T&gt; {\n    private List&lt;T&gt; zoznam;\n    private int pozicia;\n\n    public ListIterator(List&lt;T&gt; zoznam) {\n        this.zoznam = zoznam;\n        this.pozicia = 0;\n    }\n\n    @Override\n    public boolean hasNext() {\n        return pozicia &lt; zoznam.size();\n    }\n\n    @Override\n    public T next() {\n        if(this.hasNext())\n            return zoznam.get(pozicia++);\n        return null;\n    }\n}<\/code><\/pre>\n<p><strong>ListIterator<\/strong> implements the <strong>Iterator<\/strong> interface and provides a concrete implementation for List. It holds a reference to the list (List&lt;T&gt;) and keeps track of the current position for the iteration. The <em>hasNext()<\/em> method checks if there is another element in the list. The <em>next()<\/em> method returns the next element in the list and moves the position to the next element.<\/p>\n<p><strong><u>Notes.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Poznamky&lt;T&gt; {\n    private List&lt;T&gt; poznamky;\n    public Poznamky() {\n        this.poznamky = new ArrayList&lt;&gt;();\n    }\n\n    public void pridajPoznamku(T poznamka) {\n        poznamky.add(poznamka);\n    }\n\n    public Iterator&lt;T&gt; iterator() {\n        return new ListIterator&lt;&gt;(poznamky);\n    }\n}<\/code><\/pre>\n<p>The <strong>Notes <\/strong> class stores a list of notes (in this case of type T). The <em>addNote()<\/em> method adds a new note to the list. The <em>iterator()<\/em> method creates and returns a <strong>ListIterator <\/strong> instance, which is used to iterate over the notes in the list.  <\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.Iterator;\nimport designpatterns.Poznamky;\n\npublic class Main {\n    public static void main(String[] args) {\n        Poznamky&lt;String&gt; poznamky = new Poznamky&lt;&gt;();\n        poznamky.pridajPoznamku(&quot;Zajtra bude sne\u017ei\u0165.&quot;);\n        poznamky.pridajPoznamku(&quot;\u010coskoro bud\u00fa Vianoce.&quot;);\n        poznamky.pridajPoznamku(&quot;Treba nak\u00fapi\u0165 dar\u010deky.&quot;);\n        \/\/ Pouzitie iteratora na prechadzanie cez pridane poznamky\n        Iterator&lt;String&gt; iterator = poznamky.iterator();\n        while(iterator.hasNext()) {\n            System.out.println(iterator.next());\n        }\n    }\n}<\/code><\/pre>\n<p><strong>Main<\/strong> is a client class that demonstrates the use of this design pattern. It creates a <strong>Notes <\/strong> instance of a given <strong>string <\/strong> type, adds some notes, iterates over them and prints them using the iterator.<\/p>\n<p>The output from this example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-2541 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/vystup-z-prikladu-460-180.webp\" alt=\"Main is a client class that demonstrates the use of this design pattern and creates a Notes instance of a particular String type.\" width=\"460\" height=\"180\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/vystup-z-prikladu-460-180.webp 460w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/vystup-z-prikladu-460-180-300x117.webp 300w\" sizes=\"auto, (max-width: 460px) 100vw, 460px\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>The <strong>Iterator<\/strong> design pattern is used by default to iterate over a group of objects in a data structure, regardless of the specific object type. This pattern is so common that there are predefined classes in programming languages. Iterators do not have to traverse only to the next object, but can be implemented to traverse width or depth in a tree structure, for example.  <\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. ou can download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/01\/Iterator.zip\">Java <strong>Iterator <\/strong> code here<\/a>.<\/p>\n<p>If you&#8217;re a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developer<\/a> looking for work, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\">employee benefits<\/a> and respond to our <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is the Java Iterator design pattern and what is it for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2545,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2970","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2970","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=2970"}],"version-history":[{"count":5,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2970\/revisions"}],"predecessor-version":[{"id":5266,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2970\/revisions\/5266"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2545"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2970"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2970"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2970"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}