Thursday, 23 May 2024

Top Java8 interview Questions and answers

 Questions:

1) Given a list of integers, separate odd and even numbers?

2) How do you remove duplicate elements from a list using Java 8 streams?

3) How do you find frequency of each character in a string using Java 8 streams?

4) How do you find frequency of each element in an array or a list?

5) How do you sort the given list of decimals in reverse order?

6) Given a list of strings, join the strings with ‘[‘ as prefix, ‘]’ as suffix and ‘,’ as delimiter?

7) From the given list of integers, print the numbers which are multiples of 5?

8) Given a list of integers, find maximum and minimum of those numbers?

9) How do you merge two unsorted arrays into single sorted array using Java 8 streams?

10) How do you merge two unsorted arrays into single sorted array without duplicates?

11) How do you get three maximum numbers and three minimum numbers from the given list of integers?

12) Java 8 program to check if two strings are anagrams or not?

13) Find sum of all digits of a number in Java 8?

14) Find second largest number in an integer array?

15) Given a list of strings, sort them according to increasing order of their length?

16) Given an integer array, find sum and average of all elements?

17) How do you find common elements between two arrays?

18) Reverse each word of a string using Java 8 streams?

19) How do you find sum of first 10 natural numbers?

20) Reverse an integer array

21) Print first 10 even numbers

Answers:

 public static void main(String[] args) {

OddEvenSeparate();

removeDuplicates();

freqOfCharInString();

freqOfCharInList();

decimalsInreverseOrder();

joinStrings();

multiplesOfFive();

findMinMaxInList();

sortedList();

distinctSortedList();

sortedArray();

threeMaxAndMinNumbersFromList();

anagram();

sumIndividualNumbersOfNumber();

secondLargestNumberInIntArray();

sortStringArrayBasedOnSize();

sumAndAverageOfAnArray();

commonElementBetTwoArrays();

reverseWordsInAGivenString();

sumOfNaturalNumbers(10);

reverseIntegerArray();

firstNevenNumbers(10);


}

        public static void OddEvenSeparate() {

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

/*list.stream().filter(i->i%2==0).forEach(System.out::print);

list.stream().filter(i->i%2!=0).forEach(System.out::print);*/

List<Integer> evenNumbers = list.stream().filter(i->i%2==0).collect(Collectors.toList());

System.out.println("evenNumbers are : "+evenNumbers);

List<Integer> oddNumbers = list.stream().filter(i->i%2!=0).collect(Collectors.toList());

System.out.println("oddNumbers are : "+oddNumbers);

}

public static void removeDuplicates() {

List<Integer> list = Arrays.asList(1,2,2,3,3,4,5,6,7,4,5,6,7,8,9,10);

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

System.out.println("distinctNumbers are : "+distinctNumbers);

}

public static void freqOfCharInString() {

String str = "BAGAVATHAM";

Map<Character, Long> charCountMap = str.chars().mapToObj(c ->(char)c)

.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    System.out.println(charCountMap);

}

public static void freqOfCharInList() {

List<Integer> list = Arrays.asList(1,2,2,3,3,4,5,6,7,4,5,6,7,8,9,10);

Map<Integer, Long> intCountMap = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    System.out.println(intCountMap);

}

public static void decimalsInreverseOrder() {

List<Double> decimalList = Arrays.asList(12.45, 23.58, 17.13, 42.89, 33.78, 71.85, 56.98, 21.12);

List<Double> decilist = decimalList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

System.out.println("list of decimal numbers in reverse order : "+decilist);

}

public static void joinStrings() {

List<String> listOfStrings = Arrays.asList("Facebook", "Twitter", "YouTube", "WhatsApp", "LinkedIn");

        String joinedString = listOfStrings.stream().collect(Collectors.joining(", " , "[", "]"));

        System.out.println(joinedString);

        

}

public static void multiplesOfFive() {

List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);

List<Integer> mFive = listOfIntegers.stream().filter(i -> i % 5 == 0).collect(Collectors.toList());

System.out.println("multiples of Five : "+mFive);

}

public static void findMinMaxInList() {

List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);

/*Integer maxNumber = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).max(Comparator.comparing(Integer::valueOf)).get();

Integer minNumber = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).min(Comparator.comparing(Integer::valueOf)).get();*/

Integer maxNumber =  listOfIntegers.stream().max(Comparator.comparing(Integer::valueOf)).get();

Integer minNumber =  listOfIntegers.stream().min(Comparator.comparing(Integer::valueOf)).get();

