SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:8 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// 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

 

0 0

Discussions

Post the discussion to improve the above solution.