Java map iterator пример

Interface Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

All general-purpose map implementation classes should provide two «standard» constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

Читайте также:  Change all keys in array php

The «destructive» methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be «superimposed» is empty.

Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: «returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)) .» This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k . Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

Some map operations which perform recursive traversal of the map may fail with an exception for self-referential instances where the map directly or indirectly contains itself. This includes the clone() , equals() , hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.

Unmodifiable Maps

  • They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method on the Map will always cause UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  • They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException .
  • They are serializable if all keys and values are serializable.
  • They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException .
  • The iteration order of mappings is unspecified and is subject to change.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Итерация карты в Java с использованием метода entrySet()

В этом посте будут обсуждаться различные методы итерации карты в Java с использованием entrySet() метод.

Мы знаем это Map.entrySet() возвращает набор сопоставлений ключ-значение, содержащихся в карте. Итак, мы можем перебрать карту, используя Map.entrySet() , который содержит обе пары ключ-значение. Есть несколько способов сделать это:

1. Использование Iterator

Поскольку карта не расширяет Collection интерфейс, у него нет собственного итератора. Но Map.entrySet() возвращает набор сопоставлений ключ-значение, и поскольку Set расширяет Collection интерфейс, мы можем получить к нему итератор. Теперь мы можем легко обработать каждую пару ключ-значение, используя простой цикл while, как показано ниже:

2. Использование цикла for-each (расширенный оператор for)

Цикл for также имеет другую вариацию, предназначенную для итерации по коллекциям и массивам. Он называется циклом for-each и доступен любому объекту, реализующему цикл. Iterable интерфейс. В качестве Set расширяет Collection интерфейс и Collection расширяет Iterable интерфейс, мы можем использовать цикл for-each для прохода через entrySet. Обратите внимание, что этот подход также вызовет iterator() метод за кадром.

3. Использование Iterator.forEachRemaining() метод

Мы также можем использовать forEachRemaining() метод, который является последним дополнением к Iterator интерфейс в Java 8 и выше. Он выполняет данное действие для каждого оставшегося элемента, пока все элементы не будут обработаны.

Как было показано ранее, мы можем легко получить итератор для множества Map.Entry . Когда у нас есть итератор, мы можем передать ссылку на метод System.out::println или соответствующее лямбда-выражение E -> System.out.println(E) к forEachRemaining() метод, как показано ниже:

Источник

Паттерн Iterator

Java-университет

Как ты уже, вероятно, знаешь, в Java есть замечательный интерфейс Collection, реализующий интерфейс Iterator. Сразу оговорюсь, не следует путать интерфейс iterator с паттерном iterator в Java! И дабы внести ясность, для начала разберёмся именно с интерфейсом.

Дословно «Iterator» можно перевести как «переборщик». То есть это некая сущность, способная перебрать все элементы в коллекции. При этом она позволяет это сделать без вникания во внутреннюю структуру и устройство коллекций.

Представим на секунду, что iterator в Java отсутствует. В таком случае всем и каждому придётся нырнуть в самые глубины коллекций и по-настоящему разобраться, чем отличается, ArrayList от LinkedList и HashSet от TreeSet .

Методы, которые должен имплементировать Iterator

  • UnsupportedOperationException , если данный итератор не поддерживает метод remove() (в случае с read-only коллекциями, например)
  • IllegalStateException , если метод next() еще не был вызван, или если remove() уже был вызван после последнего вызова next() .
  • void add(E e) — вставляет элемент E в List ;
  • boolean hasPrevious() — вернет true , если при обратном переборе List имеются элементы;
  • int nextIndex() — вернет индекс следующего элемента;
  • E previous() — вернет предыдущий элемент листа;
  • int previousIndex() — вернет индекс предыдущего элемента;
  • void set(E e) — заменит элемент, возвращенный последним вызовом next() или previous() на элемент e .
 List list = new ArrayList<>(); list.add("Привет"); list.add("Обучающимся"); list.add("На"); list.add("JavaRush"); 
 Iterator iterator = list.iterator(); while (iterator.hasNext())

Сейчас будет «узкое место»: Java Collections как ты, вероятно, знаешь (а если не знаешь, разберись), расширяют интерфейс Iterable , но это не означает, что только List , Set и Queue поддерживают итератор. Для java Map iterator также поддерживается, но его необходимо вызывать для Map.entrySet() :

 Map map = new HashMap<>(); Iterator mapIterator = map.entrySet().iterator(); 

