Mefisto_Fell
Mefisto_Fell

Reputation: 916

How to place duplicate elements from a list into an array?

I need to find duplicate items in the collection and put them in an array.

I wrote this method:

String[] mass = new String[(int) limit];

        for (int i = 0; i < duplicates.size(); i++){
            for (int j = 1; j < duplicates.size(); j++){
                if (i != j && duplicates.get(i).equalsIgnoreCase(duplicates.get(j))){
                    mass[j - 1] = duplicates.get(j);
                }
            }

I have this collection:

List<String> duplicates = new ArrayList<>();
        Collections.addAll(duplicates, "java", "JaVa", "mm", "Mama", "ss", "MaMa");

But when I display the result on the screen, I get this answer.

JaVa
MaMa
Mama

What did I miss?

Upvotes: 1

Views: 95

Answers (3)

Ryuzaki L
Ryuzaki L

Reputation: 40008

If you like to do this by using java-8 streams

  1. First stream the List into Map, with key as String and values is Long count of occurrence

 Map<String, Long> result =  duplicates.stream().map(String::toLowerCase)
          .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
  System.out.println(result);    //{ss=1, mm=1, java=2, mama=2}
  1. Then filter if occurrence is greater than 1 and collect it as String array, below code shows combining both

String[] array = duplicates.stream().map(String::toLowerCase)
          .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
          .entrySet().stream().filter(entry->entry.getValue()>1).map(Map.Entry::getKey).toArray(String[]::new);

   System.out.println(Arrays.toString(array));  //[java, mama]

Upvotes: 2

Joakim Danielson
Joakim Danielson

Reputation: 51892

A few things, the inner loop just needs to look forward so j can start at i+1 and because of this the outer loop is ending at i < duplicates.size() -1. Then you can't use I or j when assigning to mass, you need a separate counter for this

int k = 0;
for (int i = 0; i < duplicates.size() -1; i++){
    for (int j = i + 1; j < duplicates.size(); j++){
        if (duplicates.get(i).equalsIgnoreCase(duplicates.get(j))){
            mass[k] = duplicates.get(i);
            k++;
        }
    }
 }

Upvotes: 1

Slot Machine
Slot Machine

Reputation: 71

I don't want to give it away, since it looks like you are learning. Hint: you can (and perhaps should, for practice) accomplish this task with one loop. No need to use a nested loop. Keep in mind that you can shorten a loop by using duplicates.size()-1.

Upvotes: 1

Related Questions