Showing posts with label iterable. Show all posts
Showing posts with label iterable. Show all posts

Monday, 14 August 2023

Effectively Combining Iterables with Zip function

Using Python’s zip function, we can combine multiple iterables into a single iterable. Here iterable can be a list, tuple etc.,

For example, I have 4 lists to represent employees information and I used zip() to create a list of tuples, where each tuple contains the corresponding elements from the four lists.

ids = [1, 2, 3, 4]
names = ['Krishna', 'Narasimha', 'Ramesh', 'Sailu']
ages = [34, 39, 45, 35]
cities = ['Bangalore', 'Chennai', 'Bangalore', 'Hyderabad']

zipped = zip(ids, names, ages, cities)
print(zipped)

 

This code will print the following output:

<zip object at 0x10b4e6c00>

The zipped variable is a zip object, which is an iterator of tuples, we can iterate over a zipped object using for loop like below.

for id, name, age, city in zipped:
    print(f'id : {id}, name : {name}, age : {age}, city : {city}')

 

Convert zip object to a list of tuples

Using list() function, we can convert the zip object to a list.

list_of_tuples = list(zipped)

Iterate over a zip object using next() function

while True:
    try:
        id, name, age, city = next(zipped)
        print(f'id : {id}, name : {name}, age : {age}, city : {city}')
    except StopIteration:
        print('No more elements to process')
        break

‘next()’ function will return the next tuple in the iterator, and the id, name, age, city variables will be assigned the corresponding elements from the tuple. ‘while’ loop in the code will continue to iterate over the zip object until there are more tuples to be processed. When there are no more tuples to process, next() method raises a StopIteration exception.

 

Can I iterate over a zipped object multiple times?

No, you can’t iterate over a zipped object multiple times, zip() function returns an iterator which can be traversed once.

 

Find the below working application.

 


zip_demo.py

ids = [1, 2, 3, 4]
names = ['Krishna', 'Narasimha', 'Ramesh', 'Sailu']
ages = [34, 39, 45, 35]
cities = ['Bangalore', 'Chennai', 'Bangalore', 'Hyderabad']

zipped = zip(ids, names, ages, cities)
print(zipped)

# iterating over the zipped object using for loop
print('\niterating over the zipped object using for loop')
for id, name, age, city in zipped:
    print(f'id : {id}, name : {name}, age : {age}, city : {city}')

# I can't iterate over a zipped object multiple times, so creating new one
zipped = zip(ids, names, ages, cities)
print('Convert the zipped object to a list')
list_of_tuples = list(zipped)
print(f'\nlist_of_tuples : \n{list_of_tuples}')

# I can't iterate over a zipped object multiple times, so creating new one
print('\nIterate over zipped object using next function')
zipped = zip(ids, names, ages, cities)
while True:
    try:
        id, name, age, city = next(zipped)
        print(f'id : {id}, name : {name}, age : {age}, city : {city}')
    except StopIteration:
        print('No more elements to process')
        break

Output

<zip object at 0x107ee0e80>

iterating over the zipped object using for loop
id : 1, name : Krishna, age : 34, city : Bangalore
id : 2, name : Narasimha, age : 39, city : Chennai
id : 3, name : Ramesh, age : 45, city : Bangalore
id : 4, name : Sailu, age : 35, city : Hyderabad
Convert the zipped object to a list

list_of_tuples : 
[(1, 'Krishna', 34, 'Bangalore'), (2, 'Narasimha', 39, 'Chennai'), (3, 'Ramesh', 45, 'Bangalore'), (4, 'Sailu', 35, 'Hyderabad')]

Iterate over zipped object using next function
id : 1, name : Krishna, age : 34, city : Bangalore
id : 2, name : Narasimha, age : 39, city : Chennai
id : 3, name : Ramesh, age : 45, city : Bangalore
id : 4, name : Sailu, age : 35, city : Hyderabad
No more elements to process

 

Previous                                                    Next                                                    Home

Saturday, 12 November 2022

Convert an Iterable to a Set in Java

Write a method, that takes an Iterable as input and return the set as output. Make sure that the order of elements is maintained.

 

