Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a stream for certain conditions

I am looking for a Java library that allows to match a sequence of objects, potentially mixing with matchers such as those of hamcrest.

Ideally I would like to write a test that can check that an iterable contains a sequence that would look like a regular expression, but for objects rather than character strings:

assertThat(myList).inSequence(oneOrMore(any()),zeroOrMore(equals(MyObject)));

Mockito with verify is close what I would like, but some simple matchers are missing (like zeroOrMore)

Alexandre

like image 583
alex_C Avatar asked May 24 '11 10:05

alex_C


2 Answers

Simplest solution i can think of is building a string with a letter for each object, and then use regex as usual.

public boolean matchObjects() {
    Object a = new Object();
    Object b = new Object();
    Object c = new Object();
    Object d = new Object();
    ArrayList<Object> arrayList = new ArrayList<Object>();
    arrayList.add(a);
    arrayList.add(b);
    arrayList.add(c);
    arrayList.add(b);
    arrayList.add(d);
    Iterable<Object> iterable = arrayList;
    String result = "";
    for (Object object : iterable) {
        if (object.equals(a))
            result += "a";
        else if (object.equals(b))
            result += "b";
        else if (object.equals(c))
            result += "c";
        else if (object.equals(d))
            result += "d";
        else
            result += "x";
    }
    Pattern pattern = Pattern.compile("a.*b");
    return pattern.matcher(result).find();
}
like image 133
Dorus Avatar answered Sep 30 '22 12:09

Dorus


Take a look at this google project called ObjRegex. It sounds like what I think you're looking for. I was really interested in your question because I implemented something like this in C#, but it's proprietary and I can't share it.

like image 26
agent-j Avatar answered Sep 30 '22 10:09

agent-j