Finding Largest String in ArrayList
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());
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);
}
}