Ints Class in Java



The Ints class is a utility class for primitive type int. Let us see the class declaration −

@GwtCompatible public final class Ints extends Object

Example

Let us see an example of one of the methods to perform concatenation. The concat() function in Ints class is used to concatenate the arrays passed as parameter −

import com.google.common.primitives.Ints; import java.util.*; class Demo {    public static void main(String[] args) {       int[] myArr1 = { 100, 150, 230, 300, 400 };       int[] myArr2 = { 450, 550, 700, 800, 1000 };       System.out.println("Array 1 = ");       for(int i=0; i < myArr1.length; i++) {          System.out.println(myArr1[i]);       }       System.out.println("Array 2 = ");       for(int i=0; i < myArr2.length; i++) {          System.out.println(myArr2[i]);       }       int[] arr = Ints.concat(myArr1, myArr2);       System.out.println("Concatenated arrays = "+Arrays.toString(arr));    } }

Output

Array 1 = 100 150 230 300 400 Array 2 = 450 550 700 800 1000 Concatenated arrays = [100, 150, 230, 300, 400, 450, 550, 700, 800, 1000]

Example

Let us see another example −

import java.util.List; import com.google.common.primitives.Ints; public class GuavaTester {    public static void main(String args[]) {       GuavaTester tester = new GuavaTester();       tester.testInts();    }    private void testInts() {       int[] intArray = {1,2,3,4,5,6,7,8,9};       //convert array of primitives to array of objects       List<Integer> objectArray = Ints.asList(intArray);       System.out.println(objectArray.toString());       //convert array of objects to array of primitives       intArray = Ints.toArray(objectArray);       System.out.print("[ ");       for(int i = 0; i < intArray.length ; i++) {          System.out.print(intArray[i] + " ");       }       System.out.println("]");       //check if element is present in the list of primitives or not       System.out.println("5 is in list? " + Ints.contains(intArray, 5));       //Returns the minimum       System.out.println("Min: " + Ints.min(intArray));       //Returns the maximum       System.out.println("Max: " + Ints.max(intArray));       //get the byte array from an integer       byte[] byteArray = Ints.toByteArray(20000);       for(int i = 0; i < byteArray.length ; i++) {          System.out.print(byteArray[i] + " ");       }    } }

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9] [ 1 2 3 4 5 6 7 8 9 ] 5 is in list? true Min: 1 Max: 9 0 0 78 32
Updated on: 2019-09-24T08:31:11+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements