简体   繁体   English

Java库方法,用于在集合中查找项目并检查是否完全匹配

[英]Java library method to find an item in a collection AND check if there was exactly one match

Does any common Java library provide a method to find an element in a finite collection and ensure that there was exactly one match ? 是否有任何通用的Java库提供一种在有限集合中查找元素 确保完全匹配的方法

The method could, for example, return null if nothing was found and throw an exception if multiple elements were found. 例如,如果找不到任何内容,则该方法可以返回null如果找到多个元素,则可以引发异常。

Currently I use my own Implementation (see below), but I'd rather not pollute business code with such utility methods (even if extracted in a separate utility package). 当前,我使用自己的实现(请参见下文),但我不希望使用此类实用程序方法来污染业务代码(即使是从单独的实用程序包中提取出来的)。

I also don't want the overhead of iterating over collection more than once, or an overhead of filtering collection and looking at the length of the result. 我也不想多次遍历集合的开销,或者过滤集合并查看结果长度的开销。

PS my current solution (which works, but is to be replaced with a library method): PS我当前的解决方案(可以,但是将由库方法代替):

public static <T> T getSingleMatch(Iterable<T> lookIn, com.google.common.base.Predicate<? super T> predicate) {
    T foundItem = null;
    for (T item : lookIn) {
        if (predicate.apply(item)) {
            if (foundItem != null) 
                throw new RuntimeException("multiple matches"); // alternatively: `return null;` 
            else 
                foundItem = item;
        }
    }
    // alternatively: `if (foundItem == null) throw ...`
    return foundItem;
}

One option is to separate out the two ideas into two methods, so that each method does one thing - then combine the calls 一种选择是将这两种想法分为两种方法,以便每种方法都可以做一件事-然后组合调用

  • One method to lazily filter, returning a sequence of matching results 延迟过滤的一种方法,返回一系列匹配结果
  • One method to return an item from a sequence, requiring it to be the only item 一种从序列中返回项目的方法,要求它是唯一的项目

Guava has both of those: 番石榴有两个:

So for example: 因此,例如:

String match = Iterables.getOnlyElement(Iterables.filter(source, predicate));
int index = collection.indexOf(item);
if (index != -1 && index == collection.lastIndexOf(item)) {
    // one and only one
}

If index != -1 it means no such item. 如果index != -1则表示没有此类项目。 If the next if statement doesn't evaluate to true it means that there are at least 2 items. 如果下一个if语句的求值结果不为true,则表示至少有2个项目。 You can restructure it to throw exceptions, return null or return the index or item. 您可以对其进行重组以引发异常,返回null或返回索引或项目。 I trust you know how to do this based on your question. 我相信您会根据自己的问题知道该怎么做。

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

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