Skip links

What are common list operations in Java using "Java list of"?

Using “Java List of” Construct:

In Java, the “java list of” construct refers to creating a list of elements using the “java.util.List” interface and its implementations such as “ArrayList”, “LinkedList”, etc. This construct allows you to store and manipulate collections of elements dynamically.

Use Case 1: Creating a List of Strings

import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create a list of strings using ArrayList List<String> stringList = new ArrayList<>(); // Add elements to the list stringList.add(“Apple”); stringList.add(“Banana”); stringList.add(“Orange”); // Print the list System.out.println(“List of strings: ” + stringList); } } In this example, we create a list of strings using the `ArrayList` implementation of the `List` interface. We add elements to the list and then print the entire list.

Use Case 2: Manipulating a List of Integers

import java.util.List; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { // Create a list of integers using ArrayList List<Integer> integerList = new ArrayList<>(); // Add elements to the list integerList.add(5); integerList.add(3); integerList.add(8); integerList.add(2); // Sort the list Collections.sort(integerList); // Print the sorted list System.out.println(“Sorted list of integers: ” + integerList); } } Here, we create a list of integers using `ArrayList`, add elements to the list, and then use `Collections.sort()` method to sort the list in ascending order. Finally, we print the sorted list.

Conclusion:

The “java list of” construct allows you to work with collections of elements in Java efficiently. Whether you’re storing strings, integers, or objects, you can use various implementations of the `List` interface to create, manipulate, and perform operations on lists of elements. Examples include adding elements, removing elements, accessing elements by index, sorting lists, and more.