Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Saturday, November 27, 2021

Java - Create and Iterate List of Lists With Examples

1. Overview

In this tutorial, We'll learn how to create the List of Lists and iterate them in java and the newer java 8 version with simple example programs.


This is like List is holding another list of strings or list of integers or in some cases it can be user-defined custom objects.

Let us look at each type of object creation and loop through them in java.

Java - Create and Iterate List of Lists With Examples

Wednesday, November 17, 2021

Java ArrayList Add() - How to add values to ArrayList?

How to add values to ArrayList?

In this post, we will learn how to add elements to ArrayList using java inbuilt methods. ArrayList class in java has been implemented based on the growable array which will be resized size automatically. Maintains the order of insertion of values added to it and permits adding all kinds of values including primitives, user-defined classes, wrapper classes and null values.

java arraylist add


Java ArrayList add methods:

Java ArrayList add method is overloaded and the following are the methods defined in it.

1) public boolean add(E e)
2) public void add(int index, E element)

Thursday, November 11, 2021

Java 8 - Converting a List to String with Examples

1. Overview

In this tutorial, we will learn how to convert List to String in java with example programs.

This conversion is done with the simple steps with java api methods.


First, we will understand how to make List to String using toString() method.
Next, Collection to String with comma separator or custom delimiter using Java 8 Streams Collectors api and String.join() method.
Finally, learn with famous library apache commands StringUtils.join() method.

For all the examples, input list must be a type of String as List<String> otherwise we need to convert the non string to String. Example, List is type of Double then need to convert then double to string first.

Java 8 Streams- Converting a List to String with Examples.png



2. List to String Using Standard toString() method


List.toString() is the simplest one but it adds the square brackets at the start and end with each string is separated with comma separator.

The drawback is that we can not replace the comma with another separator and can not remove the square brackets.

package com.javaprogramto.convert.list2string;

import java.util.Arrays;
import java.util.List;

