java - 使用 for-each 循环时可以跳过部分数组吗?
问题描述
我被告知只从数组中返回具有给定长度的字符串。我可以通过常规的 for 循环轻松做到这一点。但我最近发现了 for-each 循环,我正在尝试学习如何使用它们。这个问题似乎可行,但我可能错了。
有我正在处理的代码:
public List wordsWithoutList(String[] words, int len) {
String[] temp = new String[0];
for (String i : words) {
if (i.length() != len) {
temp = new String[temp.length + 1];
temp[i] = words[i];
}
}
return temp;
}
解决方案
要从数组中返回给定长度的字符串,您可以使用简单的if
语句:
public List<String> givenLength(String[] words, int len) {
List<String> strings = new ArrayList<>();
for (String word : words) {
if (word.length() == len) {
strings.add(word);
}
}
return strings;
}
推荐阅读
- azure - ModuleNotFoundError:'matplotlib_inline'
- c# - 从字符串数组中进行 Elasticsearch 搜索的 C# NEST 客户端
- haproxy - MicroK8s,家庭设置的 HA-Proxy。如何配置端口转发?
- java - 如何使用 selenium java 仅从 excel 的第一列中读取所有行
- python - 将 lambda 函数转换为常规函数
- pandas - 我正在尝试在 pandas 中使用 max 命令,它返回“'Series' object is not callable”,obs:我是新手
- r - 传单多边形填充颜色参数总是产生错误
- python-3.x - 最小化复合函数
- python-3.x - __aenter__ 和 __aexit__ 的返回类型是什么?
- php - 使用“list_terms_exclusions”排除 Wordpress 中的类别未显示结果