Java Arrays.setAll() Examples To Modify Existing Array


A quick guide to the Arrays.setAll() method from JDK 1.8. This method sets all elements of the specified array, using the provided generator function.

1. Overview

In this article, You'll learn how to use JDK 1.8 Arrays.setAll() method to modify the existing values of the array with a unique generator function. Arrays class is part of java.util package.

This method sets all elements of the specified array, using the provided generator function to compute each element.

In the previous article, We've seen how to set the whole array with the same value using Arrays.fill() method?

Java Arrays.setAll() Examples

2. Arrays.setAll() Syntax

This is an overloaded method and available in 4 versions as below.

Works for integer, double and long arrays. And also, this method provides supports for Generics.

public static void setAll(double[] array,
                          IntToDoubleFunction generator)

public static void setAll(int[] array,
                          IntUnaryOperator generator)

public static void setAll(long[] array,
                          IntToLongFunction generator)

public static <T> void setAll(T[] array,
                              IntFunction<? extends T> generator)

3. Arrays.setAll() Example - int[] Array

Below example, the program generates even numbers from the array.
package com.javaprogramto.arrays.setall;

import java.util.Arrays;

public class IntArraySetAllExample {

    public static void main(String[] args) {

        int[] intArray = new int[7];

        System.out.println("original int array : "+ Arrays.toString(intArray));

        Arrays.setAll(intArray, i -> (i + 1) * 2);

        System.out.println("array.setAll(int) output: "+ Arrays.toString(intArray));

original int array : [0, 0, 0, 0, 0, 0, 0]
array.setAll(int) output: [2, 4, 6, 8, 10, 12, 14]

4. Arrays.setAll() Example - double[] Array

Example program to set the double values using Arrays.setAll(double[]. IntToDoubleFunction) method and passing the IntToDoubleFunction as Lambda Expression.
package com.javaprogramto.arrays.setall;

import java.util.Arrays;

public class DoubleArraySetAllExample {

    public static void main(String[] args) {

        // Creating a double array with default values
        double[] doubleArray = new double[7];

        System.out.println("original double array with default values : "+ Arrays.toString(doubleArray));

        // setting values to doubleArray using setAll() method
        Arrays.setAll(doubleArray, i -> i + 10.5);

        System.out.println("Double array.setAll(double) output: "+ Arrays.toString(doubleArray));
original double array with default values : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
Double array.setAll(double) output: [10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5]

5. Arrays.setAll() Example - long[] Array

setAll() method takes long array with generator IntToLongFunction.
package com.javaprogramto.arrays.setall;

import java.util.Arrays;

public class LongArraySetAllExample {

    public static void main(String[] args) {

        // Creating a long array with default values
        long[] longArray = new long[7];

        System.out.println("original long array with default values : "+ Arrays.toString(longArray));

        // setting values to longArray using setAll() method
        Arrays.setAll(longArray, i -> i + 10 * 20);

        System.out.println("Long array.setAll(long) output: "+ Arrays.toString(longArray));

6. Arrays.setAll() Example - String[] Array

Any Array type can be passed to setAll() method because it supports for genetics. Let us try passing the String Array.
public class StringArraySetAllExample {

    public static void main(String[] args) {

        // Creating a String array with default values
        String[] stringArray = new String[7];

        System.out.println("original String array with default values : "+ Arrays.toString(stringArray));

        // setting values to stringArray using setAll() method
        Arrays.setAll(stringArray, i -> i + 10 * 20);

        System.out.println("String array.setAll(String) output: "+ Arrays.toString(stringArray));

original String array with default values : [null, null, null, null, null, null, null]
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
	at java.base/java.util.Arrays.setAll(Arrays.java:5248)
	at com.javaprogramto.arrays.setall.StringArraySetAllExample.main(StringArraySetAllExample.java:15)

Throws the runtime exception saying "ArrayStoreException: java.lang.Integer" that means it can not store the Integer values inside String Array.

So, we should return only String from inside generator logic.

Next, Change the logic to return string as below and execute the program.
Arrays.setAll(stringArray, i -> "Index " + i);
This code returns the Index number of each index and sets it into String Array.

String array.setAll(String) output: [Index 0, Index 1, Index 2, Index 3, Index 4, Index 5, Index 6]

7. Arrays.setAll() Example with Custom Object Employee[] Array

Last, look at the user-defined array with the Arrays.setAll() method.
import com.javaprogramto.models.Employee;

import java.util.Arrays;

public class EmployeeArraySetAllExample {

    public static void main(String[] args) {

        // Creating a Employee array with default values
        Employee[] employeeArray = new Employee[7];

        System.out.println("original Employee array with default values : "+ Arrays.toString(employeeArray));

        // setting values to employeeArray using setAll() method
        Arrays.setAll(employeeArray, i -> new Employee(i+1, "Index "+i, i+30));

        System.out.println("Employee array.setAll(Employee) output: "+ Arrays.toString(employeeArray));

original Employee array with default values : [null, null, null, null, null, null, null]
Employee array.setAll(Employee) output: [Employee{id=1, fullName='Index 0', age=30}, Employee{id=2, fullName='Index 1', age=31}, Employee{id=3, fullName='Index 2', age=32}, Employee{id=4, fullName='Index 3', age=33}, Employee{id=5, fullName='Index 4', age=34}, Employee{id=6, fullName='Index 5', age=35}, Employee{id=7, fullName='Index 6', age=36}]

Employee custom generator logic creates new Employee objects and sets the data. Original employeeArray is not having any values and after calling setAll() method, employee objects are set to it.

8. Conclusion

In this article, You've seen how to modify the values of the existing array using a unique generator fucntion.

All examples are shown with the Array.setAll() method for int, long, double, String, and Employee arrays.

If the generator function returns a different type of object than the original array type then it will throw ArrayStoreException. 

All Examples shown are over GitHub.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java Arrays.setAll() Examples To Modify Existing Array
Java Arrays.setAll() Examples To Modify Existing Array
A quick guide to the Arrays.setAll() method from JDK 1.8. This method sets all elements of the specified array, using the provided generator function.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content