Java - 为过滤函数创建循环

我试图弄清楚如何处理过滤项目。我能够一次按一个字段过滤我的集合(感谢 guava Immutable.of),但我不得不创建一种方法来一次又一次地过滤我的集合,直到用户告诉我(例如,在开关)他已经完成并想要返回主菜单。


private String filterOption() {

    System.out.println("What fields should I filter by? :\n" +

            "title\n" +

            "author\n" +

            "content\n" +

            "date\n");

    String filteringOption = scanner.nextLine();

    return filteringOption;

}


private String filterValue() {

    System.out.println("What value you want to use for filtering? :\n");

    String userInput = scanner.nextLine();

    return userInput;

}


public List<Message> filterMessages() {


    String filteringOption = filterOption();

    String userInput = filterValue();


    Map<String, BiPredicate<String, Message>> criteria = ImmutableMap.of(

            "title", (userTitle, message) -> userInput.equals(message.getTitle()),

            "author", (userAuthor, message) -> userInput.equals(message.getAuthor()),

            "content", (userContent, message) -> userInput.equals(message.getContent()),

            "date", (userDate, message) -> userInput.equals(message.getCreationDate())

    );


    BiPredicate<String, Message> predicate = criteria.get(filteringOption);


    filteredMessages = messageStorage.getAll().stream() //getAll() is to get entire collection

            .filter(m -> predicate.test(userInput, m))

            .collect(Collectors.toList());


    return filteredMessages;

}

有人可以告诉我一种方法,允许用户使用他们从 filterMessages() 获得的值再次使用相同的方法过滤它们吗?简而言之 - 过滤曾经过滤过的内容,直到您满意或返回列表中没有任何内容。


不负相思意
浏览 135回答 1
1回答

猛跑小猪

可能是这样的:List<Message> messageStorage = new ArrayList<>(); // messageStorage.getAll()String userChoice = "";while (!userChoice.equalsIgnoreCase("No")) {&nbsp; &nbsp; messageStorage = filterMessages(messageStorage); // modifying the existing list&nbsp; &nbsp; System.out.println("Want to continue filtering? Yes/No");&nbsp; &nbsp; userChoice = scanner.next();}我刚刚将您的filterMessages方法调整为:List<Message> filterMessages(List<Message> messageStorage) {&nbsp; &nbsp; String filteringOption = filterOption();&nbsp; &nbsp; String userInput = filterValue();&nbsp; &nbsp; Map<String, BiPredicate<String, Message>> criteria = ImmutableMap.of(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "title", (userTitle, message) -> userInput.equals(message.getTitle()),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "author", (userAuthor, message) -> userInput.equals(message.getAuthor()),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "content", (userContent, message) -> userInput.equals(message.getContent()),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "date", (userDate, message) -> userInput.equals(message.getCreationDate())&nbsp; &nbsp; );&nbsp; &nbsp; return messageStorage.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(m -> criteria.get(filteringOption).test(userInput, m))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java