Skip to main content

Java Programs Asked In An Interview | Java 8 | Core Java

 Q1)

// Write a Java Program To Find Out the Character Occurnaces In A String.

import java.util.HashMap;
import java.util.Map;

public class CharOccurnacesInString {

    // Write a Java Program To Find Out the Character Occurnaces In A String.

    public static void main(String[] args) {

        String str = "I am Sandeep Aswar";
        str = str.replaceAll(" ", "").toLowerCase();

        char[] ch = str.toCharArray();

        Map<Character, Integer> charMap = new HashMap<>();

        for (char c : ch) {

            if (charMap.containsKey(c)) {

                charMap.put(c, charMap.get(c) + 1);

            } else {
                charMap.put(c, 1);
            }

        }

        for (Map.Entry<Character, Integer> entry : charMap.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

    }

}
Output:
p -> 1 a -> 4 r -> 1 s -> 2 d -> 1 e -> 2 w -> 1 i -> 1 m -> 1 n -> 1

Q2)

// Write a java Program to concatenate Two Streams.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ConcatenateTwoStreams {

    // Write a java Program to concatenate Two Streams.

    public static void main(String[] args) {

        List<String> list1 = Arrays.asList("Java", "8");

        List<String> list2 = Arrays.asList("explained", "through", "programs");
         

        //Concatenated the list1 and list2 by concatenating into Stream

       Stream<String> concatStream =  Stream.concat(list1.stream(), list2.stream());

       // Printing the Concatenated Streams.

       concatStream.forEach( str -> System.out.print(str + " "));
   

    }

}

OutPut:
============
Java 8 explained through programs




Q3)

// Write a Java Program to Count Each Character In A String.

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountEachCharacterString {

    // Write a Java Program to Count Each Character In A String.

    public static void main(String[] args) {

        String str = "Welcome To Java Welcome To Programming";

        Map<Character, Long> charMapCount = str.chars().mapToObj(c -> (char) c)
                .filter(Character::isLetterOrDigit)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        charMapCount.forEach((character, count) -> {
            System.out.println("Character: " + character + ", count: " + count);
        });

    }

}

OutPut:
Character: a, count: 3 Character: c, count: 2 Character: e, count: 4 Character: g, count: 2 Character: i, count: 1 Character: J, count: 1 Character: l, count: 2 Character: m, count: 4 Character: n, count: 1 Character: o, count: 5 Character: P, count: 1 Character: r, count: 2 Character: T, count: 2 Character: v, count: 1 Character: W, count: 2


Q4)

// Write A Java Program To Count Each Word / Element From the String

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountEachWordFromString {

    // Write A Java Program To Count Each Word / Element From the String


    public static void main(String[] args) {


        List<String> names=Arrays.asList("AA","BB","AA","CC", "BB","BB");

       Map<String, Long> namesCount =names.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

       System.out.println(namesCount);

    }

}

Output:
=======
{CC=1, BB=3, AA=2}

Q5)

// Count the words inside the String Using Java 8 Program.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountStringWords {

    // Count the words inside the String Using Java 8 Program.

    public static void main(String[] args) {

        String str = " Welcome To Java Welcome To Programming"; // Given String is here
        String arr[] = str.split(" "); // We are using spilt method for conversion of String into arr

        List<String> words = Arrays.asList(arr); // String arr converted into list

        // Apply Stream() function on list for creation of Stream Of Strings.

        Map<String, Long> wordCouuMap = words.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        Set<Map.Entry<String, Long>> entrySet = wordCouuMap.entrySet();

        for (Map.Entry<String, Long> entry : entrySet) {
            String key = entry.getKey();
            Long value = entry.getValue();
            System.out.println("Word :" + key + " , Count :" + value);
        }

    }

}

OutPut:
========
Word : , Count :1 Word :Java , Count :1 Word :Programming , Count :1 Word :Welcome , Count :2 Word :To , Count :2


Q6)

// Write A Java 8 program to perform cube on list elements and filter numbers which
    // are greater than 50.

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

public class CubeOfElements {
   
    // Write A Java 8 program to perform cube on list elements and filter numbers which
    // are greater than 50.

    public static void main(String[] args) {
         
         List<Integer> list=List.of(1,2,3,4,5,6,7);
         
         list.stream().map( e -> e*e*e ).filter(element -> (element > 50)).collect(Collectors.toList()).forEach(System.out::println);

       


    }



}

OutPut:
=======

64
125
216
343


Q7)

