Write a method maxLength that accepts a set of strings as a parameter and that returns the length of the longest string in the list. If your method is passed an empty set, it should return 0.
// package collections;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class MaxLength {
// max length method takes the argument Of set type
public static int maxLength(Set<String> set) {
int maxLength = 0;
// this for each loop checks the all the strings in set and get
// length of each string and update the length for each iterate
for (String str : set) {
if (str.length() > maxLength)
maxLength = str.length();
}
// returns the max length
return maxLength;
}
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
Collections.addAll(set,"This", "strange", "fox", "teleported", "from", "parallel", "universe");
System.out.println("longest string in the set of strings is: " +maxLength(set));
}
}
longest string in the set of strings is: 10