Java for iterator collection

Interface Iterator

This interface is a member of the Java Collections Framework.

Method Summary

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Removes from the underlying collection the last element returned by this iterator (optional operation).

Method Details

hasNext

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

next

remove

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next() . The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy. The behavior of an iterator is unspecified if this method is called after a call to the forEachRemaining method.

forEachRemaining

Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller. The behavior of an iterator is unspecified if the action modifies the collection in any way (even by calling the remove method or other mutator methods of Iterator subtypes), unless an overriding class has specified a concurrent modification policy. Subsequent behavior of an iterator is unspecified if the action throws an exception.

 while (hasNext()) action.accept(next()); 

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java for iterator collection

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Removes from the underlying collection the last element returned by this iterator (optional operation).

Method Detail

hasNext

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

next

remove

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next() . The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Читайте также:  Validate input in php

forEachRemaining

Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.

 while (hasNext()) action.accept(next()); 

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

A Guide to Iterator in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

Читайте также:  Php plus in get

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

An Iterator is one of many ways we can traverse a collection, and as every option, it has its pros and cons.

It was first introduced in Java 1.2 as a replacement of Enumerations and:

In this tutorial, we’re going to review the simple Iterator interface to learn how we can use its different methods.

We’ll also check the more robust ListIterator extension which adds some interesting functionality.

2. The Iterator Interface

To start, we need to obtain an Iterator from a Collection; this is done by calling the iterator() method.

For simplicity, we’ll obtain Iterator instance from a list:

List items = . Iterator iter = items.iterator();

The Iterator interface has three core methods:

2.1. hasNext()

The hasNext() method can be used for checking if there’s at least one element left to iterate over.

It’s designed to be used as a condition in while loops:

2.2. next()

The next() method can be used for stepping over the next element and obtaining it:

It’s good practice to use hasNext() before attempting to call next().

Iterators for Collections don’t guarantee iteration in any particular order unless particular implementation provides it.

2.3. remove()

Finally, if we want to remove the current element from the collection, we can use the remove:

This is a safe way to remove elements while iterating over a collection without a risk of a ConcurrentModificationException.

2.4. Full Iterator Example

Now we can combine them all and have a look at how we use the three methods together for collection filtering:

This is how we commonly use an Iterator, we check ahead of time if there is another element, we retrieve it and then we perform some action on it.

2.5. Iterating With Lambda Expressions

As we saw in the previous examples, it’s very verbose to use an Iterator when we just want to go over all the elements and do something with them.

Читайте также:  Css применить для всех дочерних

Since Java 8, we have the forEachRemaining method that allows the use of lambdas to processing remaining elements:

iter.forEachRemaining(System.out::println);

3. The ListIterator Interface

ListIterator is an extension that adds new functionality for iterating over lists:

ListIterator listIterator = items.listIterator(items.size());

Notice how we can provide a starting position which in this case is the end of the List.

3.1. hasPrevious() and previous()

ListIterator can be used for backward traversal so it provides equivalents of hasNext() and next():

while(listIterator.hasPrevious())

3.2. nextIndex() and previousIndex()

Additionally, we can traverse over indices and not actual elements:

String nextWithIndex = items.get(listIterator.nextIndex()); String previousWithIndex = items.get(listIterator.previousIndex());

This could prove very useful in case we need to know the indexes of the objects we’re currently modifying, or if we want to keep a record of removed elements.

3.3. add()

The add method, which, as the name suggests, allows us to add an element before the item that would be returned by next() and after the one returned by previous():

3.4. set()

The last method worth mentioning is set(), which lets us replace the element that was returned in the call to next() or previous():

String next = listIterator.next(); if( "ONE".equals(next))

It’s important to note that this can only be executed if no prior calls to add() or remove() were made.

3.5. Full ListIterator Example

We can now combine them all to make a complete example:

ListIterator listIterator = items.listIterator(); while(listIterator.hasNext()) < String nextWithIndex = items.get(listIterator.nextIndex()); String next = listIterator.next(); if("REPLACE ME".equals(next)) < listIterator.set("REPLACED"); >> listIterator.add("NEW"); while(listIterator.hasPrevious())

In this example, we start by getting the ListIterator from the List, then we can obtain the next element either by index –which doesn’t increase the iterator’s internal current element – or by calling next.

Then we can replace a specific item with set and insert a new one with add.

After reaching the end of the iteration, we can go backward to modify additional elements or simply print them from bottom to top.

4. Conclusion

The Iterator interface allows us to modify a collection while traversing it, which is more difficult with a simple for/while statement. This, in turn, gives us a good pattern we can use in many methods that only requires collections processing while maintaining good cohesion and low coupling.

Finally, as always the full source code is available over at GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью