評論表明,只有明確列出的值應該引起被移除的元素,如:
listOne listTwo Action
"1" "1", "3-9", "11" remove "1", but not "11"
"2" "1", "3-9", "11" do nothing
"3" "1", "3-9", "11" remove "3-9"
"4" "1", "3-9", "11" do nothing (3-9 is not a range)
所以,按照這種怪異的邏輯,這裏有一個例子:
public static void main(String[] args) {
// should remove 3, 6-11, 18-20
System.out.println(remove(Arrays.asList("3", "11", "20"),
new ArrayList<>(Arrays.asList("1", "2", "3", "6-11", "18-20"))));
// should remove 2, not remove 6-11 (not a range), and not remove 18-20 (8 is not 18, 2 is not 20)
System.out.println(remove(Arrays.asList("2", "8"),
new ArrayList<>(Arrays.asList("1", "2", "3", "6-11", "18-20"))));
}
private static List<String> remove(List<String> listOne, List<String> listTwo) {
for (Iterator<String> listIter = listTwo.iterator(); listIter.hasNext();) {
String value = listIter.next();
if (shouldRemove(value, listOne))
listIter.remove();
}
return listTwo; // for easy of use
}
private static boolean shouldRemove(String value, List<String> listOne) {
int idx = value.indexOf('-');
if (idx == -1) {
for (String ref : listOne)
if (ref.equals(value))
return true;
} else {
String value1 = value.substring(0, idx);
String value2 = value.substring(idx + 1);
for (String ref : listOne)
if (ref.equals(value1) || ref.equals(value2))
return true;
}
return false;
}
輸出
[1, 2]
[1, 3, 6-11, 18-20]
你真的意味着你存儲在報名截止範圍?這聽起來像是將新範圍(18,20)這樣的實例存儲在列表中,而不是字符串更合適。 –
由於這些是「String」的列表,因此您的意思是從'listTwo'中刪除任何值,其中'listOne'的值是一個子字符串,例如使用'contains()'? – Andreas
如果這些應該是數字和數字範圍,請不要使用String。另外,如果你從'6-11'中刪除'11',不應該變成'6-10'嗎? – Andreas