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”

About Anatoly Spektor

My name is Anatoly Spektor (originally Anatolijs Spektors) I am Software and Web Developer. I have worked in Seneca Center for Development of Open Technology on Big Blue Button Add-on - Polling Module, Red Hat and some other places :) I am an author of the book 'Eclipse Debugging How To', Muay Thai fighter and amateur photographer ;)
This entry was posted in Java, open-source, Useful Functions and tagged , , , , , , , , , , . Bookmark the permalink.

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

  1. jetcracker says:

    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 says:

    If you are using JDK 6 – you can use short for-statement:

    for(String w: wordList) {
        if( w.length() > maxLength ) maxLength = w.length();
    • A says:

      this works too

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

      return max;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s