3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果要使用 JAVA Stream API,對(duì)象必須是 Iterable。正如@Michal 提到的,您可以將其更改為 Collection。從@Michal 的回答中,我們可以簡(jiǎn)化它,就像:
public class JsonArrayIntersectTest {
private boolean anyMatch(JSONArray first, JSONArray second) throws JSONException {
Set<Object> firstAsSet = convertJSONArrayToSet(first);
Set<Object> secondIdsAsSet = convertJSONArrayToSet(second);
// use stream API anyMatch
return firstAsSet.stream()
.anyMatch(secondIdsAsSet::contains);
}
private Set<Object> convertJSONArrayToSet(JSONArray input) throws JSONException {
Set<Object> retVal = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
retVal.add(input.get(i));
}
return retVal;
}
@Test
public void testCompareArrays() throws JSONException {
JSONArray deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
JSONArray deviationIds = new JSONArray(ImmutableSet.of("3", "4", "5"));
Assert.assertTrue(anyMatch(deviation, deviationIds));
deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
deviationIds = new JSONArray(ImmutableSet.of("4", "5", "6"));
Assert.assertFalse(anyMatch(deviation, deviationIds));
}
}

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
任何匹配返回 true 的要求都可以重新表述為非空交集 return true。將JSONArrayinto轉(zhuǎn)換Collection為很容易做到這一點(diǎn),例如像這樣
public class JsonArrayIntersectTest {
private boolean anyMatch(JSONArray first, JSONArray second) throws JSONException {
Set<Object> firstAsSet = convertJSONArrayToSet(first);
Set<Object> secondIdsAsSet = convertJSONArrayToSet(second);
//Set<Object> intersection = Sets.intersection(firstAsSet, secondIdsAsSet); // use this if you have Guava
Set<Object> intersection = firstAsSet.stream()
.distinct()
.filter(secondIdsAsSet::contains)
.collect(Collectors.toSet());
return !intersection.isEmpty();
}
Set<Object> convertJSONArrayToSet(JSONArray input) throws JSONException {
Set<Object> retVal = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
retVal.add(input.get(i));
}
return retVal;
}
@Test
public void testCompareArrays() throws JSONException {
JSONArray deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
JSONArray deviationIds = new JSONArray(ImmutableSet.of("3", "4", "5"));
Assert.assertTrue(anyMatch(deviation, deviationIds));
deviation = new JSONArray(ImmutableSet.of("1", "2", "3"));
deviationIds = new JSONArray(ImmutableSet.of("4", "5", "6"));
Assert.assertFalse(anyMatch(deviation, deviationIds));
}
}
但是,與直接使用 API 的初始版本相比,代碼要多得多JSONArray。它還會(huì)產(chǎn)生比直接 API 版本更多的迭代JSONArray,這可能是也可能不是問題。然而,總的來說,我認(rèn)為在傳輸類型上實(shí)現(xiàn)領(lǐng)域邏輯并不是一個(gè)好的做法,例如JSONArray并且總是會(huì)轉(zhuǎn)換成領(lǐng)域模型。
另請(qǐng)注意,生產(chǎn)就緒代碼還會(huì)null對(duì)參數(shù)進(jìn)行檢查。

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用 XStream 來處理 JSON 映射
或者根據(jù)您檢索字符串的邏輯,您可以比較為
?JSONCompareResult?result?=?JSONCompare.compareJSON(json1,?json2,?JSONCompareMode.STRICT); ?System.out.println(result.toString());
添加回答
舉報(bào)