Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Saturday, 12 November 2022

Convert an array to set in Java

Write a method that convert an array to a set in Java.

 

Signature

public static <T> Set<T> toSet(final T... elements)

 

Find the below working application.

 


ArrayToSet.java
package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ArrayToSet {

	/**
	 * 
	 * @param <T>
	 * @param objects
	 * 
	 * @return empty set if the objects is null or empty, else return a set that
	 *         contain array elements.
	 */
	@SafeVarargs
	public static <T> Set<T> toSet(final T... elements) {
		if (elements == null || elements.length == 0) {
			return Collections.emptySet();
		}
		return new HashSet<>(Arrays.asList(elements));
	}

	public static void main(String[] args) {
		Integer[] primes = { 2, 3, 5, 7, 11 };
		Set<Integer> primesSet = toSet(primes);

		System.out.println(primesSet);

	}

}

 

Output

[2, 3, 5, 7, 11]

 


You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an enumeration to Iterable in Java

How to check the type or object is a map or not?

Get a map from array in Java

Convert an iterator to set in Java

Convert an enumeration to set in Java

Friday, 11 November 2022

Get a map from array in Java

Input: array of values like below.

key1, value1, key2, value2, ……keyN, valueN

 

Output: Get a map out of the array.

key1 -> value1,
key2 -> value2,
………
………
keyN -> valueN

 


MapFromArray.java

package com.sample.app.collections;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MapFromArray {

	public static Map<Object, Object> toMap(final Object... elements) {
		if (elements == null) {
			return Collections.emptyMap();
		}

		final int noOfElements = elements.length;
		if (noOfElements % 2 != 0) {
			throw new IllegalArgumentException("Number of elements must be an even number to form a map");
		}

		final Map<Object, Object> map = new HashMap<>(noOfElements / 2);
		int i = 0;
		while (i < elements.length - 1) {
			map.put(elements[i++], elements[i++]);
		}
		return map;
	}

	public static void main(String[] args) {
		Object[] empsInfo = { 1, "Krishna", 2, "Ram", 3, "PTR" };
		Map<Object, Object> map = toMap(empsInfo);

		System.out.println(map);

	}

}

 

Output

{1=Krishna, 2=Ram, 3=PTR}

 

 

 

 

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

How to check the object is an iterable or not?

How to check the type or object is a map or not?

Get an iterator from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

Friday, 4 November 2022

Get an iterator from array in Java

Define a method that takes an array as input and return an iterator to traverse the elements.

 

Signature

public static <T> Iterator<T> getIterator(T[] array)

Find the below working application.

 


ArrayIterator.java

