java - 返回按字母顺序排序的动物列表,其最后一个字母不以参数中列出的任何字母结尾
问题描述
我需要创建一个方法,该方法返回一个按字母顺序排列的动物列表,这些动物不以参数数组中的任何字母结尾。返回的列表中也应该没有重复项
public class TrimmList
{
private List<String> inList = new ArrayList<String>(Arrays.asList("aardvark",
"cow", "dog", "cow",
"elephant","dog", "frog", "bird", "swan", "python", "pig"));
public List<String> trimList(char[] args)
{
Set<String> toRemove = new HashSet<>();
for (String a : arr) {
for (String i : inList) {
if (i.endsWith(a)) {
toRemove.add(i);
}
inList.removeAll(toRemove);
}
}
System.out.println(inList);
// [bird, aardvark, cow, elephant]
}
因此,例如,如果参数中的一个字母是“g”,则不应返回 pig
非常感谢任何建议
解决方案
如果你想要更少的 lambda 表达式,你也可以使用这个片段。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TrimList {
private List<String> inList = new ArrayList<String>(Arrays.asList("aardvark", "cow", "dog", "cow",
"elephant", "dog", "frog", "bird", "swan", "python", "pig"));
public List<String> trimList(char[] args) {
inList = new ArrayList<>(new HashSet<>(inList));
List<String> temp = new ArrayList<>();
for (String animal : inList) {
for (char c : args) {
if (animal.endsWith(String.valueOf(c))) {
temp.add(animal);
}
}
}
inList.removeAll(temp);
Collections.sort(inList);
System.out.println(inList);
return inList;
}
}
输出将是
[aardvark, bird, cow, elephant, python, swan]
推荐阅读
- jquery - 垂直滚动防止父 div 水平滚动的子级
- javascript - React:在渲染方法中调用 setState 会引发错误
- javascript - 错误:数据不应为空或应包含“字段”选项
- javascript - 将键值对添加到 redux 存储
- android-fragments - 在片段之间切换时防止刷新片段
- qt - 如何让AUTOMOC在QT5中找到头文件
- java - 使用连接的 Java 字符串掩码
- java - 从 Java 8 升级到 Java 11 - 包 sun.util 不存在
- r - 导出到 .csv R 后字符发生变化
- wpf - 我们可以在窗口上使用多 xaml 布局吗?