我试图弄清楚如何处理过滤项目。我能够一次按一个字段过滤我的收藏集(由于使用了番石榴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()获得的值再次使用相同的方法对其进行过滤吗?简而言之-过滤一下曾经过滤的内容,直到感到满意或返回列表中没有任何内容为止。
答案 0 :(得分:4)
可能类似:
List<Message> messageStorage = new ArrayList<>(); // messageStorage.getAll()
String userChoice = "";
while (!userChoice.equalsIgnoreCase("No")) {
messageStorage = filterMessages(messageStorage); // modifying the existing list
System.out.println("Want to continue filtering? Yes/No");
userChoice = scanner.next();
}
我刚刚将您的filterMessages
方法调整为:
List<Message> filterMessages(List<Message> messageStorage) {
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())
);
return messageStorage.stream()
.filter(m -> criteria.get(filteringOption).test(userInput, m))
.collect(Collectors.toList());
}