0

A Java list has repeated elements like

[cat, apple, iphone, football, apple, adam, apple, football, cat, people, cat]
  • cat repeated 3 times
  • football repeated 2 times
  • apple repeated 3 times

How to extract only the repeated elements from the list such that the final list has [cat, apple, football]?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Vishnu Kumar
  • 59
  • 1
  • 2
  • 7

5 Answers5

2

Use Set:

List<String> findDuplicates(List<String> original) {
    Set<String> seen = new HashSet<String>();
    Set<String> seenTwice = new HashSet<String>();

    for (String s: original) {
        if (!seen.add(s)) {
            seenTwice.add(s);
        }
    }
    return new ArrayList<String>(seenTwice);
}
Brigham
  • 14,395
  • 3
  • 38
  • 48
1

something like:

String temp;
ArrayList<String> newStrings= new ArrayList<String>();
int x =0;
while(x < list.length){
 list.temp = get(x);
 for(int i =0; i < list.length; i++){
  if(temp.equals(list.get(i)) && i != x)
   newStrings.add(temp);



 }
x++
}

think that will add them to a new arraylist for you from the old one

Lain
  • 2,166
  • 4
  • 23
  • 47
  • The while loop is infinite. Also, this code never checks `i != x`, so once you fix the infinite loop, it will end up adding every element to the `ArrayList`, whether or not it's a duplicate. – Brigham Feb 22 '14 at 06:08
  • @Brigham Fixed it up, just tried to write it up real quick. Should be better now – Lain Feb 22 '14 at 06:31
1

Check here there is a find duplicates method in the comments that should solve your problem

How do I remove repeated elements from ArrayList?

Community
  • 1
  • 1
Mobius
  • 153
  • 8
0

idea(s) : use a map Map<String, Integer> that maps from word to occurance

jmj
  • 237,923
  • 42
  • 401
  • 438
0

Another idea:

1. Create a set to store repeating items.
2. Create a set to store already seen items.
3. Begin loop to iterate around the array/list you have.
  3.1. If the current item is found in the already seen items set add it to repeating items set.
  3.2. Add the current item to already seen items set.
4. End loop.
RaviH
  • 3,544
  • 2
  • 15
  • 14