Write a function toSet, that takes an Enumeration as an argument and return the set as output.
Signature
public static <T> Set<T> toSet(Enumeration <T> iterator)
Find the below working application
EnumerationToSet.java
package com.sample.app.collections;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
public class EnumerationToSet {
/**
* Convert an {@link Enumeration} to the {@link Set}
*
* @param <T>
* @param iterator
*
* @return empty set, if the Enumeration is null, else return a set that contain
* the elements from Enumeration
*/
public static <T> Set<T> toSet(Enumeration<T> enumeration) {
if (enumeration == null) {
return Collections.emptySet();
}
final Set<T> set = new HashSet<>();
while (enumeration.hasMoreElements()) {
set.add(enumeration.nextElement());
}
return set;
}
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();
System.out.println(toSet(primesEnumeration));
}
}
Output
[2, 3, 5, 7, 11]
You may like
How to check the object is an iterable or not?
How to check the type or object is a map or not?
No comments:
Post a Comment