//我试图在我的 ArrayList 中找到最大的字符串并将其打印出来,还包括最大元素所在的索引并将其也打印到屏幕上。我只是想知道我哪里出错了。
谢谢。
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);
}
}
最佳答案
您还可以使用 java.util.Collections.max
或 Stream
版本:
Java 8
String max = Collections.max(strings, Comparator.comparing(String::length)); // or s -> s.length()
或
String max = strings.stream().max(comparing(String::length)).get();
Java 8 之前的版本
String max = Collections.max(Str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
然后
System.out.println("Index " + arr.indexOf(max) + " " + max + " " + "is the largest and is size " + max.length());
关于java - 查找 ArrayList 中的最大字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593820/