Search This Blog

Breaking

Tuesday, 28 July 2020

Find duplicates values from a integer list with/Without Java8 features


This is a very common question for Automation interviews. In my 8+ years of experience in Software Testing, In many interviews, people asked me this question when they were checking Java skills. The reason behind the popularity of this question is because it can be done in multiple ways with different concepts. And with each concept, the interviewer checks the knowledge of Java language understanding. 


Let me write down some of the ways, we can solve this problem:


1. By looping (How good we are with loops)

3. By Java 8 stream API (New concept)

3. BySet collection (Easiest One which We practically use :) )


So, you can see now, why this question is important. If you can solve it by any of the above-listed ways, it shows that you have a fair understanding of programming.


So let' first solve it by the naive approach (Looping):


// input list with duplicates

List<Integer> list = new ArrayList<>(

        Arrays.asList(1, 5, 10, 5, 4, 1, 5, 2, 4, 5, 2, 3, 10, 3, 3, 4, 5, 4, 5));

// Print the Arraylist

System.out.println("ArrayList with duplicates: "

        + list);


//  Method 1

     for (int i = 0; i <= list.size(); i++) {

            for (int j = i + 1; j < list.size(); j++) {


                if (list.get(i).equals(list.get(j))) {

                    list.remove(j);

                    j--;

                }


            }

        }


System.out.println("After Removing duplicate elements:" + list); //[1, 5, 10, 4, 2, 3]


// Method 2

List<Integer> list2 = list.stream().distinct().collect(Collectors.toList());

System.out.println("After Removing duplicate elements:" + list2);//[1, 5, 10, 4, 2, 3]


// Method 3

HashSet<Integer> list3 = new HashSet<Integer>(list);

System.out.println("After Removing duplicate elements:" + list3);//[1, 5, 10, 4, 2, 3]

#AutomationInterviewQuestions 

No comments:

Post a Comment