Для перебора ArrayList в Java вы можете использовать различные методы и конструкции. Вот несколько распространенных способов добиться этого:
-
Использование цикла for:
ArrayList<String> arrayList = new ArrayList<>(); // Add elements to the ArrayList for (int i = 0; i < arrayList.size(); i++) { String element = arrayList.get(i); // Process the element } -
Использование расширенного цикла for (цикл for-each):
ArrayList<String> arrayList = new ArrayList<>(); // Add elements to the ArrayList for (String element : arrayList) { // Process the element } -
Использование итератора:
ArrayList<String> arrayList = new ArrayList<>(); // Add elements to the ArrayList Iterator<String> iterator = arrayList.iterator(); while (iterator.hasNext()) { String element = iterator.next(); // Process the element } -
Использование ListIterator (позволяет двунаправленный обход):
ArrayList<String> arrayList = new ArrayList<>(); // Add elements to the ArrayList ListIterator<String> listIterator = arrayList.listIterator(); while (listIterator.hasNext()) { String element = listIterator.next(); // Process the element } -
Использование API Java 8 Stream:
ArrayList<String> arrayList = new ArrayList<>(); // Add elements to the ArrayList arrayList.stream().forEach(element -> { // Process the element });
Эти методы предоставляют различные способы перебора ArrayList в Java. Выберите тот, который лучше всего соответствует вашим потребностям.