9

// Im trying to find the largest String in my ArrayList and print it out and also to include what index the largest element resides at and to print that to screen too. Im just wondering where Im going wrong.

Thanks.

import java.util.Scanner;                  
import java.util.ArrayList;

public class ArraylistString
{
   public static void main(String [] args)
   {
    // Instance of Scanner class
      Scanner keyboardIn = new Scanner(System.in);

   // Declare an array list of Strings
      ArrayList<String> Str = new ArrayList<>();
   // Add names to ArrayList
      Str.add("Jim Bob");
      Str.add("Bobby Jones");
      Str.add("Rob Stiles");
      int largestString = Str.size();
      int index = 0;

   // Use for loop to print out elements from ArrayList
      for(int i = 0; i < Str.size(); i++)
      {  // Test which String is the largest
         if(Str[i].size() > largestString)
         {
            largestString = Str[i].size();
            index = i;
         }

      } 
      // Output largest String and index it was found at
      System.out.println("Index " + index + " "+ Str[index] + " " + "is the largest and is size " + largestString);  

   }

}
4
  • 3
    You could start by identifying how your program is misbehaving. Commented Sep 15, 2015 at 19:17
  • think what initial value should largestString have if you are trying to maximize it. Commented Sep 15, 2015 at 19:19
  • What do you mean by "largest string"? Commented Sep 15, 2015 at 19:19
  • This wouldn't compile at all. Str[i] is not a proper way to access a List. Commented Sep 15, 2015 at 19:19

7 Answers 7

36

You can also use java.util.Collections.max or the Stream version:

Java 8

String max = Collections.max(strings, Comparator.comparing(String::length)); // or s -> s.length()

OR

String max = strings.stream().max(comparing(String::length)).get();

Prior Java 8

String max = Collections.max(Str, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {          
        return o1.length() - o2.length();
    }
});     
    

Then

 System.out.println("Index " + arr.indexOf(max) + " " + max + " " + "is the largest and is size " + max.length());  
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked like a charm. Only one limitation with the logic is if there is more than one string having max length for example "abcd" and "abca" then too it will return only one result.
3

Please try these code . Here i am trying with get() to access the ArrayList elements, which is working correctly.

import java.util.Scanner;                  
import java.util.ArrayList;

class ArraylistString
{
    public static void main(String args[])
    {
        ArrayList<String> Str = new ArrayList<String>();
        Str.add("Jim Bob");
        Str.add("Bobby Jones");
        Str.add("Rob Stiles");
        int largestString = Str.get(0).length();
        int index = 0;

        for(int i = 0; i < Str.size(); i++)
        {
            if(Str.get(i).length() > largestString)
            {
                largestString = Str.get(i).length();
                                index = i;
            }
        }
        System.out.println("Index " + index + " "+ Str.get(index) + " " + "is the largest and is size " + largestString);  

    }

}

Comments

0

You have the correct idea, but wrong syntax. In Java, only arrays support the [] syntax. An ArrayList isn't an array, it's a class that implements the List interface, and you should use the get method to access its members. Similarly, a String doesn't have a size() method, it has a length() method.

Comments

0

I would set your largestString variable to your first String that you add:

int largestString = Str.get(0).length();

Then you should use the following to check for the largest String:

if(Str.get(i).length() > largestString) {
    largestString = Str.get(i).length();
    index = i;
}

You cannot index into an ArrayList with [] as you were trying to do.

I would also suggest better variable names. If I saw Str as a variable I would think it was a String. Maybe try strList or something like that.

Comments

0

From Java-8 and onwards:

    List<Integer> numList = Arrays.stream(Str).map(String::length).collect(Collectors.toList());
    Integer m = numList.stream().mapToInt(i->i).max().orElse(4000);  //get strings with their length
    int k = numList.indexOf(m);  //index of String with Maximum Length
    System.out.println(Str.get(k)); //get your longest string

Comments

0

Using Java 8:

Optional<String> op = Str.stream().sorted((e1,e2)-> e1.length() > e2.length() ? -1 :1).findFirst();
    

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
-2

What are you getting as output?

also, the line

int largestString = Str.size()

is setting largestString as the number of elements in the array Str so that may cause errors. I would set it to 0 or even -1 as a baseline, or maybe Str[0].size() so that you can start your for loop with your first element as your baseline.

EDIT:

I didn't even realize this was Java so like what people are saying, you cannot use the [] operator as you can in most languages and you should use string.length() not str.size()

1 Comment

Not a valid answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.