Signature

public static <T> List<T> toSet(final Iterable<T> iterable, final boolean skipNull)

 

Find the below working application.

 


IterableToSet.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class IterableToSet {
	/**
	 * Converts an {@link Iterable} to a {@link Set}. If skipNull is set to true,
	 * then it skip the null values while constructing the {@link Set}
	 * 
	 * @param <T>
	 * @param iterable
	 * @param skipNull
	 * 
	 * @return empty list, if the {@link Iterable} is null or empty. else return a
	 *         {@link Set} that contain the elements of {@link Iterable}.
	 */
	public static <T> Set<T> toSet(final Iterable<T> iterable, final boolean skipNull) {

		if (iterable == null) {
			return Collections.emptySet();
		}

		if (iterable instanceof Set) {
			return (Set<T>) iterable;
		}

		// Return empty list, if the iterator has no elements
		if (!iterable.iterator().hasNext()) {
			return Collections.emptySet();
		}

		// Use LinkedHashSet to maintain the order
		final Set<T> set = new LinkedHashSet<>();
		for (T ele : iterable) {
			if (skipNull == true && ele == null) {
				continue;
			}
			set.add(ele);
		}

		return set;
	}

	public static void main(String[] args) {
		final List<Integer> primesList = Arrays.asList(2, 3, 5, 7, null, 11, 13);

		Set<Integer> set1 = toSet(primesList, true);
		Set<Integer> set2 = toSet(primesList, false);

		System.out.println(set1);
		System.out.println(set2);

	}

}

 

Output

[2, 3, 5, 7, 11, 13]
[2, 3, 5, 7, null, 11, 13]

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an enumeration to set in Java

Convert an enumeration to Iterable in Java

Convert an array to set in Java

Get the string representation of an Iterable

Convert an Iterable to List in Java

Convert an Iterable to List in Java

Write a method, that takes an Iterable as input and return the List as output.

 

Signature

public static <T> List<T> toList(final Iterable<T> iterable, final boolean skipNull)

 

Find the below working application.


IterableToList.java

package com.sample.app.collections;

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

public class IterableToList {

	/**
	 * Converts an {@link Iterable} to a {@link List}. If skipNull is set to true,
	 * then it skip the null values while constructing the {@link List}
	 * 
	 * @param <T>
	 * @param iterable
	 * @param skipNull
	 * 
	 * @return empty list, if the {@link Iterable} is null or empty. else return a
	 *         {@link List} that contain the elements of {@link Iterable}.
	 */
	public static <T> List<T> toList(final Iterable<T> iterable, final boolean skipNull) {

		if (iterable == null) {
			return Collections.emptyList();
		}

		if (iterable instanceof List) {
			return (List<T>) iterable;
		}

		// Return empty list, if the iterator has no elements
		if (!iterable.iterator().hasNext()) {
			return Collections.emptyList();
		}

		final List<T> list = new ArrayList<>();
		for (T ele : iterable) {
			if (skipNull == true && ele == null) {
				continue;
			}
			list.add(ele);
		}

		return list;
	}

	public static void main(String[] args) {
		Set<Integer> primesSet1 = new HashSet<>(Arrays.asList(2, 3, 5, 7, null, 11, 13));

		List<Integer> list1 = toList(primesSet1, true);
		List<Integer> list2 = toList(primesSet1, false);

		System.out.println(list1);
		System.out.println(list2);

	}

}

 

Output

[2, 3, 5, 7, 11, 13]
[null, 2, 3, 5, 7, 11, 13]

 

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an iterator to set in Java

Convert an enumeration to set in Java

Convert an enumeration to Iterable in Java

Convert an array to set in Java

Get the string representation of an Iterable

Get the string representation of an Iterable

Write a function that takes an iterable and a delimeter as input and get the string representation of iterbale.

 

Signature

public static <T> String toString(final Iterable<T> iterable, final String delimiter, final boolean skipNull)

 

Find the below working application.


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

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

public class IterableToString {