System.out.println("Max Number is : "+maxNumber + " & Min Number is : "+minNumber);

}


public static void sortedList() {

List<Integer> unsortList1 = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);

List<Integer> unsortList2 = Arrays.asList(5, 2, 1, 4, 7, 3, 8, 9);

List<Integer> sortedList1 = Stream.concat(unsortList1.stream(), unsortList2.stream()).sorted().collect(Collectors.toList());

System.out.println(sortedList1);

}

public static void distinctSortedList() {

List<Integer> unsortList1 = Arrays.asList(45, 45, 12, 12, 56, 15, 24, 75, 31, 89);

List<Integer> unsortList2 = Arrays.asList(5, 2, 2, 1, 4, 4, 7, 3, 8, 8, 9);

List<Integer> sortedList1 = Stream.concat(unsortList1.stream(), unsortList2.stream()).sorted().distinct().collect(Collectors.toList());

System.out.println(sortedList1);

}

public static void sortedArray() {

int[] unsortArray1 = {45, 45, 12, 12, 56, 15, 24, 75, 31, 89};

int[] unsortArray2 = {5, 2, 2, 1, 4, 4, 7, 3, 8, 8, 9};

int[] sortedArray = Stream.of(unsortArray1, unsortArray2).flatMapToInt(Arrays::stream).sorted().distinct().toArray();

for(int num:sortedArray)

{

System.out.print(num); System.out.print(",");

}

}

public static void threeMaxAndMinNumbersFromList() {

List<Integer> list = Arrays.asList(5, 2, 12, 1, 4, 14, 7, 3, 8, 18, 9);

List<Integer> listMin3 = list.stream().sorted().limit(3).collect(Collectors.toList());

List<Integer> listMax3 = list.stream().sorted(Collections.reverseOrder()).limit(3).collect(Collectors.toList());

System.out.println(listMin3);

System.out.println(listMax3);

}

public static void anagram() {

String str1 = "saras"; String str2 = "asrsa";

if(str1.length() == str2.length()) {

char[] ch1 = str1.toCharArray();

char[] ch2 = str2.toCharArray();

Arrays.sort(ch1);

    Arrays.sort(ch2);

    

    boolean result = Arrays.equals(ch1, ch2);

    

    if(result) System.out.println(str1 + " and " + str2 + " are anagram.");

    else System.out.println(str1 + " and " + str2 + " are not anagram.");

    

}

else {

System.out.println("two strings are not Anagram");

}

}

private static void sumIndividualNumbersOfNumber() {

int i = 234523287;

int sum = String.valueOf(i).chars().map(Character::getNumericValue).sum();

System.out.println("The sum of the digits is: " + sum);

}

private static void secondLargestNumberInIntArray() {

Integer[] i = {1,2,3,4,5,6,7,8,9};

Integer sln = Arrays.asList(i).stream().sorted(Comparator.reverseOrder()).skip(1).findFirst().get();

System.out.println("second largest number in the given array is : "+sln);

}

private static void sortStringArrayBasedOnSize() {

String[] arr = {"praveen","sathish","chaki","minnu","junnu","sahasra"};

// Sorting the ArrayList based on string length using Collections.sort()

        Collections.sort(Arrays.asList(arr), Comparator.comparingInt(String::length));

        System.out.println(Arrays.asList(arr));

      

     }

private static void sumAndAverageOfAnArray() {

int[] arr = {1,2,4,5,7,8,90,34,6,7,8,84,56,67,78};

int sum = IntStream.of(arr).sum();

int avg = sum/arr.length;

        System.out.println("sum is :"+sum+" average is : "+avg);

      

     }

private static void commonElementBetTwoArrays() {

Integer[] arr1 = {1,2,4,5,7,8,90,34,6,7,8,84,56,67,78};

Integer[] arr2 = {3,2,9,5,0,8,34,16,17,18,84,46,57,78};

// create hashsets

        Set<Integer> set1 = new HashSet<>();

        Set<Integer> set2 = new HashSet<>();

        

// Adding elements from array1

        for (int i : arr1) { set1.add(i); }

 

        // Adding elements from array2

        for (int i : arr2) { set2.add(i); }

 

        // use retainAll() method to

        // find common elements

        set1.retainAll(set2);

        System.out.println("Common elements : " + set1);

      

     }

private static void reverseWordsInAGivenString() {

String input = "I work at cognizant";

// Splitting the input string into words and processing each word with a stream

        String result = Arrays.stream(input.split(" "))

                              .map(word -> new StringBuilder(word).reverse().toString()) // Reversing each word

                              .collect(Collectors.joining(" ")); // Joining the reversed words back into a string


        // Displaying the result

        System.out.println("Original string: " + input);

        System.out.println("Reversed words: " + result);

}

