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 List throws UnsupportedOperationException

Typically, we use Arrays.asList or the new Java 9 List.of to create a List. However, both methods return a fixed size or immutable List, it means we can’t modify it, else it throws UnsupportedOperationException. JavaListExample.java package com.mkyong; import java.util.Arrays; import java.util.List; public class JavaListExample { public static void main(String[] args) { // immutable list, cant …

Read more

What is java.util.Arrays$ArrayList?

The java.util.Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array. Arrays.java public static <T> List<T> asList(T… a) { return new ArrayList<>(a); } /** * @serial include */ private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = …

Read more

Java – How to search a string in a List?

In Java, we can combine a normal loop and .contains(), .startsWith() or .matches() to search for a string in ArrayList. JavaExample1.java package com.mkyong.test; import java.util.ArrayList; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Kotlin"); list.add("Clojure"); list.add("Groovy"); list.add("Scala"); List<String> result = new ArrayList<>(); for (String s …

Read more

Python – Get the last element of a list

In Python, we can use index -1 to get the last element of a list. #!/usr/bin/python nums = [1, 2, 3, 4, 5] print(nums[-1]) print(nums[-2]) print(nums[-3]) print(nums[-4]) print(nums[-5]) print(nums[0]) print(nums[1]) print(nums[2]) print(nums[3]) print(nums[4]) Output 5 4 3 2 1 1 2 3 4 5 Yet another example. #!/usr/bin/python # getting list of nums from the …

Read more

Java – Get the last element of a list

In Java, index starts at 0, we can get the last index of a list via this formula: list.size() – 1 JavaExample1.java package com.mkyong.test; import java.util.Arrays; import java.util.List; public class JavaExample1 { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); System.out.println(list.get(list.size() – 1)); System.out.println(list.get(list.size() – 2)); System.out.println(list.get(list.size() – 3)); …

Read more

Java – Convert ArrayList<String> to String[]

In the old days, we can use list.toArray(new String[0]) to convert a ArrayList<String> into a String[] StringArrayExample.java package com.mkyong; import java.util.ArrayList; import java.util.List; public class StringArrayExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); // default, returns Object[], not what we want, // Object[] objects = list.toArray(); // …

Read more

Java List java.lang.UnsupportedOperationException

A simple List.add() and hits the following java.lang.UnsupportedOperationException ListExample.java package com.mkyong; import java.util.Arrays; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> str = Arrays.asList("A", "B", "C"); str.add("D"); System.out.println(str); } } Output Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractList.add(AbstractList.java:153) at java.base/java.util.AbstractList.add(AbstractList.java:111) at com.mkyong.ListExample.main(ListExample.java:14) Solution The Arrays.asList returns a fixed-size list, modify …

Read more

Java – Count the number of items in a List

In Java, we can use List.size() to count the number of items in a List package com.mkyong.example; import java.util.Arrays; import java.util.List; public class JavaExample { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b", "c"); System.out.println(list.size()); } } Output 3 References Java doc – List

Java 8 – Convert a Stream to List

A Java 8 example to show you how to convert a Stream to a List via Collectors.toList Java8Example1.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Example1 { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node"); //Convert a Stream to List List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output …

Read more

Java 8 – Convert Map to List

Few Java examples to convert a Map to a List Map<String, String> map = new HashMap<>(); // Convert all Map keys to a List List<String> result = new ArrayList(map.keySet()); // Convert all Map values to a List List<String> result2 = new ArrayList(map.values()); // Java 8, Convert all Map keys to a List List<String> result3 = …

Read more

JUnit – How to test a List

First, exclude the JUnit bundled copy of hamcrest-core, and include the useful hamcrest-library, it contains many useful methods to test the List data type. pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <!– This will get hamcrest-core automatically –> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> </dependencies> 1. Assert List …

Read more

Java 8 – Convert List to Map

Few Java 8 examples to show you how to convert a List of objects into a Map, and how to handle the duplicated keys. Hosting.java package com.mkyong.java8 public class Hosting { private int Id; private String name; private long websites; public Hosting(int id, String name, long websites) { Id = id; this.name = name; this.websites …

Read more

Spring @Value – Import a list from properties file

In this tutorial, we will show you how to import a “List” from a properties file, via Spring EL @Value Tested with : Spring 4.0.6 JDK 1.7 Spring @Value and List In Spring @Value, you can use the split() method to inject the ‘List” in one line. config.properties server.name=hydra,zeus server.id=100,102,103 AppConfigTest.java package com.mkyong.analyzer.test; import java.util.List; …

Read more

jQuery and Java List example

There is no direct way to iterate over a Java List with jQuery, see the following case study : Spring controller @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView getPages() { List<String> list = new ArrayList<String>(); list.add("List A"); list.add("List B"); list.add("List C"); list.add("List D"); list.add("List E"); ModelAndView model = new ModelAndView("somepage"); model.addObject("list", list); return model; …

Read more

Spring MVC and List Example

In this tutorial, we show you how to print the List values via JSTL c:forEach tag. P.S This web project is using Spring MVC frameworks v3.2 1. Project Structure Review the project directory structure, a standard Maven project. 2. Project Dependencies Add Spring and JSTL libraries. pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <!– jstl –> …

Read more

How to join two Lists in Java

In this article, we show you 2 examples to join two lists in Java. JDK – List.addAll() Apache Common – ListUtils.union() 1. List.addAll() example Just combine two lists with List.addAll(). JoinListsExample.java package com.mkyong.example; import java.util.ArrayList; import java.util.List; public class JoinListsExample { public static void main(String[] args) { List<String> listA = new ArrayList<String>(); listA.add("A"); List<String> listB …

Read more

How to count duplicated items in Java List

A Java example to show you how to count the total number of duplicated entries in a List, using Collections.frequency and Map. CountDuplicatedList.java package com.mkyong; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class CountDuplicatedList { public static void main(String[] args) { List<String> list = new …

Read more

Spring EL Lists, Maps example

In this article, we show you how to use Spring EL to get value from Map and List. Actually, the way of SpEL works with Map and List is exactly same with Java. See example : //get map whete key = ‘MapA’ @Value("#{testBean.map[‘MapA’]}") private String mapA; //get first value from list, list is 0-based. @Value("#{testBean.list[0]}") …

Read more

What is the different between Set and List

Set and List explanation Set – Stored elements in unordered or shuffles way, and does not allow duplicate values. List – Stored elements in ordered way, and allow duplicate values. Set and List Example import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SetAndListExample { public static void main( String[] args ) { System.out.println("List …

Read more

How to loop / iterate a List in Java

Here i show you four ways to loop a List in Java. Iterator loop For loop For loop (Adcance) While loop package com.mkyong.core; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class ArrayToList { public static void main(String[] argv) { String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" }; // convert array …

Read more

How to convert Array to List in Java

Java example to show you how to convert a Array to a List ArrayToList.java package com.mkyong; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ArrayToList { public static void main(String[] argv) { String sArray[] = new String[] { "A", "B", "C" }; // convert array to list #1 List<String> list = Arrays.asList(sArray); System.out.println(list); …

Read more