Java 8 ArrayList examples create forEach shuffle
ArrayList is important data structure for many computer languages. Java's ArrayList is used to store lists of numerical data and to represent vectors, matrices, tables. ArrayList is designed to handle variety of different data and it's considered with relatively good performance(for rational size). The java arraylist has a good set of methods for creating, manipulating, shuffling, sorting and iterating over arrays.
Create ArrayList
There are many ways to create and populate ArrayList in Java 8. Here you can find several:
create arraylist of Objects
Objects are from type Language and add members with list.add:
List<Language> list = new ArrayList<>();
list.add(new Language(1, "Java7"));
list.add(new Language(2, "Java8"));
create ArrayList of Strings
and add members with method asList:
List<String> list = Arrays.asList("Java7", "Java8", "Java9");
Iterate ArrayList
In Java 8 you can iterate over ArrayList in several ways:
using simple for loop:
List<String> list = Arrays.asList("Java7", "Java8", "Java9");
for(String element : list){
System.out.println(element);
}
using forEach:
List<String> list = Arrays.asList("Java7", "Java8", "Java9");
list.forEach(element->System.out.println(element));
Output:
Java7, Java8, Java9
Using method reference:
List<String> list = Arrays.asList("Java7", "Java8", "Java9");
list.forEach(System.out::println);
Output:
Java7, Java8, Java9
Search in ArrayList
You can easily search in array list as shown from the examples:
using forEach:
List<String> list = Arrays.asList("Java7", "Java8", "Java9");
list.forEach(element->{
if("Java8".equals(element)){
System.out.println(element);
}
});
Output:
Java8
Using method reference:
List<String> list = Arrays.asList("Java7", "Java8", "Java9");
list.stream()
.filter(s->s.contains("Java9"))
.forEach(System.out::println);
Output:
Java9
Randomize ArrayList
Shuffling or randomizing an ArrayList can be done by using Collections :
import java.util.Collections;
Collections.shuffle(list);