匹配特定条件的流 [英] Matching a stream for certain conditions
问题描述
我正在寻找一个 Java 库,它允许匹配一系列对象,可能与匹配器(例如 hamcrest 的匹配器)混合使用.
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 与我想要的很接近,但缺少一些简单的匹配器(如 zeroOrMore)
Mockito with verify is close what I would like, but some simple matchers are missing (like zeroOrMore)
亚历山大
推荐答案
我能想到的最简单的解决方案是为每个对象构建一个带有字母的字符串,然后像往常一样使用正则表达式.
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();
}
这篇关于匹配特定条件的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!