stream 过滤俩个字段,使用Java 8流过滤包含来自另一个列表中的一个或多个字符串的字符串列表...

I want to use the strings imputed in a TextField to filter a list. I am using a KeyReleased Event on the TextField to filter the list on every key. The piece of code below filters the list when I type in a word, but when I press space and start typing another word the list gets empty. I am a bit new to streams. I don't know what I am doing wrong.

private ObservableList productList;

@FXML

private JFXTextField searchField;

@FXML

private TableView productTable;

@FXML

void searchKeyReleased(KeyEvent event) {

String searchText = searchField.getText();

List searchableWords = Arrays.asList(searchText.toLowerCase().trim().split("\\s+"));

List filteredList = searchableWords.stream()

.flatMap(i ->productList.stream()

.filter(j -> j.getPartDesc().toLowerCase().contains(i)))

.collect(Collectors.toList());

ObservableList productFilteredList = FXCollections.observableArrayList(filteredList);

productTable.setItems(productFilteredList);

}

----------

public class Products_Data {

private final StringProperty partDesc = new (this,"PartDesc",null);

public Products_Data() {}

public final StringProperty getPartDescProperty() {return partDesc;}

public final String getPartDesc(){return partDesc.get();}

public final void setPartDesc(String partDesc) {

getPartDescProperty().set(partDesc);

}

}

解决方案

I can’t see a fundamental problem in your Stream code. The way, you’ve written it, is not very efficient and it allows elements matching multiple words to occur multiple times in the result list. Perhaps, the UI you’re setting the result on can’t handle this.

I’d create a single filter out of the entered text, which will match if any of the words appears in the element, using a case insensitive matching instead of repeatedly converting every string to lowercase. E.g. with a utility method like this:

static final Pattern SPACE = Pattern.compile("\\s+");

public static Predicate getFilter(Function super T, String> f, String words) {

String regex = SPACE.splitAsStream(words)

.map(Pattern::quote).collect(Collectors.joining("|"));

Predicate sp = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).asPredicate();

return t -> sp.test(f.apply(t));

}

which can be used as

List filteredList = productList.stream()

.filter(getFilter(Products_Data::getPartDesc, searchField.getText()))

.collect(Collectors.toList());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值