我是Java的初学者。您能帮我找到给定数组中所有最大的字符串吗?
String[] allLongestStrings(String[] a) {
List<String> newArray = new ArrayList<String>();
String max = a[0];
for( int i = 0; i < a.length; i++){
int sum = max.compareTo(a[i]);
if( sum < 0) max = a[i];
}
for( int i = 0; i < a.length; i++){
int b = max.compareTo(a[i]);
if (b == 0) newArray.add(a[i]);
}
String[] stringArray = newArray.toArray(new String[0]);
return stringArray;
}
答案 0 :(得分:0)
快速解答:
String[] allLongestStrings(String[] arr) {
int longest = Arrays.stream(arr)
.mapToInt(String::length)
.max()
.orElse(-1);
return Arrays.stream(arr)
.filter(s -> s.length() == longest)
.toArray(String[]::new);
}
详细的答案有两种方式:
public static void main(String[] args) {
String[] arr = new String[4];
arr[0] = "cat";
arr[1] = "mouse";
arr[2] = "goose";
arr[3] = "owl";
String[] resultJava8 = allLongestStringsJava8(arr);
String[] resultTraditionalWay = allLongestStringsTraditionalWay(arr);
}
static String[] allLongestStringsJava8(String[] arr) {
int longest = Arrays.stream(arr)
.mapToInt(String::length)
.max()
.orElse(-1);
return Arrays.stream(arr)
.filter(s -> s.length() == longest)
.toArray(String[]::new);
}
static String[] allLongestStringsTraditionalWay(String[] arr) {
Set<String> result = new HashSet<>(); //or use a LinkedList if there can be same strings
int longestLength = 0;
for (String s : arr) {
if (s.length() < longestLength)
continue;
if (s.length() > longestLength)
result.clear();
result.add(s);
longestLength = s.length();
}
return result.toArray(new String[0]);
}
答案 1 :(得分:-1)
您可以使用以下代码:
public static void main(String[] args) {
String[] a = new String[] {"ab", "abc", "a", "def"};
int maxLength = Arrays.stream(a).max(Comparator.comparing(s -> s.length())).get().length();
System.out.println(Arrays.stream(a).filter(str -> str.length() == maxLength).collect(Collectors.toList()));
}
输出:
[abc, def]