package com.sample.app.iterators;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayIterator<T> implements Iterator<T>, Iterable<T> {

	private final T[] array;
	private int currentIndex;
	private final int length;

	public ArrayIterator(T[] array) {
		if (array == null) {
			throw new IllegalArgumentException("Array can't be null to get an interator");
		}
		this.array = array;
		currentIndex = 0;
		length = array.length;
	}

	@Override
	public boolean hasNext() {
		return currentIndex < length;
	}

	@Override
	public T next() {
		if (currentIndex >= length) {
			throw new NoSuchElementException();
		}
		return array[currentIndex++];
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Iterator<T> iterator() {
		return this;
	}
}

ArrayIteratorDemo.java

package com.sample.app.arrays;

import java.util.Iterator;

import com.sample.app.iterators.ArrayIterator;

public class ArrayIteratorDemo {

	public static <T> Iterator<T> getIterator(T[] array) {
		return new ArrayIterator<T>(array);
	}

	public static void main(String[] args) {
		ArrayIterator<Integer> iterator = (ArrayIterator)getIterator(new Integer[] { 2, 3, 5, 7, 11 });

		for(Integer ele: iterator) {
			System.out.println(ele);
		}
	}

}

Output

2
3
5
7
11



You may like

Interview Questions

Array programs in Java

Generic method to concatenate two arrays in Java

Get the string representation of array by given delimiter in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Tuesday, 12 July 2022

Is Arrays override toString method in Java?

In Java, object.toString() method return the string representation of an object. toString() method is defined in ‘java.lang.Object’ class, subclasses can override this method and provide custom implementation.

 

What is the default implementation of toString method?

‘java.lang.Object’ class implement toString method like below.

public String toString() {
	return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

 

Is Arrays override toString method?

Arrays don't override toString() method, so when you call toString() method on array variables, you will get the default behaviour of Object.toString().

 


ArrayToString.java
package com.sample.app;

public class ArrayToString {

	// default implementation from java.lang.Object class.
	private static String toString(Object obj) {
		return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
	}

	public static void main(String[] args) {
		int[] arr1 = { 2, 3, 5, 7 };
		String[] arr2 = { "Hi", "there" };

		System.out.println(arr1.toString() + "\t" + toString(arr1));
		System.out.println(arr2.toString() + "\t" + toString(arr2));
	}

}

 

Output

[I@15db9742	[I@15db9742
[Ljava.lang.String;@6d06d69c	[Ljava.lang.String;@6d06d69c

 

 

Previous                                                 Next                                                 Home

Monday, 16 May 2022

Get the length of longest row in a two dimensional jagged array in Java

Java support jagged arrays. A Jagged array is an array whose elements are arrays with different dimensions.

 

There are two ways to define a Jagged arrays.

a.   Specify the jagged array size using array declaration

b.   Define the array elements, let Java deduce the size

 

 

Specify the jagged array size using array declaration

 

Example

int arr[][] = new int[3][];

arr[0] = new int[2];

arr[1] = new int[6];

arr[2] = new int[4];

 

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2

b.   arr[1] of size 6

c.    arr[2] of size 4.

 

In the above example, 1st row is the longest among all the rows in the given 2-dimensional array.

 

Below snippet print the length of longest row.

int longestRow = 0;

for (int i = 0; i < arr.length; i++) {
	if (arr[i].length > longestRow) {
      longestRow = arr[i].length;
    }
}

 

Find the below working application.

 

LongestRowLength.java

 

package com.sample.app;

public class LongestRowLength {
	
	public static void main(String[] args) {
		int[][] arr = {
				{1, 2},
				{5, 6, 7, 8, 13, 14},
				{9, 10, 11, 12}
		};
		
		int longestRow = 0;
		
		for (int i = 0; i < arr.length; i++) {
			if (arr[i].length > longestRow) {
		      longestRow = arr[i].length;
		    }
		}
		
		System.out.println("Length of longest row is : " + longestRow);
	}

}

 

Output

Length of longest row is 6

 

 

 

 You may like

Interview Questions

Java: Check whether a class exists in the classpath or not

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Jagged arrays in Java

Java support jagged arrays. A Jagged array is an array whose elements are arrays with different dimensions.

 

 


There are two ways to define a Jagged arrays.

a.   Specify the jagged array size using array declaration

b.   Define the array, let Java deduce the size

 

 

Specify the jagged array size using array declaration

 

Example

int arr[][] = new int[3][];

arr[0] = new int[2];

arr[1] = new int[3];

arr[2] = new int[5];

 

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2

b.   arr[1] of size 3

c.    arr[2] of size 4.

 

Find the below working application.

 

JaggedArray1.java

package com.sample.app;

public class JaggedArray1 {

	public static void main(String[] args) {
		int arr[][] = new int[3][];
		arr[0] = new int[2];
		arr[1] = new int[3];
		arr[2] = new int[5];

		// Define array elements
		int count = 1;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				arr[i][j] = count++;
			}
		}

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
			}
			System.out.println();
		}

	}

}

Output

arr[0][0] = 1
arr[0][1] = 2

arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8
arr[2][3] = 9
arr[2][4] = 10

Define the array elements, let Java deduce the size

Example

int arr[][] = {

                  { 1, 2 },

                  { 3, 4, 5},

                  { 6, 7, 8, 9, 10}

         };

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2, and hold the elements {1, 2}

b.   arr[1] of size 3, and hold the elements {3, 4, 5}

c.    arr[2] of size 4. , and hold the elements {6, 7, 8, 9, 10}

 

Find the below working application.

 

JaggedArray2.java


package com.sample.app;

public class JaggedArray2 {

	public static void main(String[] args) {
		int arr[][] = { 
					{ 1, 2 }, 
					{ 3, 4, 5}, 
					{ 6, 7, 8, 9, 10} 
				};

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
			}
			System.out.println();
		}

	}

}

Output

arr[0][0] = 1
arr[0][1] = 2

arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8
arr[2][3] = 9
arr[2][4] = 10


You may like

Interview Questions

Call the main method of one class from other class using reflection

Java: Check whether a class exists in the classpath or not

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?