GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java ArrayList - ArrayList methods, sorting, traversing in Java Java ArrayListlast modified February 23, 2024
In this article we show how to work with Java collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A collection is an object that represents a group of objects. ArrayList definition
Elements in the
An The add method
Single elements can be added to an Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> langs = new ArrayList<>();
langs.add("Java");
langs.add("Python");
langs.add(1, "C#");
langs.add(0, "Ruby");
for (String lang : langs) {
System.out.printf("%s ", lang);
}
System.out.println();
}
The example adds elements to an array list one by one. List<String> langs = new ArrayList<>();
An langs.add("Java");
An element is appended at the end of the list with the langs.add(1, "C#");
This time the overloaded for (String lang : langs) {
System.out.printf("%s ", lang);
}
With the $ java Main.java Ruby Java C# Python Note that the elements keep the order they were inserted. The List.of methodSince Java 9, we have a couple of factory methods for creating lists having a handful of elements. The created list is immutable. Main.java
import java.util.List;
void main() {
var words = List.of("wood", "forest", "falcon", "eagle");
System.out.println(words);
var values = List.of(1, 2, 3);
System.out.println(values);
}
In the example, we create two lists that have four and three elements. The get and size methods
The Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> colours = new ArrayList<>();
colours.add("blue");
colours.add("orange");
colours.add("red");
colours.add("green");
String col = colours.get(1);
System.out.println(col);
int size = colours.size();
System.out.printf("The size of the ArrayList is: %d%n", size);
}
The example uses the String col = colours.get(1);
The int size = colours.size();
The $ java Main.java orange The size of the ArrayList is: 4 The copy method
A copy of a list can be generated with Main.java
import java.util.List;
void main() {
var words = List.of("forest", "wood", "eagle", "sky", "cloud");
System.out.println(words);
var words2 = List.copyOf(words);
System.out.println(words2);
}
The example creates a copy of a list with Raw ArrayList
An
Note: It is generally not recommended to use raw lists.
Raw lists often require casts and they are not type safe. Main.java
import java.util.ArrayList;
import java.util.List;
class Base {}
enum Level {
EASY,
MEDIUM,
HARD
}
void main() {
Level level = Level.EASY;
List da = new ArrayList();
da.add("Java");
da.add(3.5);
da.add(55);
da.add(new Base());
da.add(level);
for (Object el : da) {
System.out.println(el);
}
}
The example adds five different data types into an array list — a string, double, integer, object, and enumeration. List da = new ArrayList(); When we add multiple data types to a list, we omit the angle brackets. $ java Main.java Java 3.5 55 com.zetcode.Base@659e0bfd EASY The addAll method
The following example uses the Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> colours1 = new ArrayList<>();
colours1.add("blue");
colours1.add("red");
colours1.add("green");
List<String> colours2 = new ArrayList<>();
colours2.add("yellow");
colours2.add("pink");
colours2.add("brown");
List<String> colours3 = new ArrayList<>();
colours3.add("white");
colours3.add("orange");
colours3.addAll(colours1);
colours3.addAll(2, colours2);
for (String col : colours3) {
System.out.println(col);
}
}
Two lists are created. Later, the elements of the lists are added to the
third list with the colours3.addAll(colours1);
The colours3.addAll(2, colours2); This overloaded method adds all of the elements starting at the specified position. $ java Main.java white orange yellow pink brown blue red green Modifying elements
The next example uses methods to modify the Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> items = new ArrayList<>();
fillList(items);
items.set(3, "watch");
items.add("bowl");
items.remove(0);
items.remove("pen");
for (Object el : items) {
System.out.println(el);
}
items.clear();
if (items.isEmpty()) {
System.out.println("The list is empty");
} else {
System.out.println("The list is not empty");
}
}
void fillList(List<String> data) {
data.add("coin");
data.add("pen");
data.add("pencil");
data.add("clock");
data.add("book");
data.add("spectacles");
data.add("glass");
}
An items.set(3, "watch");
The items.add("bowl");
The items.remove(0);
The items.remove("pen");
The overloaded items.clear();
The if (items.isEmpty()) {
The $ java Main.java pencil watch book spectacles glass bowl The list is empty The removeIf method
The Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<Integer> values = new ArrayList<>();
values.add(5);
values.add(-3);
values.add(2);
values.add(8);
values.add(-2);
values.add(6);
values.removeIf(val -> val < 0);
System.out.println(values);
}
In our example, we have an values.removeIf(val -> val < 0); All negative numbers are removed from the array list. $ java Main.java [5, 2, 8, 6] The removeAll method
The Main.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
void main() {
List<String> letters = new ArrayList<>();
letters.add("a");
letters.add("b");
letters.add("c");
letters.add("a");
letters.add("d");
System.out.println(letters);
letters.removeAll(Collections.singleton("a"));
System.out.println(letters);
}
In the example, we remove all "a" letters from the list. The replaceAll method
The Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;
void main() {
List<String> items = new ArrayList<>();
items.add("coin");
items.add("pen");
items.add("cup");
items.add("notebook");
items.add("class");
UnaryOperator<String> uo = (x) -> x.toUpperCase();
items.replaceAll(uo);
System.out.println(items);
}
The example applies an operator on each of the list elements; the elements' letters are transformed to uppercase. UnaryOperator<String> uo = (x) -> x.toUpperCase();
A items.replaceAll(uo);
The operator is applied on the list elements with the $ java Main.java [COIN, PEN, CUP, NOTEBOOK, CLASS]
The second example uses the Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;
class MyOperator<T> implements UnaryOperator<String> {
@Override
public String apply(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
void main() {
List<String> items = new ArrayList<>();
items.add("coin");
items.add("pen");
items.add("cup");
items.add("notebook");
items.add("glass");
items.replaceAll(new MyOperator<>());
System.out.println(items);
}
We have a list of string items. These items are capitalized with the
help of the class MyOperator<T> implements UnaryOperator<String> {
A custom @Override
public String apply(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
Inside the items.replaceAll(new MyOperator<>()); The operator is applied on the list items. $ java Main.java [Coin, Pen, Cup, Notebook, Glass] The contains method
The Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> items = new ArrayList<>();
items.add("coin");
items.add("pen");
items.add("cup");
items.add("notebook");
items.add("class");
String item = "pen";
if (items.contains(item)) {
System.out.printf("There is a %s in the list%n", item);
}
}
The example checks if the specified item is in the list. if (items.contains(item)) {
System.out.printf("There is a %s in the list%n", item);
}
The message is printed if the item is in the list. $ java Main.java There is a pen in the list Getting index of elements
Each of the elements in an Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> colours = new ArrayList<>();
colours.add(0, "blue");
colours.add(1, "orange");
colours.add(2, "red");
colours.add(3, "green");
colours.add(4, "orange");
int idx1 = colours.indexOf("orange");
System.out.println(idx1);
int idx2 = colours.lastIndexOf("orange");
System.out.println(idx2);
}
The example prints the first and last index of the "orange" element. $ java Main.java 1 4 List of listsWe can add other lists into a list. Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<Integer> l1 = new ArrayList<>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2 = new ArrayList<>();
l2.add(4);
l2.add(5);
l2.add(6);
List<Integer> l3 = new ArrayList<>();
l3.add(7);
l3.add(8);
l3.add(9);
List<List<Integer>> nums = new ArrayList<>();
nums.add(l1);
nums.add(l2);
nums.add(l3);
System.out.println(nums);
for (List<Integer> list : nums) {
for (Integer n : list) {
System.out.printf("%d ", n);
}
System.out.println();
}
}
The example creates three lists of integers. Later, the lists are added into another fourth list. List<Integer> l1 = new ArrayList<>(); l1.add(1); l1.add(2); l1.add(3); A list of integers is created. List<List> nums = new ArrayList<>(); nums.add(l1); nums.add(l2); nums.add(l3); A list of lists is created. for (List<Integer> list : nums) {
for (Integer n : list) {
System.out.printf("%d ", n);
}
System.out.println();
}
We use two for loops to go through all the elements. $ java Main.java [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 1 2 3 4 5 6 7 8 9 The subList method
The Main.java
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> items = new ArrayList<>();
items.add("coin");
items.add("pen");
items.add("cup");
items.add("notebook");
items.add("glass");
items.add("chair");
items.add("ball");
items.add("bowl");
List<String> items2 = items.subList(2, 5);
System.out.println(items2);
items2.set(0, "bottle");
System.out.println(items2);
System.out.println(items);
}
The example creates a sublist from a list of items. List<String> items2 = items.subList(2, 5);
A sublist is created with the items2.set(0, "bottle"); We replace the first item of the sublist; the modification is reflected in the original list, too. $ java Main.java [cup, notebook, glass] [bottle, notebook, glass] [coin, pen, bottle, notebook, glass, chair, ball, bowl] Traversing elements
In the following example, we show five ways to traverse an Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
void main() {
List<Integer> nums = new ArrayList<>();
nums.add(2);
nums.add(6);
nums.add(7);
nums.add(3);
nums.add(1);
nums.add(8);
for (int i = 0; i < nums.size(); i++) {
System.out.printf("%d ", nums.get(i));
}
System.out.println();
for (int num : nums) {
System.out.printf("%d ", num);
}
System.out.println();
int j = 0;
while (j < nums.size()) {
System.out.printf("%d ", nums.get(j));
j++;
}
System.out.println();
ListIterator<Integer> it = nums.listIterator();
while(it.hasNext()) {
System.out.printf("%d ", it.next());
}
System.out.println();
nums.forEach(e -> System.out.printf("%d ", e));
System.out.println();
}
In the example, we traverse an array list of integers with for loops, while loop,
iterator, and List<Integer> nums = new ArrayList<>(); nums.add(2); nums.add(6); nums.add(7); nums.add(3); nums.add(1); nums.add(8);
We have created an for (int i = 0; i < nums.size(); i++) {
System.out.printf("%d ", nums.get(i));
}
Here, we use the classic for loop to iterate over the list. for (int num : nums) {
System.out.printf("%d ", num);
}
The second way uses the enhanced-for loop, which was introduced int Java 5. int j = 0;
while (j < nums.size()) {
System.out.printf("%d ", nums.get(j));
j++;
}
The third way uses the while loop. ListIterator<Integer> it = nums.listIterator();
while(it.hasNext()) {
System.out.printf("%d ", it.next());
}
Here, a nums.forEach(e -> System.out.printf("%d ", e));
In the last way, we use the $ java Main.java 2 6 7 3 1 8 2 6 7 3 1 8 2 6 7 3 1 8 2 6 7 3 1 8 2 6 7 3 1 8 Sorting elements
There are different ways to sort an Sorting with the sort method
The Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
void main() {
List<Person> persons = createList();
persons.sort(Comparator.comparing(Person::age).reversed());
System.out.println(persons);
}
List<Person> createList() {
List<Person> persons = new ArrayList<>();
persons.add(new Person(17, "Jane"));
persons.add(new Person(32, "Peter"));
persons.add(new Person(47, "Patrick"));
persons.add(new Person(22, "Mary"));
persons.add(new Person(39, "Robert"));
persons.add(new Person(54, "Greg"));
return persons;
}
record Person(int age, String name) {}
We have an persons.sort(Comparator.comparing(Person::age).reversed()); This line sorts the persons by their age, from the oldest to the youngest. $ java Main.java
[Age: 54 Name: Greg, Age: 47 Name: Patrick, Age: 39 Name: Robert, Age: 32 Name: Peter,
Age: 22 Name: Mary, Age: 17 Name: Jane]
Sorting elements using stream
In the second example, we use Java stream to sort the Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
void main() {
List<Country> countries = createList();
List<Country> sorted_countries = countries.stream()
.sorted((e1, e2) -> Integer.compare(e1.population,
e2.population))
.collect(Collectors.toList());
System.out.println(sorted_countries);
}
List<Country> createList() {
List<Country> countries = new ArrayList<>();
countries.add(new Country("Slovakia", 5424000));
countries.add(new Country("Hungary", 9845000));
countries.add(new Country("Poland", 38485000));
countries.add(new Country("Germany", 81084000));
countries.add(new Country("Latvia", 1978000));
return countries;
}
record Country(String name, int population) {
}
In this example, we have a list of countries. Each country has a name and population. The countries are sorted by population. List<Country> sorted_countries = countries.stream()
.sorted((e1, e2) -> Integer.compare(e1.population,
e2.population))
.collect(Collectors.toList());
With the $ java Main.java
[Country{name=Latvia, population=1978000}, Country{name=Slovakia, population=5424000},
Country{name=Hungary, population=9845000}, Country{name=Poland, population=38485000},
Country{name=Germany, population=81084000}]
The countries are sorted by their population in ascending mode. Working with ArrayList and simple Java array
The following example uses an Main.java
import java.util.Arrays;
import java.util.List;
void main() {
String[] a = new String[] { "Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
List<String> planets = List.of(a);
System.out.println(planets);
String[] planets2 = planets.toArray(new String[0]);
System.out.println(Arrays.toString(planets2));
}
An String[] a = new String[] { "Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
We have an array of strings. List<String> planets = List.of(a);
We generate an immutable list from the array with String[] planets2 = planets.toArray(new String[0]);
The Stream to listJava streams can be converted to lists using collectors. Main.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
void main() {
var words = Stream.of("forest", "eagle", "river", "cloud", "sky");
List<String> words2 = words.collect(Collectors.toList());
System.out.println(words2.getClass());
}
We have a stream of strings. We convert the stream to a list with
$ java Main.java class java.util.ArrayList
In this article we have worked with the Java SourceJava ArrayList - language reference AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |