java findall_Java中.NET数组/列表的通用FindAll方法的简单实现

java findall

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "

去年被问到一个问题后,我进入了一种心情,在那里我做了一些研究和编码,只是为了乐趣和学习。 随后,从这次旅程中,我将这篇文章整理成“

Range Searching Using Visual Basic.NET".  Being the Java nut that I am, I would not have felt complete, if I didn't also play with this topic in Java; therefore, you can also read on " 使用Visual Basic.NET进行范围搜索 “。如果我也没有在Java中玩过这个主题,那么我就不会感到很完整;因此,您也可以阅读” Range Searching Using Java" which has the origins of some of the code used in this article. 使用Java进行范围搜索 “它具有本文中使用的某些代码的起源。

What does the FindAll method have to do with anything?

FindAll方法与什么有什么关系?

[The FindAll generic method] retrieves all the elements that match the conditions defined by the specified predicate.
[FindAll泛型方法]检索与指定谓词定义的条件匹配的所有元素。

Very concise definition for a nice generic method in .NET I found to be similarly short and sweet.  In my research, the goal was to create a more efficient means of searching for values in an array/list that met specific criteria without having to loop through each value.  What I found was the FindAll method proved to be faster both in performance and actual code implementation.

我发现.NET中一个很好的通用方法的定义非常简洁,同样简短而优美。 在我的研究中,目标是创建一种更有效的方法来搜索满足特定条件的数组/列表中的值,而不必遍历每个值。 我发现,事实证明FindAll方法在性能和实际代码实现上都更快。

System.Array.FindAll(arrayOfObjects, _
   New Predicate(Of String)(AddressOf MatchRange) _
)

Just one line of code to use as FindAll utilizes a delegate function known as a Predicate that takes one argument and returns a true or false if the argument meets criteria specified within the predicate's implementation.

用作FindAll的只有一行代码利用了称为谓词的委托函数,该函数接受一个参数,如果该参数满足在谓词的实现中指定的条件,则返回true或false。

'Delegate implementation for Predicate needed in System.Array.FindAll
Function MatchRange(ByVal n As String) As Boolean
    Return Ranges.MatchRange(n, RANGE_START, RANGE_END)
End Function

For a better look at delegates from a Java perspective, you can read "A Java Programmer Looks at C# Delegates" by Steven M. Lewis and Wilhelm Fitzpatrick.

为了从Java角度更好地了解委托,您可以阅读Steven M. LewisWilhelm Fitzpatrick撰写的Java程序员看C#委托 ”。

For my simple implementation, I chose to go with a Predicate interface and anonymous inner classes to simulate the delegate functionality.

对于我的简单实现,我选择使用Predicate接口和匿名内部类来模拟委托功能。

1.创建谓词接口。 (1. Create Predicate Interface.)

/**
 * Predicate interface used to emulate .NET 
 * <code>System.Predicate(Of T)</code>.
 */
package com.blogspot.crossedlogic.rangesearching;

public interface Predicate<T> {
    
    /**
     * @param obj - object to test against predicate criteria.
     * @return boolean flag indicating a match (true) or no match (false).
     */
    public boolean isMatch(T obj);
}

2.创建FindAll函数。 (2. Create FindAll Function.)

In .NET, you can utilize shared (static) functions from the List/Array class or from an instance of an implementation of List; therefore, a findAll method could be added to a custom List implementation in Java, but the code I went with uses a utility class that I could store other functions relating to predicates.

在.NET中,您可以利用List / Array类或List实现的实例中的共享(静态)函数。 因此,可以将findAll方法添加到Java中的自定义List实现中,但是我使用的代码使用了一个实用程序类,该类可以存储与谓词有关的其他函数。

package com.blogspot.crossedlogic.rangesearching;


import java.util.ArrayList;
import java.util.List;


public class Predicates {

    /**
     * Replicate .NET findAll and <code>Predicate</code>.
     * 
     * @param <T>
     * @param array - an array of objects of type <T>.
     * @param match -
     *            <p>
     *            instance of an implementation of the Predicate
     *            interface.
     *            </p>
     * @return List<T> representing all matches found.
     * @see com.blogspot.crossedlogic.rangesearching.Predicate
     */
    public static <T> List<T> findAll(T[] array,
            Predicate<T> match) {
        List<T> lst = new ArrayList<T>();

        for (T obj : array) {
            if (match.isMatch(obj)) {
                lst.add(obj);
            }
        }

        return lst;
    }

    /**
     * Replicate .NET findAll and <code>Predicate</code>.
     * 
     * @param <T>
     * @param list - collection of objects of type <T>.
     * @param match - instance of an implementation of the
     *            Predicate interface.
     * @return List<T> representing all matches found.
     * @see com.blogspot.crossedlogic.rangesearching.Predicate
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> findAll(List<T> list,
            Predicate<T> match) {
        return findAll((T[]) list.toArray(), match);
    }
}

3.享受! (3. Enjoy!)

package com.expertsexchange.articles;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import com.blogspot.crossedlogic.rangesearching.Predicate;
import com.blogspot.crossedlogic.rangesearching.Predicates;


public class PredicateMatchExample {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<Number> numbers = new ArrayList<Number>();
        List<Number> matches;

        for (int i = new Random(System.currentTimeMillis())
                .nextInt(10); i < 100; i += 7) {
            numbers.add(i);
        }

        displayNumbers(numbers, "All Numbers");

        // find all the perfect squares.
        matches = Predicates.findAll(numbers
                .toArray(new Number[] {}),
                new Predicate<Number>() {

                    @Override
                    public boolean isMatch(Number n) {
                        double sqrt = Math.sqrt(n.doubleValue());
                        return Math.ceil(sqrt) == sqrt;
                    }
                });

        displayNumbers(matches, "Perfect Squares");

        // find all numbers less than 50.
        matches = Predicates.findAll(numbers,
                new Predicate<Number>() {

                    @Override
                    public boolean isMatch(Number n) {
                        // mimic .NET delegate method;
                        // utilize existing method for
                        // implementation.
                        return isLessThan50(n);
                    }
                });

        displayNumbers(matches, "Less Than 50");
    }

    static boolean isLessThan50(Number n) {
        return n.intValue() < 50;
    }

    static void displayNumbers(List<Number> numbers, String title) {
        System.out.printf("%s: %s.", title,
                (numbers.size() > 0) ? Arrays.toString(
                        numbers.toArray()).replaceAll(
                        "^\\[|\\]$", "") : "none");
        System.out.println("");
    }
}
Predicates.findAll(numbers, new Predicate<Number>() {
    @Override 
    public boolean isMatch(Number n) { 
        return isLessThan50(n); 
    }
});

I found the FindAll method very useful and I am hoping you will as well.  In addition, having a Predicate concept in Java may come in handy for other projects as well.

我发现FindAll方法非常有用,希望您也能如此。 另外,在Java中具有谓词概念也可能对其他项目很有用。

Thanks for taking the time to read the above.  If you have any questions on how the code works that is not explained well enough in the code comments, please post below and I will be happy to clarify.

感谢您抽出宝贵的时间阅读以上内容。 如果您对代码的工作方式有任何疑问,但在代码注释中没有充分解释,请在下面发布,我们将很乐于澄清。

Happy coding!

编码愉快!

Best regards,

最好的祝福,

Kevin (aka MWVisa1)

凯文(又名MWVisa1)

翻译自: https://www.experts-exchange.com/articles/912/Simple-Implementation-of-NET-Array-List's-Generic-FindAll-Method-in-Java.html

java findall

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值