Java: How to find Longest String in ArrayList ? [FUNCTION]

While I was playing with Java code, I have coded a class that has method that finds longest String in the ArrayList. Method is very simple, but I am sure that some of you will find it useful.

So here it is:

 // I have a class attribute:
private ArrayList wordsList = new ArrayList();

// here is method itself:
public String longest_word(){
	String longest_word="";
	int maxLength=0;
		for(int i=0; i

			if(wordsList.get(i).length() > maxLength){
			  maxLength = wordsList.get(i).length();
			  longest_word = wordsList.get(i);
			}
		}
	return longest_word;
	}

Check out more posts on “Useful Java Functions and Tutorials”

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. jetcracker

    It’s better to use iterators for this type of work. Because if your array is a LinkedList instance, using get(i) will have a negative effect on performance.

  2. jetcracker

    If you are using JDK 6 – you can use short for-statement:
    [sourcecode language=”java”]
    for(String w: wordList) {
    if( w.length() > maxLength ) maxLength = w.length();
    }
    [/sourcecode]

    1. A

      this works too

      public int maxLength(ArrayListlist){
      int max=0;
      for(int i=0; i<=list.size()-1; i++){
      if(list.get(i).length()<max){
      max=list.get(i).length();
      }

      }
      return max;
      }

arrow