java - 返回按字母顺序排序的动物列表,其最后一个字母不以参数中列出的任何字母结尾

标签 java list collections

我需要创建一个方法,返回一个按字母顺序排列的动物列表,这些动物不以参数数组中的任何字母结尾。返回的列表中也不应该有重复项

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/

相关文章:

javascript - 将数组转换为嵌套对象列表 - Eloquent Javascript 4.3

c# - 具有多个具有相同键的条目的字典

Java:添加到集合 map

java - 如果对象具有相同字段,如何过滤和组合对象

java - 涉及通过 LAN 连接的 2 台机器的 rmi 程序示例

java - JAXB - 这些对象是无状态的 - JAXBContext、Marshaller、Unmarshaller

string - 解析命令行参数来处理 bash 中的文件列表?

java - 在 ComponentListener 中传递 2 个对象以及这些对象

java - spring mvc Controller 类不工作

c# - 在嵌套列表中按属性排序列表