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:

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

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