// How will you get Current Time And Date Using Java 8 Date And Time API

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class CurrentDateAndTime {


    // How will you get Current Time And Date Using Java 8 Date And Time API

    public static void main(String[] args) {
       
       // Using LocalDate API to get the Date

       System.out.println("Current Local Date :" + LocalDate.now());

       // Using LocalTime API to get current Time

       System.out.println("Current Local Time :" + LocalTime.now());
       
       //Using LocalDateTime API to get the Local Date And Time

       System.out.println("Current Date and Time: " + LocalDateTime.now());

     



    }
   
}

OutPut:
=======

Current Local Date :2023-11-24 Current Local Time :08:35:57.012297800 Current Date and Time: 2023-11-24T08:35:57.013293400


Q8)

// Java 8 Program for Counting Duplicate Elements From the String.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DuplicateElementCount {

    // Java 8 Program for Counting Duplicate Elements From the String.

    public static void main(String[] args) {

        List<String> names = Arrays.asList("AA", "BB", "CC", "AA", "CC");

        Map<String, Long> namesCount = names.stream().filter(x -> Collections.frequency(names, x) > 1)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(namesCount);

    }

}

OutPut:
========
{CC=2, AA=2}


Q9)

// Consider the Array. If it contains the repeated elements then it returns true
    // And If it contains distinct elements then return false

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;

public class DuplicateElementFound {

    // Consider the Array. If it contains the repeated elements then it returns true
    // And If it contains distinct elements then return false

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of an Array :");
        int size = sc.nextInt();

        int arr[] = new int[size];

        System.out.println("Enter the element of An Array:");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.println("Entered Array:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + ",");
        }
        System.out.println();

        boolean flag=DuplicateElementFound.duplicateFound(arr);
        if(flag == true)
        {
            System.out.println("The Elements are Not Distince In Array");
        }
        else{
             System.out.println("Elements are Distinct");
        }
       
      sc.close();

    }

    public static boolean duplicateFound(int arr[])
    {
   
        List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

        Set<Integer> set = new HashSet<>(list);

        if(set.size() == list.size())
        {
            return false;            
        }
        return true;


    }


}

Output:
===========
1) Senario -1
Enter the size of an Array :
5
Enter the element of An Array:
10
20
30
40
50
Entered Array:
10,20,30,40,50,
Elements are Distinct
2) Senario-2
Enter the size of an Array :
6
Enter the element of An Array:
10
20
30
40
50
10
Entered Array:
10,20,30,40,50,10,
The Elements are Not Distince In Array

=========================================================================

Q10)

// Find Out the Duplicate Elements From A list

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateIntegers {
   
    // Find Out the Duplicate Elements From A list

    public static void main(String[] args) {
       
        List<Integer> list=Arrays.asList(10,15,24,7,24,74,10,7);

        Set<Integer> set = new HashSet<>();
        // Hashset Object does not allow duplicates and doesnot preserve insertion order.

        list.stream().filter(n -> !set.add(n)).forEach(System.out::println);



    }
}

OutPut:
==============
24 10 7










Comments

Popular posts from this blog

Java 8 Programs Asked In Interview For Experienced Professionals | Java 8 Coding Interview Questions Asked In The Interview.

 Q1) // Given Two Strings. Find Out the Two Strings are Anagrams or not.     // Anagram means a String which has same characters present with the another     // String,     // Only the sequence of the Characters are different. package J ava C oncept O f D ay ; import java . util . stream . Collectors ; import java . util . stream . Stream ; public class AnagramStrings {     // Given Two Strings. Find Out the Two Strings are Anagrams or not.     // Anagram means a String which has same characters present with the another     // String,     // Only the sequence of the Characters are different.     public static void main ( String [] args ) {         String str1 = "Listen" ;         String str2 = "Silent" ;         str1 = Stream . of ( str1 . split ( "" )). map ( String :: toLowerCase ). sorted (). collect ( Collectors . joining ());...

How many primitive data types are there in Java?

Java includes a set of fundamental data types known as primitive data types. These data types are the essential components for storing and managing various kinds of data, including numbers, characters, and boolean values. Java encompasses a total of eight primitive data types, and this article aims to provide an in-depth explanation of each type in a simplified manner. 1.      byte: The byte data type is designed for storing small integer values, with a range spanning from -128 to 127. 2.      short: Slightly more accommodating than byte , the short data type can be employed for storing relatively larger integer values, ranging from -32,768 to 32,767. 3.      int: Among the most commonly used primitive data types, int can hold larger integer values, with a range extending to approximately -2 billion to 2 billion. 4.      long: When dealing with very large integer values, the long data t...