Тогда метод next() будет возвращать объект Entry , содержащий в себе пару «ключ»-«значение». Дальше все аналогично с List :

 while (mapIterator.hasNext()) < Map.Entryentry = mapIterator.next(); System.out.println("Key: " + entry.getKey()); System.out.println("Value: " + entry.getValue()); > 

Ты думаешь: «Стоп. Мы говорим про интерфейс, а в заголовке статьи написано «Паттерн». То есть, паттерн iterator – это интерфейс Iterator? Или интерфейс — это паттерн?» Если это слово встречается впервые, даю справку: паттерн — это шаблон проектирования, некое поведение, которого должен придерживаться класс или множество взаимосвязанных классов. Итератор в java может быть реализован для любого объекта, внутренняя структура которого подразумевает перебор, при этом можно изменить сигнатуру обсуждаемых методов. Главное при реализации паттерна – логика, которой должен придерживаться класс. Интерфейс итератор – частная реализация одноименного паттерна, применяемая как к готовым структурам ( List, Set, Queue, Map ), так и к прочим, на усмотрение программиста. Расширяя интерфейс Iterator, ты реализуешь паттерн, но для реализации паттерна не обязательно расширять интерфейс. Простая аналогия: все рыбы плавают, но не всё, что плавает – рыбы. В качестве примера я решил взять… слово. А конкретнее — существительное. Оно состоит из частей: приставки, корня, суффикса и окончания. Для частей слова создадим интерфейс WordPart и классы, расширяющие его: Prefix, Root, Suffix и Ending :

 interface WordPart < String getWordPart(); >static class Root implements WordPart < private String part; public Root(String part) < this.part = part; >@Override public String getWordPart() < return part; >> static class Prefix implements WordPart < private String part; public Prefix(String part) < this.part = part; >@Override public String getWordPart() < return part; >> static class Suffix implements WordPart < private String part; public Suffix(String part) < this.part = part; >@Override public String getWordPart() < return part; >> static class Ending implements WordPart < private String part; public Ending(String part) < this.part = part; >@Override public String getWordPart() < return part; >> 

Тогда класс Word (слово) будет содержать в себе части, а кроме них добавим целое число, отражающее количество частей в слове:

 public class Word < private Root root; private Prefix prefix; private Suffix suffix; private Ending ending; private int partCount; public Word(Root root, Prefix prefix, Suffix suffix, Ending ending) < this.root = root; this.prefix = prefix; this.suffix = suffix; this.ending = ending; this.partCount = 4; >public Word(Root root, Prefix prefix, Suffix suffix) < this.root = root; this.prefix = prefix; this.suffix = suffix; this.partCount = 3; >public Word(Root root, Prefix prefix) < this.root = root; this.prefix = prefix; this.partCount = 2; >public Word(Root root) < this.root = root; this.partCount = 1; >public Root getRoot() < return root; >public Prefix getPrefix() < return prefix; >public Suffix getSuffix() < return suffix; >public Ending getEnding() < return ending; >public int getPartCount() < return partCount; >public boolean hasRoot() < return this.root != null; >public boolean hasPrefix() < return this.prefix != null; >public boolean hasSuffix() < return this.suffix != null; >public boolean hasEnding()

Окей, у нас есть четыре перегруженных конструктора (для простоты, предположим, что суффикс у нас может быть только один). Существительное не может состоять из одной приставки, поэтому для конструктора с одним параметром будем устанавливать корень. Теперь напишем реализацию паттерна итератор: WordIterator, переопределяющий 2 метода: hasNext() и next() :

 public class WordIterator implements Iterator  < private Word word; private int wordPartsCount; public WordIterator(Word word) < this.word = word; this.wordPartsCount = word.getPartCount(); >@Override public boolean hasNext() < if (wordPartsCount == 4) < return word.hasPrefix() || word.hasRoot() || word.hasSuffix() || word.hasEnding(); >else if (wordPartsCount == 3) < return word.hasPrefix() || word.hasRoot() || word.hasSuffix(); >else if (wordPartsCount == 2) < return word.hasPrefix() || word.hasRoot(); >else if (wordPartsCount == 1) < return word.hasRoot(); >return false; > @Override public Word.WordPart next() throws NoSuchElementException < if (wordPartsCount try < if (wordPartsCount == 4) < return word.getEnding(); >if (wordPartsCount == 3) < return word.getSuffix(); >if (wordPartsCount == 2) < return word.getPrefix(); >return word.getRoot(); > finally < wordPartsCount--; >> > 
 public class Word implements Iterable < … @Override public Iteratoriterator() < return new WordIterator(this); >… > 

Источник

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