Java – How to remove items from a List while iterating?

In Java, if we remove items from a List while iterating it, it will throw java.util.ConcurrentModificationException. This article shows a few ways to solve it. Table of contents 1. java.util.ConcurrentModificationException 2. Java 8 Collection#removeIf 2.1 removeIf examples 2.2 removeIf uses Iterator 3. ListIterator example 4. Filter and Collect example 5. References P.S Tested with Java …

Read more

Java 8 – How to convert Iterator to Stream

In Java 8, we can use StreamSupport.stream to convert an Iterator into a Stream. // Iterator -> Spliterators -> Stream Stream<String> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED) , false); Review the StreamSupport.stream method signature, it accepts a Spliterator. StreamSupport.java public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) { Objects.requireNonNull(spliterator); return new ReferencePipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), parallel); } …

Read more

Java Iterator examples

A few of Java Iterator and ListIterator examples. 1. Iterator 1.1 Get Iterator from a List or Set, and loop over it. JavaIteratorExample1a.java package com.mkyong; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class JavaIteratorExample1a { public static void main(String[] args) { /* Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(4); set.add(5); Iterator<Integer> iterator = …

Read more

Java – How to Iterate a HashMap

In Java, there are 3 ways to loop or iterate a HashMap 1. If possible, always uses the Java 8 forEach. Map<String, String> map = new HashMap<>(); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); 2. Normal for loop in entrySet() Map<String, String> map = new HashMap<>(); for …

Read more

Java – How to get the first item from Set

In Java, we can use Set.iterator().next() to get the first item from a java.util.Set JavaExample.java package com.mkyong; import java.util.HashSet; import java.util.Set; public class JavaExample { public static void main(String[] args) { Set<String> examples = new HashSet<>(); examples.add("1"); examples.add("2"); examples.add("3"); examples.add("4"); examples.add("5"); System.out.println(examples.iterator().next()); // java 8 System.out.println(examples.stream().findFirst().get()); } } Output 1 1 References Oracle doc – …

Read more