简体   繁体   English

如何使用 Java 8 中的 Streams 将列表过滤到与提供的后缀匹配的项目

[英]How to filter a list down to items matching supplied suffix using Streams in Java 8

I am new to Java streams but need to master by practice really!我是 Java 流的新手,但真的需要通过实践来掌握!

The collection input is made up of strings eg [name][dot][country], example as follows:集合输入由字符串组成,例如 [name][dot][country],示例如下:

 - JAMES.BRITAIN
 - JOHN.BRITAIN
 - LEE.BRITAIN
 - GEORGE.FRANCE
 - LEON.FRANCE
 - MARSELLE.FRANCE
 - KOFI.GHANA
 - CHARLIE.GHANA

Given a list of countries, How do I return a list of items whose suffixes matches the supplied countries给定国家/地区列表,如何返回后缀与提供的国家/地区匹配的项目列表

So, if I supplied a list parameter containing Britain as item, the resulting list should be:因此,如果我提供了一个包含英国作为项目的列表参数,则结果列表应该是:

 - JAMES.BRITAIN
 - JOHN.BRITAIN
 - LEE.BRITAIN

In the real code the streams statement below gives me the list to be filtered ie:在实际代码中,下面的流语句为我提供了要过滤的列表,即:

List<String> allSolrCollections =  (List<String>) findAllCollections()
                    .getJsonArray(SOLR_CLOUD_COLLECTION)
                    .getList()
                    .stream() 
                    .map(object -> Objects.toString(object, null))
                    .collect(Collectors.toList());

That is:那是:

 - JAMES.BRITAIN
 - JOHN.BRITAIN
 - LEE.BRITAIN
 - GEORGE.FRANCE
 - LEON.FRANCE
 - MARSELLE.FRANCE
 - KOFI.GHANA
 - CHARLIE.GHANA

But, I had to use the following non-stream code to filter by suffice name:但是,我必须使用以下非流代码按足够的名称进行过滤:

private List<String> getCollectionsFilteredBySuffices(List<String> listParam, List<String> allItemsList) {
         
        List<String> finalList = new ArrayList<>();
        for (String country: listParam) {
             for (String item: allItemsList) {
                if (item.endsWith(country)) {
                    finalList .add(item);
                }
            }
        }
        return finalList ;
    }

Can I do both logic in a single java stream statement eg我可以在一个 java stream 语句中执行这两个逻辑吗?

 List<String> allSolrCollections =  (List<String>) findAllCollections()
                        .getJsonArray(SOLR_CLOUD_COLLECTION)
                        .getList()
                        .filter(//all items with suffices matching content of list param)
                        .stream() 
                        .map(object -> Objects.toString(object, null))
                        .collect(Collectors.toList());

Regardless of the implementation, your method would be more performant if you generate a HashSet of prefixes.无论实现如何,如果您生成一个HashSet前缀,您的方法将更加高效。 That would allow to check each element in the list against this set in constant time.这将允许在恒定时间内对照该集合检查列表中的每个元素。

To achieve it with streams, you need to apply filter() operation, which expects a Predicate and would retain in the stream those elements for which the predicate would be evaluated to true .要使用流实现它,您需要应用filter()操作,该操作需要一个Predicate并将保留在 stream 中那些谓词将被评估为true的元素。

Since your data has a structure [name][dot][country] , you can use regular expression "[^.]*\\."由于您的数据具有[name][dot][country]结构,因此您可以使用正则表达式"[^.]*\\." , which matches zero or more symbols distinct from a dot followed by a dot , to extract the suffix that corresponds to a country. ,它匹配零个或多个与点不同的符号,后跟一个,以提取对应于国家/地区的后缀。

That's how it might be implemented.这就是它可能实现的方式。

private List<String> getCollectionsFilteredBySuffices(List<String> listParam,
                                                      List<String> allCollections) {

    Set<String> suffixes = new HashSet<>(listParam);
    
    return allCollections.stream()
        .filter(s -> suffixes.contains(s.replaceAll("[^.]*\\.", "")))
        .collect(Collectors.toList()); // or .toList() for Java 16+
}

Here's a single-statement solution (if you want the code to be consice at all costs):这是一个单语句解决方案(如果您希望代码不惜一切代价保持简洁):

return allCollections.stream()
    .filter(s -> listParam.contains(s.replaceAll("[^.]*\\.", "")))
    .collect(Collectors.toList());

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

相关问题 在 Java 中使用流和过滤器并与可变参数匹配 - Using Streams and filter in Java and matching with a varargs 使用 Java 8 流按日期过滤项目 - Filter out items by Date using Java 8 streams 如何在Java8 Streams中通过多个过滤谓词比较两个Map列表以识别匹配和不匹配的记录 - How to compare Two List of Map to identify the matching and non matching records with multiple filter predicates in Java8 Streams 如何使用 java 流在另一个列表中过滤列表 - How filter list inside another list using java streams 如何使用 Java 8 个流根据 map 参数返回的列表进行过滤 - How to filter based on list returned by map param using Java 8 streams 如何使用 Java 8 流从列表中过滤元素? - How to filter element from a List using Java 8 streams? 如何在 Java 8 Streams 中将字符串列表过滤到由字符串组成的不同列表 - How to filter a list of String down to a distinct list made of string suffices in Java 8 Streams 如何通过&#39;,&#39;使用带&#39;作为前缀和后缀的流来加入列表元素 - How to join a list elements by ',' using streams with ' as prefix and suffix too 列表中的Java流 <Object> 获取任何与filter()匹配的对象的属性 - Java streams on List<Object> get a property of any object matching filter() 使用流过滤Java中的内部和外部列表 - filter inner and outer list in java using streams
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM