如何在循环列表时重置for循环?例如,当列表中有重复项时,我希望for循环重置,即(i = 0和j = 1)。
在这段代码中,当列表中的后续条目相同时,我希望删除重复项并重置for循环。例如,我们有
list1 = [东,西,西,东]
我希望结果list1等于空列表。
这是因为,当" west"条目被删除,这导致列表更新为[east,east]。由于这也是重复的,因此结果必须是空列表[]。
j=1;
for (int i=0;i<(list1.size()-1);i++){
if((list1.get(i)==list1.get(j))){
list1.remove(i);
list1.remove(i);
i=0;
j=1;
}else{
j++;
}
}
答案 0 :(得分:1)
如果您想删除重复项,为什么不使用Set?
String[] list1 = {"east", "west", "west", "east"};
List<String> list = new ArrayList<>(Arrays.asList(list1));
Set<Object> alreadyPresent = new HashSet<>();
Iterator<String> iterator = list.iterator();
for (String element : new ArrayList<String>(list)) {
if (!alreadyPresent.add(element)) {
while(list.remove(element));
}
}
编辑(好多了):
String[] list1 = {"a","b","b","a","d","e","f"};
List<String> list = new ArrayList<>(Arrays.asList(list1));
for (String element : new ArrayList<String>(list)) {
if(Collections.frequency(list, element) > 1) {
while(list.remove(element));
}
}
答案 1 :(得分:1)
你可以反过来遍历ArrayList:
ArrayList<String> list1 = new ArrayList<String>(Arrays.asList(new String[]{"east", "west", "west", "east", "foo"}));
for (int i = (list1.size() - 2);i >= 0;i--){
for(int j = (list1.size() - 1);j > i;j--) {
if((list1.get(i).equals(list1.get(j)))) {
list1.remove(i);
list1.remove(i);
}
}
}
System.out.println(list1);
答案 2 :(得分:0)
List<String> list1 = new ArrayList<String>();
list1.add("east");
list1.add("east");
list1.add("west");
list1.add("test");
list1.add("west");
int j=1;
for (int i=0;i<list1.size();i++){
//here you can say if you want exactly two or more
if(Collections.frequency(list1, list1.get(i)) > 1) {
list1.removeAll(Collections.singleton(list1.get(i)));
i=0;
}
}
System.out.println(list1);
答案 3 :(得分:0)
尝试模块化您的代码更多一点!
// The function you are trying to impliment
void removePairs(List<Object> list) {
while (removePair(list)) {}
}
让我们使用辅助方法让我们的生活更轻松
// Return true if successfully removed a pair
boolean removePair (List<Object> list) {
for(i = 0; i < list.size() - 1; i++) {
// Get the next objects
Object firstObject = list.get(i);
Object secondObject = list.get(i + 1);
if (firstObject.equals(secondObject)) {
list.remove(i);
list.remove(i + 1);
return true;
}
}
return false;
}
另外一点,j = 1
不应该是它的位置。我指的是变量范围。在原始代码中,在for循环完成后,您(希望)不会关心j
。但它仍然在闲逛,等待它被用于不应该的东西时出现错误!
答案 4 :(得分:0)
说明问题:如果在重复值的序列中显示[..., a, a, ...]
,则要删除它们,并递归。
最具可读性的是取消j
或int j = i - 1;
。
List<String> list = new ArrayList<>();
Collections.addAll(list, "east", "west", "west", "east");
for (int i = 1; i < list.size(); ++i) {
String value = list.get(i);
int priorI = i - 1;
if (value.equals(list.get(priorI))) {
list.remove(priorI);
list.remove(priorI);
// next i will be priorI but at least 1
i = Math.max(0, priorI - 1); // With ++i will be > 0
}
}