private static void sumOfNaturalNumbers(int n) {

System.out.println("Sum of N Natural Numbers is : "+n*(n+1)/2);

}

private static void reverseIntegerArray() {

Integer[] intArray = {1,2,3,4,5,6,7,8,9};

List<Integer> list = Arrays.asList(intArray);

Collections.reverse(list);

System.out.println(list);

}

private static void firstNevenNumbers(int n) {

for(int i=1;i<=n;i++) {

if(i%2==0) { 

System.out.print(i); 

if(i<n){ 

System.out.print(",");

}

}

}

}

Wednesday, 15 July 2020

How to sort a list of objects based on a particular field of the objects in java?



List<Object> list = new Arraylist<Object>(); 
Sorting a List in Ascending order using Comparator:
Collections.sort(list, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getVariable().compareTo(o2.getVariable());
    }
});

Friday, 23 August 2019

Coins to form a sequence of alternating heads and tails - codility test using java



package com.codility.interview;

public class AlternateCoinSequence {

public static int flip(int ch) {
return (ch == 0) ? 1 : 0;
}

public static int getFlipWithStartingCharcter(int[] coinSeq, int expected) {
int flipCount = 0;
for (int i = 0; i < coinSeq.length; i++) {

if (coinSeq[i] != expected)
flipCount++;

expected = flip(expected);
}
return flipCount;
}

public static int minFlipToMakeStringAlternate(int[] coinSeq) {
return Math.min(getFlipWithStartingCharcter(coinSeq, 0), getFlipWithStartingCharcter(coinSeq, 1));
}

public static void main(String[] args) {
AlternateCoinSequence c = new AlternateCoinSequence();

int[] coinSeq = { 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1 };
  //int[] coinSeq = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }; --7 min flips
  //int[] coinSeq = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }; --9 max flips


System.out.println("Number of min flips required to make coin seq are "+minFlipToMakeStringAlternate(coinSeq));

}

}

Tuesday, 26 March 2019

Registrations and Payment (200 Marks) - Code Challenge on Core Java

Use Case:

 Registrations and Payment (200 Marks)
PKR Pvt Limited is in the business of conducting Java Certification exams. Students interested in appearing for Certification examination are required to fill on-line application form on PKR's website. At the end of successful fill of the application form, each student is assigned a "Roll Number". This registration data is provided which consist of the details of the student - Roll No., Registration Date, Registration Time, Name, Gender.

Student needs to make the payment of examination fees of Rs. 1000 through credit card using "Bill Desk". For making the payment, student needs to provide their "Roll Number".

At the end of registration process, "Bill Desk" sends data of all those students who have made the payment. This data of the students who have made the payment is provided.

PKR Pvt limited has a problem - There is a need to find out those students who have registered on PKR's website (and hence, received the "Roll Number") but have not made the payment.

PKR Pvt Limited has hired you as "Technical Specialist". You are requested to develop an efficient computer program in 'Java' programming language to compare both input data (Registration Data and Bill Desk Data) and generate a report on list of those students who have not made the payment.

Core Java Code:

import java.io.*;
import java.util.*;
public class CandidateCode {
    static String rollno;
    static String registrationdate;
    static String registrationtime;
    static String name;
    static String gender;
    static int L=10;
    private String generateRollNumber() {
        Long n = Math.round(Math.random() * 100000000);
        String rollnumber = Long.toString(n);
        return rollnumber;
    }
   
