我需要创建一个方法,返回一个按字母顺序排列的动物列表,这些动物不以参数数组中的任何字母结尾。返回的列表中也不应该有重复项
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]
关于java - 返回按字母顺序排序的动物列表,其最后一个字母不以参数中列出的任何字母结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61396106/