Skip to content
On this page

Menggunakan ForEach Java

Melakukan print semua data collections

java
List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
 alphabets.forEach(s -> System.out.println(s)); 
java
List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
 alphabets.forEach(System.out::println); 
java
List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
 alphabets.forEach(s -> System.out.print(s + ",")); 

Menggunakan filter dan forEach

case code 1: mengambil data dengan awalan "d"
case code 2: mengambil data yang jumlah katanya lebih dari 2

java
List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
    alphabets.stream()
        .filter(s -> s.startsWith("d")) 
        .forEach(System.out::println); 
java
List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
    alphabets.stream()
        .filter(s -> s.length() > 2) 
        .forEach(System.out::println); 

Menggunakan map dan forEach

menghitung jumlah kata

java
List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
    alphabets.stream()
        .mapToInt(s -> s.length()) 
        .forEach(System.out::println); 

Ambil data foreach ke list

java
List<String> itemsList = new ArrayList<>(); 
for (int i = 0; i < itemsArray.length(); i++) { 
    itemsList.add(itemsArray.getString(i)); 
}
java
List<String> itemsList = new ArrayList<>();
itemsArray.forEach(item -> itemsList.add(item.toString()));
java
List<String> itemsList = new ArrayList<>();
itemsArray.forEach(itemsList::add);
java
List<String> itemsList = new ArrayList<>();
itemsArray.forEach(item -> {
    if (item instanceof String) {
        itemsList.add((String) item);
    }
});