Class ArrayList
Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)
The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(. ));
The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
This class is a member of the Java Collections Framework.
- Foreach java – подробное руководство
- Java forEach на карте
- forEach в наборе
- Использование forEach в массиве
- Фильтрация списка
- IntConsumer, LongConsumer, DoubleConsumer
- Java ArrayList forEach
- Syntax of ArrayList forEach() in Java
- Parameters of ArrayList forEach() in Java
- Return Values of ArrayList forEach() in Java
- Exceptions of ArrayList forEach() in Java
- Example
- What is ArrayList forEach() in Java?
- More Examples
- Example 1: ArrayList forEach() in Java
- Example 2: forEach() Method on ArrayList Which Contains a List of Numbers
- Example 3: forEach() Method on ArrayList Which Contains list of Objects
- Conclusion
Foreach java – подробное руководство
Метод forEach() был введен в Java 8. Он предоставляет программистам новый, краткий способ итерации по коллекции.
Метод forEach() выполняет заданное действие для каждого элемента Iterable до тех пор, пока все элементы не будут обработаны или действие не вызовет исключение.
void forEach(Consumer action);
Это синтаксис метода forEach().
Потребительский интерфейс – это функциональный интерфейс (интерфейс с одним абстрактным методом), который принимает один ввод и не возвращает результата.
@FunctionalInterface public interface Consumer
Это определение потребительского интерфейса.
package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class JavaForEachListConsumer < public static void main(String[] args) < List items = new ArrayList<>(); items.add("coins"); items.add("pens"); items.add("keys"); items.add("sheets"); items.forEach(new Consumer() < @Override public void accept(String name) < System.out.println(name); >>); > >
В этом примере мы перебираем список строк с помощью forEach(). Этот синтаксис можно сократить с помощью лямбда-выражения Java.
Лямбда-выражения используются в основном для определения встроенной реализации функционального интерфейса, то есть интерфейса только с одним методом. Лямбда-выражение создается с помощью лямбда-оператора.
package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class JavaForEachListLambda < public static void main(String[] args) < List items = new ArrayList<>(); items.add("coins"); items.add("pens"); items.add("keys"); items.add("sheets"); items.forEach((String name) -> < System.out.println(name); >); > >
Вот тот же пример. Лямбда-выражение делает пример более кратким.
Java forEach на карте
В следующем примере на карте используется forEach().
package com.zetcode; import java.util.HashMap; import java.util.Map; public class JavaForEachMap < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 3); items.put("pens", 2); items.put("keys", 1); items.put("sheets", 12); items.forEach((k, v) -> < System.out.printf("%s : %d%n", k, v); >); > >
У нас есть карта пар строка / целое число. С помощью метода forEach() мы перебираем карту и печатаем ее пары ключ / значение.
В следующем примере мы явно показываем Consumer и Map.Entry в коде.
package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class ForEachMap2 < public static void main(String[] args) < HashMapmap = new HashMap<>(); map.put("cups", 6); map.put("clocks", 2); map.put("pens", 12); Consumeraction = entry -> < System.out.printf("key: %s", entry.getKey()); System.out.printf(" value: %s%n", entry.getValue()); >; map.entrySet().forEach(action); > >
В примере выполняется цикл для набора записей, который извлекается с помощью entrySet().
forEach в наборе
В следующем примере для набора используется forEach().
package com.zetcode; import java.util.HashSet; import java.util.Set; public class JavaForEachSet < public static void main(String[] args) < Set brands = new HashSet<>(); brands.add("Nike"); brands.add("IBM"); brands.add("Google"); brands.add("Apple"); brands.forEach((e) -> < System.out.println(e); >); > >
У нас есть набор струн. С помощью метода forEach() мы перебираем набор и выводим его значения.
Использование forEach в массиве
В следующем примере forEach() используется для массива.
package com.zetcode; import java.util.Arrays; public class JavaForEachArray < public static void main(String[] args) < int[] nums = < 3, 4, 2, 1, 6, 7 >; Arrays.stream(nums).forEach((e) -> < System.out.println(e); >); > >
В этом примере у нас есть массив целых чисел. Мы используем метод Arrays.stream() для преобразования массива в поток. Затем метод forEach() перебирает элементы и выводит их на консоль.
Фильтрация списка
Мы можем легко отфильтровать наши данные перед их просмотром с помощью forEach().
package com.zetcode; import java.util.ArrayList; import java.util.List; public class JavaForEachListFilter < public static void main(String[] args) < List items = new ArrayList<>(); items.add("coins"); items.add("pens"); items.add("keys"); items.add("sheets"); items.stream().filter(item -> (item.length() == 4)).forEach(System.out::println); > >
В этом примере мы фильтруем список строк и выводим отфильтрованный список на консоль. Отображаются только строки из четырех символов.
IntConsumer, LongConsumer, DoubleConsumer
Начиная с Java 8, у нас есть встроенные потребительские интерфейсы для примитивных типов данных: IntConsumer, LongConsumer и DoubleConsumer.
package com.zetcode; import java.util.Arrays; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; public class JavaForEachConsSpec < public static void main(String[] args) < int[] inums = < 3, 5, 6, 7, 5 >; IntConsumer icons = i -> System.out.print(i + " "); Arrays.stream(inums).forEach(icons); System.out.println(); long[] lnums = < 13L, 3L, 6L, 1L, 8L >; LongConsumer lcons = l -> System.out.print(l + " "); Arrays.stream(lnums).forEach(lcons); System.out.println(); double[] dnums = < 3.4d, 9d, 6.8d, 10.3d, 2.3d >; DoubleConsumer dcons = d -> System.out.print(d + " "); Arrays.stream(dnums).forEach(dcons); System.out.println(); > >
В этом примере мы создаем три типа потребителей и перебираем их с помощью forEach().
Обычный способ зациклить карту.
Map items = new HashMap<>(); items.put(«A», 10); items.put(«B», 20); items.put(«C», 30); items.put(«D», 40); items.put(«E», 50); items.put(«F», 60); for (Map.Entry entry : items.entrySet())
В Java 8 Вы можете зациклить карту с помощью forEach + лямбда-выражения.
Map items = new HashMap<>(); items.put("A", 10); items.put("B", 20); items.put("C", 30); items.put("D", 40); items.put("E", 50); items.put("F", 60); items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v)); items.forEach((k,v)-> < System.out.println("Item : " + k + " Count : " + v); if("E".equals(k))< System.out.println("Hello E"); >>);
Нормальный цикл for в цикле список.
List items = new ArrayList<>(); items.add(«A»); items.add(«B»); items.add(«C»); items.add(«D»); items.add(«E»); for(String item : items)
В Java 8 вы можете зациклить список с помощью forEach + лямбда-выражения или ссылки на метод.
List items = new ArrayList<>(); items.add("A"); items.add("B"); items.add("C"); items.add("D"); items.add("E"); //lambda //Output : A,B,C,D,E items.forEach(item->System.out.println(item)); //Output : C items.forEach(item-> < if("C".equals(item))< System.out.println(item); >>); //method reference //Output : A,B,C,D,E items.forEach(System.out::println); //Stream and filter //Output : B items.stream() .filter(s->s.contains("B")) .forEach(System.out::println);
Средняя оценка 4.8 / 5. Количество голосов: 9
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Видим, что вы не нашли ответ на свой вопрос.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.
Java ArrayList forEach
In Java, the ArrayList collection has a method called forEach() , which lets us perform some operation on each element of the collection. The method traverses each element of the Iterable of ArrayList until all elements have been processed or an exception is raised.
Syntax of ArrayList forEach() in Java
The syntax for forEach() method is:
Parameters of ArrayList forEach() in Java
forEach() method takes in a single parameter: action, which represents the action to be performed for each element.
Consumer is a class that can be used when an object needs to be taken as input, and some operation is to be performed on the object without returning any result.
E signifies the data type of the ArrayList on which the action is being performed.
Thus the only parameter action is the operation that needs to be performed on each item in the ArrayList of data type E .
Return Values of ArrayList forEach() in Java
forEach() method does not return any value.
Exceptions of ArrayList forEach() in Java
NullPointerException: forEach throws a NullPointerException if the action passed to the method is null.
Example
We mostly use lambda functions within forEach to perform a certain operation on the items in the ArrayList .
For example, consider the following operation where we are printing the elements of a list line by line.
What is ArrayList forEach() in Java?
We should use forEach instead of conventional for loops, especially when we wish to use lambda functions. This is because the lambda function avoids the creation of bulky classes.
Lambda functions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method.
The above code using the lambda function can be written as:
The code becomes much cleaner and more elegant to look at.
Furthermore, the forEach operator uses an Internal Iterator which manages the iteration in the background and leaves the developer to just code what is supposed to be done with the elements of the collection. The iterator is responsible for iterating through the elements one by one.
In the example above, the argument provided is a lambda expression. This means that the method only needs to know what is to be done, and how iteration has to be done is taken care of internally.
More Examples
Example 1: ArrayList forEach() in Java
Let us say we have a list of strings that we wish to concatenate to make a line.
One by one, the strings in the words list would be concatenated, resulting in the following output:
Example 2: forEach() Method on ArrayList Which Contains a List of Numbers
Let us write a simple program to double the numbers in a list of Integers:
For every number in the list, we will multiply the number by 2 and update it in the same list itself.
Example 3: forEach() Method on ArrayList Which Contains list of Objects
Let us now take a fairly elaborate example where you want to create a list of objects in a retail store from a given list of items.
For every item in the store list, we create an Item object and increment a counter to store the id. These item objects are appended to a separate list.
Conclusion
- forEach() is used to iterate over the element of an ArrayList.
- forEach() expects an action as an argument and applies the action to each element.
- If the action is null , then it results in a NullPointerException.
- forEach() works excellent with lambda functions by avoiding the creation of bulky classes to define methods.