    static String paymentRollNo[] = new String[L];
    private void paymentMethod(String x) {
        int z = 0;
        paymentRollNo[z]=x;
        System.out.println("Payment of 500 is done successfully for RollNo: "+x);
        z++;
    }
   
/*    private void billDeskData() {
        System.out.println();
    }*/
    public static void main(String args[]) throws Exception {
        CandidateCode cc = new CandidateCode();
        Scanner scanner = new Scanner(System.in);
        int N;
        String M;
        System.out.println("how many students registered are N: ");
        N = scanner.nextInt();
        String registrationDate[] = new String[N];
        String registrationTime[] = new String[N];
        String studentName[] = new String[N];
        String studentGender[] = new String[N];
        String studentRollNo[] = new String[N];
       
        for (int i = 0; i < N; i++) {
            System.out.println("Please Register with following details ");
            System.out.println("Enter your Registration Date ");
            registrationdate = scanner.next();
            registrationDate[i] = registrationdate;
            System.out.println("Enter your Registration Time ");
            registrationtime = scanner.next();
            registrationTime[i] = registrationtime;
            System.out.println("Enter your Name ");
            name = scanner.next();
            studentName[i] = name;
            System.out.println("Enter your Gender ");
            gender = scanner.next();
            studentGender[i] = gender;
            if (registrationDate[i] != null & registrationTime[i] != null & studentName[i] != null
                    & studentGender[i] != null) {
                rollno = cc.generateRollNumber();
                System.out.println("rollno: "+rollno);
                studentRollNo[i] = rollno;
            } else {
                System.out.println("Please Re-Check all details and fill the details Properly");
            }
           
           
            System.out.println(
                    "Payment of Examination Fees 500 Rupees: If you want to continue with Payment now please enter your RollNumber or please enter N to exit");
            M = scanner.next();
            if(M.equals("N"))
            {
                System.out.println("Thanks for registering with us");
            }
            else
            {
                cc.paymentMethod(M);
            }
        }
        for (int j = 0; j < N; j++) {
            //System.out.println("Registration_Data :");
            //System.out.println(N);
            System.out.println(studentRollNo[j] + ", " + registrationDate[j] + ", " + registrationTime[j] + ", "
                    + studentName[j] + ", " + studentGender[j]);
        }
       
        System.out.println("Students details who had made Payment are: ");
        for (int k = 0; k < N; k++) {
            if(paymentRollNo[k] !=null) {
            System.out.println(paymentRollNo[k] + ", "+ studentName[k]);
        }
        }
            System.out.println("Students details who haven't made Payment are: ");
            for (int k1 = 0; k1 < N; k1++) {
                if(paymentRollNo[k1] ==null) {
                System.out.println(studentRollNo[k1] + ","+ studentName[k1]);
            }
        scanner.close();
    }
 }
}

 


Monday, 10 September 2018

How to display duplicate characters in given a string using java

package com.java.collections;

import java.util.HashMap;
import java.util.Iterator;

public class DuplicateCharacters {
   
    static void findDuplicateCharacters(String str) {
       
        HashMap<Character, Integer> hm = new HashMap<>();
       
        for(int i=0; i<str.length();i++)
        {
            char c = str.charAt(i);
           
            if(hm.get(c)!=null)
            {
                hm.put(c, hm.get(c)+1);
            }
            else
            {
                hm.put(c, 1);
            }
                       
        }
           //System.out.println(hm);
        Iterator<Character> c = hm.keySet().iterator();
        while(c.hasNext())
        {
            char temp = c.next();
            if(hm.get(temp)>1)
            {
                System.out.println("the Character " + temp + " appeared " + hm.get(temp) + " times");
            }
        }
    }

    public static void main(String[] args) {
       
        findDuplicateCharacters("i i am am java java and and");

    }

}

How to find duplicate words in a given sentence or in a string using java

package com.java.collections;

import java.util.HashMap;
import java.util.Iterator;

public class DuplicateString {
   
    static void findDuplicateWord(String str) {
       
        HashMap<String, Integer> hm = new HashMap<>();
       
        String[] s = str.split(" ");
       
        for(String tempString : s)
        {
            if(hm.get(tempString)!=null)
            {
                hm.put(tempString, hm.get(tempString)+1);
            }
            else
            {
                hm.put(tempString, 1);
            }
           
        }
         //   System.out.println(hm);
        Iterator<String> tempString = hm.keySet().iterator();
        while(tempString.hasNext())
        {
            String temp = tempString.next();
            if(hm.get(temp)>1)
            {
                System.out.println("the word " + temp + " appeared " + hm.get(temp) + " times");
            }
        }
    }

    public static void main(String[] args) {
       
        findDuplicateWord("i i am am java java and and");

    }

}

Sunday, 9 September 2018

Spring Basics Part-1

Basics of Spring:
1.What is Spring?
A.Spring   is a light weight framework. It is one of the most popular open source framework
    for developing enterprise applications.

2.What is Spring Framework?
A.The Spring Framework is an application framework and inversion of control container for the
    Java Platform.
    The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
    WEB MVC etc.


3.What are main Advantages of Spring Framework?
A.
  1. Spring is a light weight framework and It minimally invasive development with POJO.
  2. Spring achieves the loose coupling through dependency injection and interface based programming.
  3. Spring supports declarative programming through aspects and common conventions.
  4. Boiler Plate Redution through aspects and templates.