2017-09-01 37 views
-2

我有一个Integer键入ArrayList,我想遍历我的列表,并能够匹配当前索引项的所有重复项。查找列表中的副本

for(int i = 0; i < list.size(); i++) { 
    if(list.get(i) == list.get())//stuck here 

//I want to scan the list if the current element has the same value to 
//other elements while ignoring the value of my current index 

任何帮助,将不胜感激。谢谢!

+4

我不明白你想要什么实现。代码应该返回或打印什么? “匹配每一个”不是很清楚。给出一个示例输入和一个示例输出。 –

+0

由于卡住了,我还没有输出。我只希望for循环匹配'ArrayList '中的每个值,而忽略for循环中的当前索引(即'i') – GGWP

+0

如果您不知道输出**应该是什么**,你可以执行任何事情。 –

回答

0
for(int i = 0; i < list.size(); i++) { 
    // I have used Equal here but you can use "==" if you need to do   // it stronge 
    list.stream().filter(t->!t.equal(list.get(i))).foreach(t->{ 
       // do what you want to do here 
    }) 
} 
+0

'list [i]'(不正确的语法)应该从过滤器中排除。 –

+0

@ PM77-1什么是不正确的语法?列表是arraylist的权利? –

+0

@ PM77-1 ohhh对呀:)谢谢! –

1

应该是这样的:

int currentIndex = 3; 
T value = list.get(currentIndex); 
Iterator<T> it = list.iterator(); 
for (int i = 0; it.hasNext(); i++) { 
    T checkValue = it.next(); 
    if (i == currentIndex) continue; 
    if (value != checkValue) continue; 

    // whatever should take place in case of equality 
} 

我认为有“重复”你真的是一个对象列表,而不是对象相等是相同的实例。在这种情况下!value.equals(checkValue)应使用(额外的检查不是空,以防止异常值)

0

我想尝试一种更符合逻辑的做法:

for(Object element : list){ 
    if(1<Collections.frequency(list,element)){ // count occurrences of the element 
    /// 
    } 
} 
+0

Map > duplicates = IntStream.range(0,list.size()) .mapToObj(Integer :: valueOf) .collect(Collectors.groupingBy(i - > list.get(i),Collectors 。设置())); – egorlitvinenko