Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Thursday, July 11, 2019

Find Duplicate Values in a List Using Java

In this article, we will see how to find the duplicate values from an array or list using java.  This is one of important programming questions in technical interview. Each interviewer has different approach to access the candidate. But, the logic and the approach by candidate is really matter. In this program we have used Map and List both, so its a kind of collections interview questions. You can find few more collection interview question.  Today we will see how to find the duplicate values from array. 


The logic is very simple here, see the below.

  • At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
  • Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
  • Finally we will have the map , which holds the array elements with the counter for repentance. 
  • Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).


DuplicateFinder.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DuplicateFinder {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>(
                Arrays.asList(4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90));

        System.out.println("Input List Data = " + list);

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

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

            if (map.isEmpty()) {
                map.put(list.get(i), 1);
            } else if (map.containsKey(list.get(i))) {
                map.put(list.get(i), map.get(list.get(i)) + 1);
            } else {
                map.put(list.get(i), 1);
            }
        }

        System.out.println("\nDuplicate values are: ");

        // Iterate the Map and display the duplicate values.
        for (Entry<Integer, Integer> entry : map.entrySet()) {

            if (entry.getValue() > 1) {
                System.out.println(entry.getKey());

                // TODO: We can now put these values into any list.
            }
        }
    }
}

Output:

Input List Data = [4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90]

Duplicate values are:
4
5
25

Note- One small point: because HashMap does not guarantee iteration order, the order of 4, 5, and 25 in the output can vary.



Happy Learning.

Wednesday, July 10, 2019

Find One Missing Number from a List Using Java


In this article, we will see how to find the missing number from a list using java.  This is one of important common interview question asked in interview. You can see, how to find all missing numbers from a list. In this program we will use core java or the traditional way using for loop for finding the miss number from a list. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find one missing number using traditional core java style. 


The logic is very simple here, see the below.

  • At first we need to find the MAX number from the list. We need this MAX number because , we need to calculate the SUM of all natural number up to that max number. 
  • Then , we need to calculate the sum of all those natural number.
  • Then we will subtract each element from the given list from sumOfNaturalNumbers.
  • Now, the at the last  the value inside sumOfNaturalNumbers is the missing number.

FindOneMissingNumber.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;

public class FindOneMissingNumber {

    public static void main(String[] args) {
        ArrayList<Integer> numberList = new ArrayList<>(
                Arrays.asList(10, 3, 2, 4, 5, 6, 7, 9, 8, 14, 1, 11, 13));

        int sumOfNaturalNumbers = getSumUptoMax(findMax(numberList));

        for (int i = 0; i < numberList.size(); i++) {
            /*
             * Subtract each element from the list from sumOfNaturalNumbers.
             * The final value will be the missing number.
             */
            sumOfNaturalNumbers = sumOfNaturalNumbers - numberList.get(i);
        }

        int missingNumber = sumOfNaturalNumbers;
        System.out.println("Missing Number is :: " + missingNumber);
    }

    // Find the sum of all natural numbers up to limitNumber.
    private static int getSumUptoMax(int limitNumber) {
        int sum = 0;

        for (int i = 1; i <= limitNumber; i++) {
            sum = sum + i;
        }

        return sum;
    }

    // Find the greatest value from the list.
    private static int findMax(ArrayList<Integer> numberList) {
        int largest = numberList.get(0);

        for (int i = 1; i < numberList.size(); i++) {
            if (numberList.get(i) > largest) {
                largest = numberList.get(i);
            }
        }

        return largest;
    }
}

Output:

Missing Number is :: 12

 

This approach assumes the list contains the numbers from 1 through the maximum value, with exactly one number missing.


Happy Learning.

Find a Missing Number from a List Using Java 8 Streams

In this article, we will find the missing number from a list of numbers using java 8.  This is one of important questions asked in interview. This program is to find the only one missing number. Check how to find all missing numbers from a list. In this program we will use only java 8 stream to find the missing number. Earlier post we had seen how to use stream to sort the employee. Check more how find one missing number using traditional core java style


FindMissingNumber.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;

public class FindMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 3, 2, 4, 5, 6, 7, 9, 10));
// Get the Max value from the List.
int maxValue = numberList.stream().max(Comparator.naturalOrder()).get().intValue();
// Get sum of all natural numbers - upto the above maxvalue
int sumOfAllNumber = IntStream.range(1, maxValue + 1).sum();
// Get the sum of all number inside List.
int sumofList = numberList.stream().mapToInt(Integer::intValue).sum();
// Now print the missing number.
System.out.println("The Missing Number is:: " + (sumOfAllNumber - sumofList));
}
}

Output - 

The Missing Number is:: 8

Saturday, October 27, 2018

Filter Strings Using Stream API in Java


In this article we will learn how to use Java 8 Stream Filter with Example,  I have used String list to filter the names. Stream, A sequence of elements supporting sequential and parallel aggregate operations. Below example will show you how to filter the list with predicate.

StringFilterUsingStream.java

package com.techbyteslearn.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StringFilterUsingStream {

    public static void main(String[] str) {

        List<String> nameList = new ArrayList<String>();

        nameList.add("Roshna");
        nameList.add("Amit Kumar");
        nameList.add("Manoj");
        nameList.add("Neha");
        nameList.add("Rina");
        nameList.add("Ashna");
        nameList.add("Peter");
        nameList.add("Deb Kumar");

        System.out.println("All Names ::");
        nameList.stream().forEach(name -> System.out.println(name));

        // Filter all names ending with "Kumar"
        List<String> filteredList = nameList.stream()
                .filter(name -> name.endsWith("Kumar"))
                .collect(Collectors.toList());

        System.out.println("\nFiltered Names ::");
        filteredList.stream().forEach(name -> System.out.println(name));
    }
}

Output:

All Names :: Roshna Amit Kumar Manoj Neha Rina Ashna Peter Deb Kumar Filtered Names :: Amit Kumar Deb Kumar

I changed the comment from “ends with” to “ending with” and formatted the stream expression for readability. The program logic remains the same.


Hope this will help you. Happy Learning.