简体   繁体   English

如何在数组列表中搜索匹配的元素,然后使用这些元素创建列表

[英]how to search an array list for matching elements then create a list with those elements

My program for university allows me to search for parts in an arraylist i created. 我的大学课程允许我在创建的数组列表中搜索零件。 My goal now is to apply a filter to search for specific types of parts such as 'cpu'. 我现在的目标是应用过滤器来搜索特定类型的零件,例如“ cpu”。

This is what i'm trying to do, i input a word, the word is sent to a loop which checks if any element in the list has that word; 这就是我要尝试的操作,我输入了一个单词,然后将该单词发送到循环,该循环检查列表中是否有任何元素具有该单词; if it does, then it will add it to a new list and print it. 如果是这样,它将把它添加到新列表并打印。 However this is just printing an empty loop. 但是,这只是打印一个空循环。 I'm trying to get it working for just the type of item, then i'll do the price. 我正在尝试使其仅适用于某种类型的物品,然后由我来承担价格。

private void filter(){
    System.out.print("Enter type of part to view ('all' for no filtering): ");
    String filterPart = In.nextLine();
    System.out.print("Enter minimum price ('-1' for no filtering): ");
    double minPrice  = In.nextDouble();
    catalogue.LoopSearch(filterPart);
}

And here is the LoopSearch Method 这是LoopSearch方法

public Part LoopSearch(String filterPart){
    List<Part> list2 = new ArrayList<Part>();
    for (Part part : parts) {
    if (part.hasName(filterPart)) {
        list2.add(part);
    }

    System.out.print(list2);
}
return null;



}

lastly, this is the hasName method 最后,这是hasName方法

public boolean hasName(String filterPart) {
       return filterPart.equals(this.name);
}

The following code can be used to filter the elements: 以下代码可用于过滤元素:

List<Part> newParts = parts.stream()
 .filter(p -> p.hasName(filterPart))
 .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM