The Wayback Machine - https://web.archive.org/web/20240819102612/https://www.geeksforgeeks.org/java-util-arrays-parallelsetall-arrays-setall-java/
Open In App

Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java

Last Updated : 28 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites : 

parallelSetAll and setAll are introduced in Arrays class in java 8. 

  • parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. 
    Syntax: 
public static void parallelSetAll(double[] arr, IntToDoubleFunction g)
Parameters :
arr :  Array to which the elements to be set 
g : It is a function that accepts index of an array 
and returns the computed value to that index
  • Variations : 
parallelSetAll(double[] arr, IntToDoubleFunction g)
parallelSetAll(int[] arr, IntUnaryOperator g)
parallelSetAll(long[] arr, IntToLongFunction g)
parallelSetAll(T[] arr, IntFunction g)
  • setAll() : It set all the element in the specified array in by the function which compute each element. 
    Syntax: 
public static void setAll(int[] arr, IntUnaryOperator g)
Parameters :
    arr :  Array to which the elements to be set
   g : It is a function that accepts index of an array 
and returns the computed value to that index
  • Variations : 
setAll(double[] array, IntToDoubleFunction generator)
setAll(int[] array, IntUnaryOperator generator)
setAll(long[] array, IntToLongFunction generator)
setAll(T[] array, IntFunction generator)

parallelSetAll() vs setAll()

Both functions produces same output as can be seen, but parallelSetAll() is consider faster as it performs the changes on the array parallel(i.e. at once) while setAll() updates each indices of the array(i.e. one after another). Though setAll() runs faster on smaller sized array but parallelSetAll() takes over setAll() when the size of array is larger. 
 

Examples

Lets see an example of parallelSetAll(int[] arr, IntUnaryOperator g) and setAll(int[] array, IntUnaryOperator generator) 
 

Java





Output: 
 

Example 1: Modifying the values at even index and storing the square of index
0  1  4  3  16  5  36  7  64  9  100  11  144  13  196  15  256  17  324  19  

Example 2: Modifying the values when even value is encountered
1  4  3  16  5  36  7  64  9  100  11  144  13  196  15  256  17  324  19  400  

Example 3:setAll gives exactly same output as parallelSetAll
0  1  4  3  16  5  36  7  64  9  100  11  144  13  196  15  256  17  324  19  

Example 2 : We can even even pass arrays of user defined data type. Lets see an example of setAll(T[] array, IntFunction generator) and parallelSetAll(T[] arr, IntFunction g)
 

Java




// Java program to demonstrate setAll()
// and ParallelSetAll
import java.util.Arrays;
class GFG {
    // User Defined class Person
    static class Person {
        String name;
        int age;
 
        // constructor
    public Person(String name, int age)
        {
            this.name = name;
            this.age = age;
        }
    }
 
    public static void main(String[] args)
    {
        // Declaring Arrays of person
        Person p[] = { new Person("samir", 20),
                       new Person("anil", 25), new Person("amit", 10),
                       new Person("rohit", 17), new Person("Geek5", 19),
                       new Person("sumit", 22), new Person("gourav", 24),
                       new Person("sunny", 27), new Person("ritu", 28) };
 
        // Applying parallelSetAll on p array
        Arrays.parallelSetAll(p, e->{
            if (p[e].name.startsWith("s"))
                return new Person("You are a geek", 100);
            else
                return new Person(p[e].name, p[e].age);
        });
        System.out.println("Example 1; Modifying the name that starts with s");
 
        // Printing array elements
        Arrays.stream(p).forEach(e->System.out.println(e.name + "   " + e.age));
 
        // Declaring another array of person
        Person p1[] = { new Person("samir", 16),
                        new Person("anil", 25), new Person("amit", 10),
                        new Person("rohit", 17), new Person("Geek5", 19),
                        new Person("sumit", 16), new Person("gourav", 24),
                        new Person("sunny", 11), new Person("ritu", 28) };
 
        // Applying setAll on p1
        Arrays.setAll(p1, e->{
            if (p1[e].age < 18)
                return new Person("Teenager", p1[e].age);
            else
                return new Person(p1[e].name, p1[e].age);
        });
 
        System.out.println("\n\nExample 2: Modifying name whose"
                           + "age is less than 18");
 
        // Printing array elements
        Arrays.stream(p1).forEach(e->System.out.println(e.name + "   " + e.age));
    }
}


Output: 
 

Example 1; Modifying the name that starts with s
You are a geek   100
anil   25
amit   10
rohit   17
Geek5   19
You are a geek   100
gourav   24
You are a geek   100
ritu   28


Example 2: Modifying name whose age is less than 18
Teenager   16
anil   25
Teenager   10
Teenager   17
Geek5   19
Teenager   16
gourav   24
Teenager   11
ritu   28

Reference : 
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html 

 



Similar Reads

Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Java.util.Arrays.deepEquals() in Java
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension. Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of eleme
4 min read
Java.util.Arrays.copyOfRange() in Java
This method creates a copy of elements, within a specified range of the original array.Syntax : public static int[] copyOfRange(int[] original_array, int from_index, int to_index) original_array : Array to be copied fromfrom_index : Starting index of range to be copiedto_end : the final index of the range to be copied, exclusive. (This index may li
4 min read
Java.util.Arrays.parallelPrefix in Java 8
Prerequisites: Lambda Expressions in Java 8Stream In Java The parallelPrefix method is introduced to the Arrays class in java 8. The parallelPrefix method performs a given mathematical function on the elements of the array cumulatively, and then modifies the array concurrently. Syntax : parallelPrefix(int[] array, IntBinaryOperator op) Parameters :
6 min read
util.Arrays vs reflect.Array in Java with Examples
Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can’t be instantiated or changed. Only the methods of this class can be used by the class name itself. On the other hand, Arrays class in java.util package is
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate&lt;T, V&gt; interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate&lt;T, V&gt; Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
How to Fix java.util.NoSuchElementException in Java?
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException
4 min read
Difference Between java.lang and java.util
Java Packages contain classes, interfaces, and sub-packages. The packages java.lang and java.util are two of the most commonly used packages in Java Standard Library. Both packages contain useful classes and utilities. In this article, we will learn about java.lang and java.util package with examples and also the difference between these two packag
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
Java.util.Locale Class in Java | Set 1
As the name suggests util.Locale Class is used to perform locale tasks and provides locale information for the user. Declaration : public final class Locale extends Object implements Cloneable, Serializable Constructors : Locale(String L): Creates Locale from the given language code.Locale(String L, String C): Creates Locale from the given language
4 min read
Practice Tags :
three90RightbarBannerImg