How to select duplicate values from a list in java?

后端 未结 13 928
傲寒
傲寒 2021-01-18 00:38

For example my list contains {4, 6, 6, 7, 7, 8} and I want final result = {6, 6, 7, 7}

One way is to loop through the list and eliminate unique values (4, 8 in this

13条回答
  •  轮回少年
    2021-01-18 01:25

    Try this:

    Inspired by this answer: https://stackoverflow.com/a/41262509/11256849

    for (String s : yourList){
         if (indexOfNth(yourList, s, 2) != -1){
             Log.d(TAG, s);
          }
       }
    

    Using this method:

    public static  int indexOfNth(ArrayList list, T find, int nthOccurrence) {
            if (list == null || list.isEmpty()) return -1;
            int hitCount = 0;
            for (int index = 0; index < list.size(); index++) {
                if (list.get(index).equals(find)) {
                    hitCount++;
                }
                if (hitCount == nthOccurrence) return index;
            }
            return -1;
        }
    

提交回复
热议问题