	/**
	 * 
	 * @param <T>
	 * @param delimiter use comma (,), if it is null
	 * @param iterable
	 * @param skipNull, skip null values, it it is set to true, else add the string
	 *                  "null" for null values.
	 * 
	 * @return a string representation of the given iterable. Elements in the
	 *         iterable are separated by given delimeter.
	 */
	public static <T> String toString(final Iterable<T> iterable, final String delimiter, final boolean skipNull) {

		if (iterable == null) {
			return "";
		}

		String delimeterToUse = delimiter;

		if (delimiter == null) {
			delimeterToUse = ",";
		}

		final StringJoiner stringJoiner = new StringJoiner(delimeterToUse);

		for (T ele : iterable) {
			if (skipNull == true && ele == null) {
				continue;
			}

			if (ele == null) {
				stringJoiner.add("null");
			} else {
				stringJoiner.add(ele.toString());
			}

		}

		return stringJoiner.toString();

	}

	public static void main(String[] args) {
		List<Object> list = Arrays.asList(1, "krishna", null, 34, "Bangalore", true);

		String str1 = toString(list, "->", false);
		String str2 = toString(list, "->", true);

		System.out.println(str1);
		System.out.println(str2);

	}

}

 

Output

1->krishna->null->34->Bangalore->true
1->krishna->34->Bangalore->true

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Get a map from array in Java

Convert an iterator to set in Java

Convert an enumeration to set in Java

Convert an enumeration to Iterable in Java

Convert an array to set in Java

Convert an enumeration to Iterable in Java

Write a method that takes an enumeration as input and return an Iterable as output.

 

Signature

public static <T> Iterable<T> toIterable(final Enumeration<T> enumeration)

 

Find the below working application.

 


EnumerationToIterable.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class EnumerationToIterable {

	/**
	 * Convert an {@link Enumeration} to an {@link Iterable}
	 * 
	 * @param <T>
	 * @param enumeration
	 * @return empty list, if the enumeration is null, else return an iterable that
	 *         is used to traverse the elements of enumeraiton.
	 */

	public static <T> Iterable<T> toIterable(final Enumeration<T> enumeration) {
		if (enumeration == null) {
			return Collections.emptyList();
		}

		final Iterable<T> iterable = () -> new Iterator<T>() {
			@Override
			public boolean hasNext() {
				return enumeration.hasMoreElements();
			}

			@Override
			public T next() {
				return enumeration.nextElement();
			}
		};

		return iterable;
	}

	public static void main(String[] args) {
		final Vector<Integer> primesVector = new Vector<>();
		primesVector.addAll(Arrays.asList(2, 3, 5, 7, 11));

		final Enumeration<Integer> primesEnumeration = primesVector.elements();
		Iterable<Integer> iterable = toIterable(primesEnumeration);

		for (int i : iterable) {
			System.out.println(i);
		}
	}
}

 

Output

2
3
5
7
11

  

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 a map from array in Java

Convert an iterator to set in Java

Convert an enumeration to set in Java

Friday, 11 November 2022

How to check the object is an iterable or not?

Using Class.isAssignableFrom method, we can check whether given object is an iterable or not.

 

Signature

public native boolean isAssignableFrom(Class<?> cls)

'isAssignableFrom' method return true, if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter, else false.

 

Example

public static boolean isIterable(final Class<?> clazz) {
    return clazz != null && (Iterable.class.isAssignableFrom(clazz));
}

 

Above snippet return true, if the given type an iterable, else false.

 


Find the below working application.

 

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

import java.util.Arrays;
import java.util.HashMap;

public class IterableCheckDemo {
	
	public static boolean isIterable(final Class<?> clazz) {
        return clazz != null && (Iterable.class.isAssignableFrom(clazz));
    }
	
	public static void main(String[] args) {
		final Object list = Arrays.asList(2, 3, 5, 7);
		final Object map = new HashMap<>();
		
		System.out.println("Is list iterable : " + isIterable(list.getClass()));
		System.out.println("Is map iterable : " + isIterable(map.getClass()));
	}

}

 

Output

Is list iterable ? true
Is map iterable ? false

 

  

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Generic method to concatenate two arrays in Java

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java