Write a method removeEvenLength that accepts a set of strings as a parameter and that removes all of the strings of even length from the set.
// package collections;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveEvenLength {
public static Set<String> removeEvenLength(Set<String> set) {
// create a set to store our new elements
Set<String> newSet = new HashSet<String>();
// loop through each value in set and check if the leght is even or odd
// adds only odd legth strings
for(String string: set) {
if(string.length()%2==1)
newSet.add(string);
}
// return out new set
return newSet;
}
public static void printList(Set<String> set) {
System.out.println(Arrays.toString(set.toArray()));
}
public static void main(String[] args) throws InterruptedException {
Set<String> set = new HashSet<String>();
Collections.addAll(set,"This", "strange", "fox", "teleported", "from", "parallel", "universe");
System.out.println("after removing the even length strings from set: "+(removeEvenLength(set)));
}
}
Output:
after removing the even length strings from set: [strange, fox]