首页 > 解决方案 > 返回按字母顺序排序的动物列表,其最后一个字母不以参数中列出的任何字母结尾

问题描述

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

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

非常感谢任何建议

标签: javalistcollections

解决方案


如果你想要更少的 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]

推荐阅读