jc claracay
jc claracay

Reputation: 1

How to print duplicated items in an array?

I've got the solution for my question but feel free to add more or shorten the code I made !

Here is the code I already developped:

public static void main(String[] args) {     

            Scanner sc = new Scanner(System.in);
            System.out.print("Input Array Length:"); // limit of array

            int n=sc.nextInt();
            System.out.println();


            String  arr[]=new String [n];

            for (int i = 0; i < arr.length; i++) {

                System.out.println("Enter elements:"); // elements of array
                arr[i] = sc.next();
            }



            for (int i = 0; i < arr.length -1; i++) { // start loop

                for (int j = i+1; j < arr.length; j++) 
                {
                    if( (arr[i].equals(arr[j]))) // condition to find duplicate
                    {
                        System.out.println("Duplicate Element is : "+arr[j]);
                    }
                }
            }
        }

Upvotes: 0

Views: 91

Answers (2)

miiiii
miiiii

Reputation: 1620

Well, if you are looking for more readable and elegant code, this snippet might help..

String[] myStringArray = { "A", "B", "C", "D", "E" , "A", "B", "A", "AC"};
    List<String> allStr = Arrays.asList( myStringArray );
    Set<String> duplicateStrings = allStr.stream()
            .filter(i -> Collections.frequency(allStr, i) >1)
            .collect(Collectors.toSet());
    System.out.println(duplicateStrings);

Explanations [Needed As always :-) ]:

  • Created a stream from your String Array for processing
  • Filtering the Strings which are duplicated so that we can print later
  • Used Collections.frequency() to get the count of occurrence of the same object
  • If it is greater than one, it is a duplicate, we'll keep it so that can be printed (or used)
  • Finally, collecting all the outputs of Filter operation to Set
  • As set doesn't allow duplicates, it will hold single value of the duplicated words (String objects)

Hope it helps.

What may I look next?

Java Stream API for further reading.

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

One of possible solution, is to create a Map, where key is an unique items from the array, and value - items' count:

Set<String> duplicates = Arrays.stream(arr)
                               .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
                               .filter(entry -> entry.getValue() > 1)
                               .map(Map.Entry::getKey)
                               .collect(Collectors.toSet());

Upvotes: 1

Related Questions