java - 查找数组中长度最小的所有字符串
问题描述
words
我想从我的数组中返回最小值
找到最短的单词很容易,但我不确定如何返回一个包含最短单词的新数组。
public class Test{
public static void main(String args[]){
String[] words = {"What", "is", "the", "shortest", "word", "is"};
String shortest = words[0];
for ( int i=0; i<words.length; i++){
if(words[i].length() <= shortest.length()){
shortest = words[i];
}
}
System.out.println(shortest);
}
}
预期的输出类似于shorestWords [] = {"is", "is"}
解决方案
你可以做:
// Finding the shortest length
int shortestLength = Arrays.stream(words)
.mapToInt(String::length)
.min()
.getAsInt();
// Retrieve only shortest length strings
String[] shortestLengthStrs = Arrays.stream(words)
.filter(str -> str.length() == shortestLength)
.toArray(String[]::new);
推荐阅读
- azure-cosmosdb - cosmos SQL 是否支持使用 AltLink 进行查询的方式?
- android - Android自定义迁移Sqlcipher从3到4
- r - 在每行和报告列名中查找最大值
- php - Bitninja 是否有 sql 注入误报?
- database - 如何将excel文件作为POST发送以由php页面处理
- siesta-swift - 如何在午睡中覆盖某些资源的默认(“**”)装饰器?
- assembly - 如何直接从 Assembly (x86) 中动态调用 LoadLibraryA?
- microsoft-teams - 用于团队的 MS Graph API - Webhook
- android - Flutter StartApp 插件
- c# - 有什么方法可以让分支覆盖率达到 100%?