/**
 * Example to convert List to string using toString() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingToStringExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");
	
	// converting List<String> to String using toString() method
	String stringFromList = list.toString();
	
	// priting the string
	System.out.println("String : "+stringFromList);		
	}
}
 
Output:

String : [One, Two, Three, Four, Five]

 

3. List to String Using Java 8 String.join() Method


The above program works before java 8 and after. But, java 8 String is added with a special method String.join() to convert the collection to a string with a given delimiter.

The below example is with the pipe and tilde separators in the string.

import java.util.Arrays;
import java.util.List;

/**
 * Example to convert List to string using String.join() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingString_JoinExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");
	
	// converting List<String> to String using toString() method
	String stringFromList = String.join("~", list);
	
	// priting the string
	System.out.println("String with tilde delimiter: "+stringFromList);
	
	// delimiting with pipe | symbol.
	String stringPipe = String.join("|", list);
	
	// printing
	System.out.println("String with pipe delimiter : "+stringPipe);
	
	}
}

 
Output:
String with tilde delimiter: One~Two~Three~Four~Five
String with pipe delimiter : One|Two|Three|Four|Five

 

4. List to String Using Java 8 Collectors.joining() Method


Collectors.join() method is from java 8 stream api. Collctors.joining() method takes delimiter, prefix and suffix as arguments. This method converts list to string with the given delimiter, prefix and suffix.

Look at the below examples on joining() method with different delimiters. But, String.join() method does not provide the prefix and suffix options.

If you need a custom delimiter, prefix and suffix then go with these. If you do not want the prefix and suffix then provide empty string to not to add any before and after the result string.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Example to convert List to string using Collectors.joining() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingString_JoinExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");

	// using java 8 Collectors.joining with delimiter, prefix and suffix
	String joiningString = list.stream().collect(Collectors.joining("-", "{", "}"));
	
	// printing
	System.out.println("Collectors.joining string : "+joiningString);
	
	String joiningString3 = list.stream().collect(Collectors.joining("@", "", ""));
	
	// printing
	System.out.println("Collectors.joining string with @ separator : "+joiningString3);
	
	
	}
}
 
Output:
Collectors.joining string : {One-Two-Three-Four-Five}
Collectors.joining string with @ separator : One@Two@Three@Four@Five

 

5. List to String Using Apache Commons StringUtils.join() method


Finally way is using external library from apache commons package. This library has a method StringUtils.join() which takes the list and delimiter similar to the String.join() method.

import org.apache.commons.lang3.StringUtils;

/**
 * Example to convert List to string using apache commons stringutils.join() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingStringUtils_JoinExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");

	// using java 8 Collectors.joining with delimiter, prefix and suffix
	String joiningString = StringUtils.join(list, "^");
	
	// printing
	System.out.println("StringUtils.join string with ^ delimiter : "+joiningString);
	
	String joiningString3 = StringUtils.join(list, "$");
	
	// printing
	System.out.println("StringUtils.join string with @ separator : "+joiningString3);
	
	
	}
}
 

Output:
StringUtils.join string with ^ delimiter : One^Two^Three^Four^Five
StringUtils.join string with @ separator : One$Two$Three$Four$Five
 

6. Conclusion


In this article, we've seen how to convert List to String in java using different methods before and after java 8.

It is good to use the String.join() method for a given delimiter to produce the string from List.
or If you want to add a prefix or suffix then use stream api Collectors.joining() method with delimiter, prefix and suffix values.



Tuesday, May 12, 2020

Java 8 ArrayList forEach Examples

1. Introduction


In this tutorial, You'll learn how to iterate ArrayList using the forEach() method in Java 8. Now ArrayList comes up with a handy utility method to traverse all the elements of List using arraylist foreach.

forEach() is added as part of java 8 changes.

Java 8 ArrayList forEach() Examples


Read more articles on ArrayList.

forEach() method iterates the values till last value or it throws an exception.

This is a complete replacement for the traditional Iterator concept. Internally, It does the looping around the list values.

First, We will see the syntax, its internal implementation, and examples to use forEach() method.

Iterating List, Map or Set with forEach() method

Thursday, March 26, 2020

Program: How To Reverse ArrayList in Java + Custom Reverse

1. Introduction


In this article, we'll be learning how to reverse ArrayList in java. Reversing can be done in two ways using Collections.reverse() method and custom reverse method.
This is one of the ArrayList interview questions commonly asked.


In the end, You will decide which is the simplest way to reverse List?

Program: How To Reverse ArrayList in Java + Custom Reverse



Thursday, March 19, 2020

How to add Integer Values to ArrayList, int array Examples

1. Introduction


In this tutorial, We'll learn an ArrayList problem of how to add integer values to an ArrayList. Let us write an example program to add primitive int values and wrapper integer objects.


In the previous articles, we have discussed how to remove duplicate values in ArrayList.

In the next article, We'll learn How to Iterate ArrayList values?

How to add Integer Values to ArrayList, int array Examples

Thursday, December 19, 2019

Java Program To Copy(Add) All List Values To A new ArrayList

1. Overview


In this tutorial, We'll be learning how to copy all list values to another new List or ArrayList in Java. Here our context copy means adding all values to a new List. how to copy list values to another list in java or Copy a List to Another List in Java can be done in many ways in java.
And We will keep tracking and show all the possible errors that encounter in our practice programs. Please read the entire article to get a better deeper understanding.

We have already written an article on ArrayList API Methods and its examples.

Java Program To Copy(Add) All List Values To A new ArrayList


We will be showing the example programs using constructor, addAll method, Using Java 8 and Java 10 concepts finally using Collections.copy() method. Hope this article will be interesting for you.

Note: ArrayList is not an Immutable object.

Wednesday, December 4, 2019

Java Program To Convert String to ArrayList Using Arrays.asList()

1. Overview


In this ArrayList articles series, You'll be learning today how to convert a String into an ArrayList using java built-in methods. There are many scenarios in the real-time applications where we need to do transform the string into a list of objects. Typically string should be multiple values separated by a delimiter. For example take a String like "Started,Approved,In Progress,Completed". Here we are seeing the statues in string format and all these statuses are for processing the tickets raised by the users. This is the status flow. We need to now convert this string into a List<String>.


Java Program To Convert String to ArrayList Using Arrays.asList()


Note: String can have integers, double and strings values with a delimiter. The same below shown program works for any type of values present in the input string.

Saturday, November 16, 2019

Java Program To Find Unmatched values From Two Lists

1. Overview:

In this tutorial, We'll be learning about a java program how to compare two lists and find out the unmatched contents from those two lists. We will demonstrate the example programs in Java and Python languages.

1.1 Example


Input:

List 1: ["File Name 1", "File Name 2", "File Name 3", "File Name 4", "File Name 5", "File Name 6", "File Name 7", "File Name 8"]
List 2: ["File Name 2", "File Name 4", "File Name 6", "File Name 8"]

Output:

Unmatched values: ["File Name 1", "File Name 3", "File Name 5", "File Name 7]

Find Unmatched values From Two Lists


This example is for Strings. If the list is having custom objects such as objects of Student, Trade or CashFlow. But in our tutorial, We will discuss for Employee objects in the list.

We can use any List implementation classes such as ArrayList, LinkedList, Stack, and Vector. For now, all programs in this post are using ArrayList implementation.

2. Java

We'll write a program to remove the duplicates values from list1 based on list2 and operation seems to be more complex but if we use the java collection API methods then our life will become easy because these methods are being tested by many developers every day.

See in our case need to find the unmatched content against list2 from list1.

2.1 String values


List interface has a method named "removeAll" which takes any collection implementation class (in our example it an ArrayList).

removeAll() method removes from the current list all of its elements that are contained in the specified collection that passed to this method as an argument.

Syntax: See the method signature below.

boolean removeAll(Collection c)

Creating two lists which are having files names in it.

// List 1 contains file names from 1 to 8.
List list1 = new ArrayList<>();
list1.add("File Name 1");
list1.add("File Name 2");
list1.add("File Name 3");
list1.add("File Name 4");
list1.add("File Name 5");
list1.add("File Name 6");
list1.add("File Name 7");
list1.add("File Name 8");

//List 2 contains only even number file names.
List list2 = new ArrayList<>();
list2.add("File Name 2");
list2.add("File Name 4");
list2.add("File Name 6");
list2.add("File Name 8");

Now we are going to delete the file names that are already present in list 2 from list 1.

list1.removeAll(list2);

All the elements that are present in list2 are deleted from list1 which means all even number file names are deleted from list1.

Let us take a look at the contents in list1.

[File Name 1, File Name 3, File Name 5, File Name 7]

Note: If list2 is null then will through NullPointerException.

2.2 Custom Objects

What happens if these two lists are having objects instead of String literals? Custom objects such as Employee, Student, Trade or User objects.

We will demonstrate an example with Employee object for now. The same is applicable for any type of object in the list.

Creating an Employee class with id and name.

public class Employee {

 private int id;
 private String name;

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 // setter and getter methods.
 
 // Overrding toString method.
 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }
}

Creating list1 and list2 with employee objects.

List list1 = new ArrayList<>();
list1.add(new Employee(100, "Jhon"));
list1.add(new Employee(200, "Cena"));
list1.add(new Employee(300, "Rock"));
list1.add(new Employee(400, "Undertaker"));

List list2 = new ArrayList<>();
list2.add(new Employee(100, "Jhon"));
list2.add(new Employee(300, "Rock"));

list1 and list2 have common employee objects for id 100 and 200 with the same name. Now we have to remove these two objects from list1. We know that removeAll method removes objects from list1 comparing with list2 objects. We'll call removeAll method.

list1.removeAll(list2);

Now see the objects in list1 after calling removeAll method.

[Employee [id=100, name=Jhon], Employee [id=200, name=Cena], Employee [id=300, name=Rock], Employee [id=400, name=Undertaker]]


Observe that removeAll method is not removed duplicate objects from list1.
To make this code work, we need to override equals() method in Employee class as below.


@Override
public boolean equals(Object obj) {
 Employee other = (Employee) obj;
 if (id != other.id)
  return false;
 if (name == null) {
  if (other.name != null)
   return false;
 } else if (!name.equals(other.name))
  return false;
 return true;
}


Why we need to override equals method is because removeAll method internally compares the contents invoking equals() method on each object. Here the object is an employee so it calls equals method on employee object.

Take a look at the output of list1 now.

[File Name 1, File Name 3, File Name 5, File Name 7]

We have to notice one point here that the same code had worked in the case of String objects because String class already overridden equals method as below.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String aString = (String)anObject;
        if (coder() == aString.coder()) {
            return isLatin1() ? StringLatin1.equals(value, aString.value)
                              : StringUTF16.equals(value, aString.value);
        }
    }
    return false;
}

All codes are shown are compiled and run successfully in java 12.

3. Python


In Python, finding out the unmatched contents from two lists is very simple in writing a program.

Let us have a look at the following code.

def finder(arr1,arr2):
    eliminated = []

    for x in arr1:
        if x not in arr2:
            eliminated.append(x)
        else:
            pass
    return eliminated

We can sort two lists before for loop as below. I have seen many developers do sorting before comparing the contents. But, actually sorting is not necessary to do.

arr1 = sorted(arr1)
arr2 = sorted(arr2)

4. Conclusion


In this tutorial, We've explored the way to remove the duplicate contents from list 1 against list 2 and finding out the unmatched contents from two lists.

Further discussed comparing two employee lists and finding out unmatched content using removeAll method in Java and Program in Python for the same.

As usual, All examples are shown in this tutorial are available on GitHub.

Wednesday, November 6, 2019

Java ArrayList Real Time Examples

1. Overview


In this tutorial, You'll learn ArrayList with Real-Time examples. If you are new to java programming, you'll get a question "What are the real-life examples of the ArrayList in Java?". Initial days when I was in engineering the second year, my professor was teaching ArrayList in java.

I have learned about it. ArrayList is a dynamic array to store the elements and also it grows the size automatically if it reaching its threshold value. But when we should be using the ArrayList in realtime applications.


Remember, for now, In the software world there is no application deployed in production without ArrayList. Now think about the usage of ArrayList. ArrayList can be used in many more scenarios in realtime.

We will be seeing a few real-time examples of ArrayList in Java.


Java ArrayList Real Time Examples

Monday, May 27, 2019

Removing All Duplicate Values from ArrayList including Java 8 Streams

1. Overview

In this tutorial, We'll learn how to clean up the duplicate elements from ArrayList. Many of the scenarios we do encounter the same in real time projects. But, this can be resolved in many ways.

We will start with Set first then next using new List with using built in method contains() before adding each value to newList.

Next, will see duplicate elements removal with new java 8 concept Streams.

Then later, interestingly we have a list with Employee objects. Employee has id and name. Some Employee objects are added to list. Later realized that list has now duplicate employee based on the id. Now how to remove custom duplicate objects from ArrayList.

Removing All Duplicate Values from ArrayList including Java 8 Streams

Thursday, May 23, 2019

Find Unique and Duplicates Values From Two Lists

1. Overview

In this tutorial, We'll learn how to find the unique values from two lists and how to find all common or duplicates values from two lists.

We'll demonstrate using two ArrayList's to find out unique and duplicates objects in it.

To achieve our requirement, we must compare values in both list. Either we can run the loop through each list or we can use list api built in methods. We'll explore using built in api methods such as contains(), retailAll() and removeAll() methods.




Find Unique and Duplicates From Two Lists

Friday, April 26, 2019

Java ArrayList add method examples

Java ArrayList add method examples:

Introduction:

We will learn Java ArrayList add method with examples. Add method is used to add the specified values at last position of arraylist and at the specified position.

java.util.ArrayList is a class in Java which is implemented based on array concepts. It has many inbuilt methods to simplify the common functionalities.

In this post, we will see examples of how to use add method in ArrayList. Add method is used to add elements to it.

add method 

ArrayList has two add methods.
1. public boolean add(E e) - Adds the value after the last value in the arraylist.
2. public void add(int index, E element) - Adds the values at specified index. 
add() method first ensures that there is sufficient space in the arraylist. If list does not have space, then it grows the list by adding more spaces in underlying array. Then it add the element to specific array index.
Java ArrayList add method examples

Monday, April 8, 2019

How to remove an element from ArrayList in Java?

4 Best Ways to Remove Item from ArrayList:

Learn How to remove an element from ArrayList in Java in this post. We can remove the elements from ArrayList using index or its value using following methods of ArrayList.


1) remove(int index): Takes the index of the element
2) remove(Object o): Takes actual value present in the arraylist.
3) removeIf(Predicate<? super E> filter): which takes the predicate that means if the value is matches to the specified object then it will be removed.
4) void remove(): Removes the current element at the time of iteration.

First 3 methods are from ArrayList and last method is from Iterator interface.


How to remove an element from ArrayList in Java

Friday, July 20, 2018

How To Sort ArrayList In Java – Collections.Sort() Examples

How To Sort ArrayList In Java :

In this post, we will learn how to sort ArrayList in java. This is very easy to understand and remember the methods.


1) Sorting ArrayList in ascending order
2) Sorting ArrayList in descending order



How To Sort ArrayList In Java – Collections.Sort



Sorting List in Ascending order:
package com.java.w3schools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FruitsArrayList {
      public static void main(String[] args) {
            List<String> fruits = new ArrayList<>();
            fruits.add("Mango");
            fruits.add("Orange");
            fruits.add("Apple");
            fruits.add("Banana");
            System.out.println("Printing fruits before sorting : " + fruits);
            Collections.sort(fruits);
            System.out.println("Printing fruits after sorting : " + fruits);
      }
}


Output:

Printing fruits before sorting : [Mango, Orange, Apple, Banana]
Printing fruits after sorting : [Apple, Banana, Mango, Orange]
Collections class has a method sort() which takes List as argument. This method does sorting in ascending order. Observer the output of the above program.

Sorting List in Descending order:

Just replace the Collection.sort with the following code snippet.
Collections.sort(fruits, Collections.reverseOrder());

Output:

Printing fruits before sorting : [Mango, Orange, Apple, Banana]
Printing fruits after sorting : [Orange, Mango, Banana, Apple]
Collections class has a method for sorting the list elements in reverse order that is descending order.
In the next post, we will learn how to sort a list of students where Student is a user defined class with properties of id, name, age.

Wednesday, December 6, 2017

Java ArrayList remove Example: How to remove by index, by Value/Object, for a specific range


How to remove a value from ArrayList in java with example programs.

In this post, we will learn how to program to remove elements from a ArrayList in java. Removing value can be done in three ways.

1) By index
2) By value or Object
3) For a given specific range

ArrayList api provides various methods to do remove operations.

java-arraylist-remove




Monday, October 16, 2017

Add ArrayList to another ArrayList in Java | addAll method

In this post, We will learn How to add ArrayList into a another ArrayList in java.

We can accumulate this in two ways.

1) While creating ArrayList object.
2) Using addAll method.


Add ArrayList to another ArrayList in Java


1) Adding existing ArrayList into new list:

ArrayList has a constructor which takes list as input. Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

ArrayList(Collection c)

Thursday, September 21, 2017

Java API ArrayList Example

Java API ArrayList Overview

In this tutorial, We'll learn about Java Collection API ArrayList.
ArrayList is a class which is widely used in real time applications. It is in package java.util and public class. This is added in java 1.2 version.

Java API ArrayList Example


Class Name: ArrayList
First Version: 1.2
Super Class: AbstractList
Implemented interfaces: List, RandomAccess, Cloneable, Serializable
Pacakge: java.util.