首页 > 解决方案 > 查找数组中长度最小的所有字符串

问题描述

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"}

标签: javaarraysstring

解决方案


你可以做:

// 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);

推荐阅读