ArrayList of two strings in java
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList Output In the above example, we have created an arraylist named languages. Notice the line, Here, the toString() method converts arraylist into a string. The entire arraylist is converted as a single string. Note: We can also convert the arraylist into a string array. To learn more, visit Java ArrayList to Array Conversion. Output In the above example, we have used the join() method of the String class to convert the arraylist into a string. To learn more, visit Java String join(). Output In the above example, we have created a string named str. We have used the split() method to convert the given string into an array. To learn more about splitting a string, visit Java String split(). Notice the expression, The asList() method converts the string array into an arraylist.
ArrayList class in Java is basically a resize-able array i.e. it can grow and shrink in size dynamically according to the values that we add to it. It is present in java.util package. Syntax: ArrayListAn ArrayList in java can be instantiated once with the help of the ‘new’ keyword and can be referred to by various objects/variables. The figure above shows how the object ‘list’ points to the ArrayList inside the memory. Now let us see how we can make another object to point to the same ArrayList that is instantiated above. Syntax: Two variables refer to the same ArrayList: ArrayListNow when assigned the ‘list’ to the ‘secondList’ then the ‘secondList’ also starts pointing to the same ArrayList inside the memory. Notice here simply create a new instance. Now, for a better understanding let’s dive into code and see a few examples. Below is the implementation of the problem statement:
Output ArrayList after insertions: 17 10 1 33 2 ArrayList after modifications using secondList: 10 1 33 2 51 99 Article Tags : Learn to add multiple items to an ArrayList in a single statement using simple to follow Java examples. 1. Arrays.asList() – Initializing with Multiple ItemsTo initialize an ArrayList with multiple items in a single line can be done by creating a List of items using Arrays.asList(), and passing the List to the ArrayList constructor. In the given example, we are adding two strings “a” and “b” to the ArrayList. ArrayList2. Collections.addAll() – Add Multiple Items to Existing ArrayListTo add all items from another collection to this ArrayList, we can use Collections.addAll() method that adds all of the specified items to the given list. Note that the items to be added may be specified individually or as an array. ArrayListAlternatively, we can use ArrayList constructor that accepts a collection and initializes the ArrayList with the items from the argument collection. This can be useful if we are adding the whole collection into this ArrayList. List3. Stream API – Adding Selected Items to ArrayListThis method uses Java Stream API. We create a stream of elements from the first list, add a filter() to get the desired elements only, and then add the filtered elements to another list. In the above examples, we learned to all multiple elements to ArrayList. We have added all elements to ArrayList and then we saw the example to add only selected items to the ArrayList from the Java 8 stream API. Happy Learning !!
Let us know if you liked the post. That’s the only way we can improve.
last modified November 12, 2021 Java ArrayList tutorial shows how to work with ArrayList collection in Java. Located in the java.util package, ArrayList is an important collection of the Java collections framework. Java collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A collection is an object that represents a group of objects. ArrayList is an ordered sequence of elements. It is dynamic and resizable. It provides random access to its elements. Random access means that we can grab any element at constant time. An ArrayList automatically expands as data is added. Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null. Elements in the ArrayList are accessed via an integer index. Indexes are zero-based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time. An ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList, its capacity grows automatically. Choosing a proper capacity can save some time. Java ArrayList adding single itemsSingle elements can be added to an ArrayList with the add method. com/zetcode/ListAddItem.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class ListAddItem { public static void main(String[] args) { ListThe example adds elements to an array list one by one. ListAn ArrayList is created. The data type specified inside the diamond brackets (< >) restricts the elements to this data type; in our case, we have a list of strings. langs.add("Java");An element is appended at the end of the list with the add method. langs.add(1, "C#");This time the overloaded add method inserts the element at the specified position; The "C#" string will be located at the second position of the list; remember, the ArrayList is an ordered sequence of elements. for (String lang : langs) { System.out.printf("%s ", lang); }With the for loop, we go through the ArrayList list and print its elements. Ruby Java C# PythonNote that the elements keep the order they were inserted. Java List.ofSince Java 9, we have a couple of factory methods for creating lists having a handful of elements. The created list is immutable. com/zetcode/ListOf.java package com.zetcode; import java.util.List; public class ListOf { public static void main(String[] args) { var words = List.of("wood", "forest", "falcon", "eagle"); System.out.println(words); var values = List.of(1, 2, 3); System.out.println(values); } }In the example, we create two lists that have four and three elements. Java ArrayList get() and size()The get returns the element at the specified position in this list and the size returns the size of the list. com/zetcode/GetAndSizeEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class GetAndSizeEx { public static void main(String[] args) { ListThe example uses the get and size methods of the ArrayList String col = colours.get(1);The get method returns the second element, which is "orange". int size = colours.size();The size method determines the size of our colours list; we have four elements. orange The size of the ArrayList is: 4Java ArrayList copyA copy of a list can be generated with List.copy method. com/zetcode/ListCopy.java package com.zetcode; import java.util.List; public class ListCopy { public static void main(String[] args) { var words = List.of("forest", "wood", "eagle", "sky", "cloud"); System.out.println(words); var words2 = List.copyOf(words); System.out.println(words2); } }The example creates a copy of a list with List.copy. Raw ArrayListAn ArrayList can contain various data types. These are called raw lists. Note: It is generally not recommended to use raw lists. Raw lists often require casts and they are not type safe. com/zetcode/DataTypesEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; class Base {} enum Level { EASY, MEDIUM, HARD } public class DataTypesEx { public static void main(String[] args) { Level level = Level.EASY; List da = new ArrayList(); da.add("Java"); da.add(3.5); da.add(55); da.add(new Base()); da.add(level); for (Object el : da) { System.out.println(el); } } }The example adds five different data types into an array list — a string, double, integer, object, and enumeration. List da = new ArrayList();When we add multiple data types to a list, we omit the angle brackets. Java 3.5 55 com.zetcode.Base@659e0bfd EASYJava ArrayList add multiple elementsThe following example uses the addAll method to add multiple elements to a list in one step. com/zetcode/AddingMultipleItemsEx.java Two lists are created. Later, the elements of the lists are added to the third list with the addAll method. colours3.addAll(colours1);The addAll method adds all of the elements to the end of the list. colours3.addAll(2, colours2);This overloaded method adds all of the elements starting at the specified position. white orange yellow pink brown blue red greenJava ArrayList modifying elementsThe next example uses methods to modify the ArrayList. com/zetcode/ModifyingListEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class ModifyingListEx { public static void main(String[] args) { ListAn ArrayList is created and modified with the set, add, remove, and clear methods. items.set(3, "watch");The set method replaces the fourth element with the "watch" item. items.add("bowl");The add method adds a new element at the end of the list. items.remove(0);The remove method removes the first element, having index 0. items.remove("pen");The overloaded remove method remove the first occurrence of the "pen" item. items.clear();The clear method removes all elements from the list. if (items.isEmpty()) {The isEmpty method determines if the list is empty. pencil watch book spectacles glass bowl The list is emptyJava ArrayList removeIfThe removeIf method removes all of the elements of a collection that satisfy the given predicate. com/zetcode/RemoveIfEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class RemoveIfEx { public static void main(String[] args) { ListIn our example, we have an ArrayList of integers. We use the removeIf method to delete all negative values. values.removeIf(val -> val < 0);All negative numbers are removed from the array list. [5, 2, 8, 6]Java ArrayList removeAllThe removeAll method removes from this list all of its elements that are contained in the specified collection. Note that all elements are removed with clear. com/zetcode/RemoveAll.java package com.zetcode; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RemoveAll { public static void main(String[] args) { ListIn the example, we remove all "a" letters from the list. Java ArrayList replaceAllThe replaceAll method replaces each element of a list with the result of applying the operator to that element. com/zetcode/ReplaceAllEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.UnaryOperator; public class ReplaceAllEx { public static void main(String[] args) { ListThe example applies an operator on each of the list elements; the elements' letters are transformed to uppercase. UnaryOperatorA UnaryOperator that transforms letters to uppercase is created. items.replaceAll(uo);The operator is applied on the list elements with the replaceAll method. [COIN, PEN, CUP, NOTEBOOK, CLASS]The second example uses the replaceAll method to capitalize string items. com/zetcode/ReplaceAllEx2.java package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.UnaryOperator; class MyOperatorWe have a list of string items. These items are capitalized with the help of the replaceAll method. class MyOperatorA custom UnaryOperator is created. @Override public String apply(String var) { if (var == null || var.length() == 0) { return var; } return var.substring(0, 1).toUpperCase() + var.substring(1); }Inside the UnaryOperator's apply method, we retur the string with its first letter in uppercase. items.replaceAll(new MyOperator<>());The operator is applied on the list items. [Coin, Pen, Cup, Notebook, Glass]The contains method returns true if a list contains the specified element. com/zetcode/ContainsEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class ContainsEx { public static void main(String[] args) { ListThe example checks if the specified item is in the list. if (items.contains(item)) { System.out.printf("There is a %s in the list%n", item); }The message is printed if the item is in the list. There is a pen in the listGetting index of elements in ArrayListEach of the elements in an ArrayList has its own index number. The indexOf returns the index of the first occurrence of the specified element, or -1 if the list does not contain the element. The lasindexOf returns the index of the last occurrence of the specified element, or -1 if the list does not contain the element. com/zetcode/GetIndexEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class GetIndexEx { public static void main(String[] args) { ListThe example prints the first and last index of the "orange" element. 1 4Java list of listsWe can add other lists into a list. com/zetcode/ListOfLists.java
The example creates three lists of integers. Later, the lists are added into another fourth list. ListA list of integers is created. List
A list of lists is created. for (ListWe use two for loops to go through all the elements. [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 1 2 3 4 5 6 7 8 9Java ArrayList subListThe subList method returns a view of the portion of a list between the specified fromIndex, inclusive, and toIndex, exclusive. The changes in a sublist are reflected in the original list. com/zetcode/SubListEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; public class SubListEx { public static void main(String[] args) { ListThe example creates a sublist from a list of items. ListA sublist is created with the subList method; it contains items with indexes 2, 3, and 4. items2.set(0, "bottle");We replace the first item of the sublist; the modification is reflected in the original list, too. [cup, notebook, glass] [bottle, notebook, glass] [coin, pen, bottle, notebook, glass, chair, ball, bowl]Java ArrayList traversingIn the following example, we show five ways to traverse an ArrayList. com/zetcode/TraversingArrayListEx.java package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class TraversingArrayListEx { public static void main(String[] args) { ListIn the example, we traverse an array list of integers with for loops, while loop, iterator, and forEach construct. ListWe have created an ArrayList of integers. for (int i = 0; i < nums.size(); i++) { System.out.printf("%d ", nums.get(i)); }Here, we use the classic for loop to iterate over the list. for (int num : nums) { System.out.printf("%d ", num); }The second way uses the enhanced-for loop, which was introduced int Java 5. int j = 0; while (j < nums.size()) { System.out.printf("%d ", nums.get(j)); j++; }The third way uses the while loop. ListIteratorHere, a ListIterator is used to traverse the list. nums.forEach(e -> System.out.printf("%d ", e));In the last way, we use the forEach method, which was introduced in Java 8. 2 6 7 3 1 8 2 6 7 3 1 8 2 6 7 3 1 8 2 6 7 3 1 8 2 6 7 3 1 8The example prints the elements of a list to the console, utilizing various techniques. Java ArrayList sortingThere are different wasy to sort an ArrayList. Sorting ArrayList with its sort methodThe ArrayList's sort method sorts a list according to the order induced by the specified comparator. com/zetcode/ArrayListSortingEx.java package com.zetcode; import java.util.ArrayList; import java.util.Comparator; import java.util.List; class Person { private int age; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } @Override public String toString() { return "Age: " + age + " Name: " + name; } } public class ArrayListSortingEx { public static void main(String[] args) { ListWe have an ArrayList of custom Person classes. We sort the persons according to their age in a reversed order. persons.sort(Comparator.comparing(Person::getAge).reversed());This line sorts the persons by their age, from the oldest to the youngest. [Age: 54 Name: Greg, Age: 47 Name: Patrick, Age: 39 Name: Robert, Age: 32 Name: Peter, Age: 22 Name: Mary, Age: 17 Name: Jane]Sorting ArrayList with Java 8 streamIn the second example, we use Java stream to sort the ArrayList. Streams API is a more powerful way to do sorting. com/zetcode/ArrayListSortingEx2.java package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; class Country { private String name; private int population; public Country(String name, int population) { this.name = name; this.population = population; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public String toString() { return "Country{" + "name=" + name + ", population=" + population + '}'; } } public class ArrayListSortingEx2 { public static void main(String[] args) { ListIn this example, we have a list of countries. Each country has a name and population. The countries are sorted by population. ListWith the stream method, we create a stream from a list. The sorted method sorts elements according to the provided comparator. With Integer.compare we compare the populations of countries. With collect, we transform the stream into a list of countries. [Country{name=Latvia, population=1978000}, Country{name=Slovakia, population=5424000}, Country{name=Hungary, population=9845000}, Country{name=Poland, population=38485000}, Country{name=Germany, population=81084000}]The countries are sorted by their population in ascending mode. Working with ArrayList and simple Java arrayThe following example uses an ArrayList with a simple Java array. com/zetcode/ListToArray.java package com.zetcode; import java.util.Arrays; import java.util.List; public class ListToArray { public static void main(String[] args) { ListAn ArrayList is converted to an array and vice versa. ListWith the Arrays.asList method, we create a fixed-size list backed by the specified array. String[] planets2 = planets.toArray(new String[0]);The ArrayList's toArray is used to convert a list to an array. Stream to listJava streams can be converted to lists using collectors. com/zetcode/ToList.java package com.zetcode; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ToList { public static void main(String[] args) { var words = Stream.of("forest", "eagle", "river", "cloud", "sky"); ListWe have a stream of strings. We convert the stream to a list with Collectors.toList. class java.util.ArrayListIn this tutorial, we have worked with the Java ArrayList container. List all Java tutorials. |