Java 8 Important Interview Questions asked in MNCs

Support this post with a reaction:

Are you preparing for a Java developer role interview and want to master Java 8 interview questions that are actually asked in top MNCs like TCS, Wipro, Cognizant, Accenture, Capgemini, IBM, Infosys and other top mncs now a day? If yes, you’re in the right place. This blog is the goldmine you’ve been searching for.

This ultimate list of Java 8 interview questions and answers is prepared by Prakash Kumar, a highly experienced Java Developer with 7+ years in the industry and worked on large scale enterprise application like e commerce, healthcare, retail domain. After attending 100+ interviews across top-tier companies, he handpicked the most commonly asked and conceptually important questions that interviewers expect you to know — but rarely tell you beforehand.

From Lambda Expressions and Stream API to Functional Interfaces, Default Methods, and Method References, this guide will take you deep into the core of Java 8 features.

🚀 Pro Tip: Don’t stop at Java 8! Interviewers expect strong fundamentals too. Make sure to also check out:
👉 Top Core Java Interview Questions and Answers
👉 Advanced Java Interview Questions for Experienced Developers

⚠️ Warning: Once you start reading, you won’t stop until you’ve reached the end — that’s how valuable and insightful this content is.

So, whether you’re a fresher, mid-level, or experienced developer aiming for MNCs or product-based companies, bookmark this post right now — because you’ll want to revisit it again and again before every interview.
Let’s dive in and explore the real Java 8 questions that companies are asking today.

Java 8 Interview Questions(Most Important)

1. Tell us some newly added features in Java 8.

Some newly added Features of Java 8 are Lambda Expression, Functional Interface, Stream API, Default Method, Method References, Date Time API, Optional Class, Nashorm, and JavaScript Engine.

Short Explanations

Lambda Expression: lambda expression is a block of code that takes parameters and returns a value. We can refer to Lambda Expression as an object.

Functional Interfaces: It is an interface that contains only one abstract method.

Method References: Method References allow us to call the Class method by its name. “::” denotes method reference.

Default method: It is a method in the interface that implementation is not required in the class implementing that interface.

Stream API: Stream API is a sequence of objects used to process Collections.

Date Time API: It is introduced to overcome old Date drawbacks like new Date Time API is thread safe.

Optional: It is a Wrapper class to check the null value.

Nashorn, JavaScript Engine: Nashorn is an improved Javascript engine to replace the existing Rhino.

2. What is Default Method in Java 8?

The default method is a method inside the interface with the keyword default. It is a type of non-abstract method.

As we know an interface can have only abstract methods without a body. And we need a separate class for the implementation of interface methods. If we add a new method then we have to add the implementation of the newly added method in the class implementing the same interface.
To overcome this issue, Java 8 has introduced the concept of default methods. In interface, a default method can have its body so we don’t need to add its implementation in the class implementing the same interface.

Default Method Example:

interface DefaultInterface
{
    // abstract method of interface
    public void cube(int a);
  
    // default method of interface
    default void display()
    {
      System.out.println("This is default method");
    }
}
  
class Main implements DefaultInterface
{
    // need to add the implementation of 
    //cube abstract method
    public void cube(int a)
    {
        System.out.println(a*a*a);
    }
    public static void main(String args[])
    {
        Main obj = new Main();
        obj.cube(5);
        // default method executed 
        //no need to add implementation
        obj.display();
    }
}

Output

125
This is default method

3. Can We Override Default Method in Java?

Yes, we can override the default method in Java.

4. What is Static Interface Methods in Java 8 ?

A static method in an interface is a method that belongs to the interface itself, not to the objects (classes) that implement it. This means you cannot override it in the implementing classes.

Key Points:

  • It promotes better code organization and avoids the need for separate utility classes.
  • You call static methods in interfaces using the interface name, not the implementing class.
  • It helps in defining utility or helper methods related to the interface.

Static Method Example:

interface StaticInterface {
    // static method in interface
    static void staticMethod()
    {
        System.out.println("This is static Method can call by Interface");
    }
}
// Implementation Class
public class Main implements StaticInterface {
    public static void main(String[] args)
    {
        // Calling the static 
        //direcly using interface name
        StaticInterface.staticMethod();
    }
}

Output

This is static Method can call by Interface

5. What is the Lambda Expression in Java 8.

Lambda expression is a function without a name. It is also known as an anonymous function as it does not have type information by itself. We can also say it is a short and concise way to represent a method without a name.

Lambda expressions are mainly used to implement the single abstract method of a functional interface, making your code cleaner, more readable, and more functional in style.

Key Characteristics of Lambda expression:

  • Commonly used for collection operations like filter, map, forEach, etc.
  • No method name: It’s an anonymous function.
  • No need for full method declaration: No modifiers, return type, or class.
  • Executed on demand.
  • Mostly used with functional interfaces.

Basic Structure/Syntax of a Lambda Expression

FunctionalInterface fi = (String name) -> { 
   System.out.println(name); 
   return name; 
}

Lambda expression is divided into three parts

1. List of Arguments/Params:

(String name) 

Params or Parameters are passed in () round brackets. Lambda expression can have zero, one, two, or more params. Declaring the type of parameter is optional. It can be inferred from the context. 

2. Arrow Token:

-> 

Arrow token is a lambda arrow operator which separates the parameters from the body. It points the list of arguments to the body. 

3. Expression/Body:

{ 
  System.out.println("Hello "+name); 
  return "Hello "+name; 
}

The body contains the expressions or statements. If we have more than one line then we will use {} curly braces. the return type of the anonymous function is the same as that of the body expression. 

Features of a lambda expression

  • Lambda expressions can be passed as a parameter to another method. 
  • Lambda expressions can be standalone without belonging to any class.

Arraylist Iteration Using Lambda Expression

import java.util.*;
class Main{
    public static void main(String args[]){
        List<String> arr = Arrays.asList("quescol","interview");
        arr.forEach(s->System.out.println(s));
    }
}

Output

quescol
interview

6. What is String::valueOf Expression means?

String::valueOf is a example method reference introduced in Java 8. Here, String is class and valueOf is a static method of String class.

This expression is mostly used in functional programming, especially with functional interfaces like Function<T, R>, where you need to pass a method as a parameter.

What String::valueOf Does:

  • Converts a given value (like int, float, char, object, etc.) into its String representation.
  • It is a reference to the method String.valueOf() which takes one argument and returns a string.
  • Used to replace lambda expressions with cleaner syntax when the method already exists

Example Using Lambda:

Function<Integer, String> func = (value) -> String.valueOf(value);
System.out.println(func.apply(100));  // Output: "100"

Same Example Using Method Reference

Function<Integer, String> func = String::valueOf;
System.out.println(func.apply(100));  // Output: "100"

Both examples do the same thing, but String::valueOf is cleaner and more readable.

7. What is Optional in Java 8? What is it best used for?

In Java 8, Optional is a newly introduced class in java.util package to eliminate too many null checks. It is used to handle the presence or absence of a value in a safer and more readable way and helps to avoid NullPointerException. Optional comes with some built-in functions like isPresent(), ofNullable(), empty(), of() etc. 

Optional Example Java 8

import java.util.Optional;
public class Main {
	public static void main(String[] args)
	{
		String[] words = new String[10];
		words[5] = "quescol";
		if (Optional.ofNullable(words[5]).isPresent()) {
			String word = words[5].toLowerCase();
			System.out.print(word);
		}
		else
			System.out.println("Word is null");
	}
}

Output

quescol

8. What is the list of Optional methods

MethodDescription
Optional.empty()Creates an empty Optional (no value)
Optional.of(value)Wraps a non-null value (throws exception if null)
Optional.ofNullable(value)Wraps a value that might be null
isPresent()Returns true if a value is present
get()Returns the value (throws exception if empty)
orElse(default)Returns value if present, otherwise returns default
ifPresent(Consumer)Executes code only if value is present

9. What is Stream in Java 8?

Stream API is introduced newly in Java 8 to process the Collection object. Stream is not a data structure or it does not store any data, It just provides a convenient way to operate with data source and make its processing faster or we can say, it acts as a pipeline through which data flows and gets processed.

Key Points of Stream:

  • Streams don’t change the original data; they only process and return results.
  • You can perform operations like filtering, mapping, sorting, counting, reducing, etc.
  • Supports lazy evaluation — operations are performed only when needed.
  • Can be sequential or parallel for better performance on large datasets.

There are two methods to generate a Stream

1). stream() − Returns a sequential stream considering collection as its source.

2). parallelStream() − Returns a parallel Stream considering collection as its source.

There are two types of operation performed on Stream

1). Intermediate operation : it contains methods like map(), filter() and Sorted().

2). Terminal Operation : It contains methods like contains(), forEach() and reduce().

Example of Stream API

import java.util.*;  
import java.util.stream.Collectors;  
class Student{  
    int id;  
    String name;  
    int roll;  
    public Student(int id, String name, int roll) {  
        this.id = id;  
        this.name = name;  
        this.roll = roll;  
    }  
}  
public class Main {  
    public static void main(String[] args) {  
        List<Student> studentsList = new ArrayList<Student>();  
        studentsList.add(new Student(1,"Mayank",2));  
        studentsList.add(new Student(2,"Nishant",1));  
        studentsList.add(new Student(3,"Subhesh",3));  
        List<Integer> studentsListOutput =studentsList.stream()  
                                     .filter(s -> s.roll >= 2) 
                                     .map(s->s.roll)          
                                     .collect(Collectors.toList());  
        System.out.println(studentsListOutput);  
    }  
} 

 Output

[2, 3]

10. What Data Source a Stream can process?

A Stream can process the following data:

  • A Collection
  • An Array
  • An I/O channel

11. Tell me Some Intermediate Operations of Stream API?

Intermediate operations return a new stream and are lazy. they don’t do anything until a terminal operation (like forEach() or collect()) is called.

1. filter(Predicate<T>)

Filters the elements of the stream based on the given condition. It allows only those elements that satisfy the given predicate. Used when you want to include only specific elements.

List<Integer> result = list.stream()
    .filter(n -> n > 10)
    .collect(Collectors.toList());

2. map(Function<T, R>)

It transforms each element of the stream. It produces a new stream of transformed values. It is used for for data transformation, like converting string to uppercase, object to another type, etc.

Example

List<String> upper = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

3. flatMap(Function<T, Stream<R>>)

flatMap() is used to flatten nested data structures, like a List of Lists, into a single stream. It does this by converting each nested element into a stream and then merging all those streams into one.

List<List<String>> listOfLists = Arrays.asList(
    Arrays.asList("A", "B"),
    Arrays.asList("C", "D")
);

List<String> flatList = listOfLists.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());

Output: [A, B, C, D]

4. distinct()

It removes duplicate elements from the stream and keeps only unique ones, based on equals() and hashCode().

List<Integer> unique = List.of(1, 2, 2, 3).stream()
    .distinct()
    .collect(Collectors.toList());

Output: [1, 2, 3]

5. sorted()

Sorts elements in their natural order (for example, numeric or lexicographic order like A-Z or 1-10). It is used when sorting is required in the default order (Comparable implemented).

List<String> sorted = names.stream()
    .sorted()
    .collect(Collectors.toList());

6. sorted(Comparator<T>)

Sorts elements using a custom comparator provided as an argument. You can use it when you need a custom sorting logic.

List<Integer> sortedDesc = numbers.stream()
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());

7. peek(Consumer<T>)

Performs an action on each element of the stream without changing the stream itself. Mainly used for debugging. It is used to log or inspect elements during intermediate stages.

stream.peek(System.out::println)
     .filter(x -> x > 10)
     .collect(Collectors.toList());

8. limit(long maxSize)

Keeps only the first n(maxSize) elements from the stream. It is used for pagination, sampling, or limiting processing.

List<Integer> limited = numbers.stream()
    .limit(5)
    .collect(Collectors.toList());

9. skip(long n)

Skips the first n elements of the stream and keep the rest. It is useful in pagination when combined with limit().

List<Integer> afterSkip = numbers.stream()
    .skip(3)
    .collect(Collectors.toList());

10. mapToInt, mapToLong, mapToDouble

Specialized versions of map() that convert objects to primitive streams (IntStream, LongStream, or DoubleStream). It is used for numeric operations, counting, or performance benefits of primitive streams.

IntStream lengths = names.stream()
    .mapToInt(String::length);

12. What new feature added in new Date and Time API in Java 8?

In Java 8, a completely new Date and Time API was introduced in the package java.time to overcome the problems of the old java.util.Date and java.util.Calendar classes.

🚀 Key Features of the New Date and Time API:

1. Immutability

  • All classes like LocalDate, LocalTime, LocalDateTime, etc., are immutable and thread-safe.

2. Better Design (Inspired by Joda-Time)

  • Easy to use, more readable, and follows clear naming conventions.

3. New Core Classes

  • LocalDate – for date (e.g., 2025-06-18)
  • LocalTime – for time (e.g., 12:30:45)
  • LocalDateTime – for both date and time
  • ZonedDateTime – with time zone support
  • Period and Duration – for date/time calculations

4. Time Zone Handling

  • Improved support using ZoneId and ZonedDateTime.

5. Parsing and Formatting

  • Built-in formatter using DateTimeFormatter.

6. No More Null Confusion

  • Use of Optional with Date/Time helps avoid NullPointerException.

13. What is LocalDate in Java 8?

In Java 8, LocalDate is a immutable and thread-safe class from the java.time package that represents a date without time or timezone. For example, 2025-06-18. immutable means once it’s created, it cannot be changed.

Some important function of LocalDate are getDayOfMonth(), getDayOfWeek(), getMonth(), getYear() etc.

📌 Key Points of LocalDate:

  • Represents only date (no time, no timezone).
  • Default format: YYYY-MM-DD (e.g., 2025-06-18).
  • Commonly used for birthdays, due dates, or any date-based logic.

Example of LocalDate Program 

import java.time.LocalDate;    
public class Main {    
  public static void main(String[] args) {    
    LocalDate date = LocalDate.now();    
    System.out.println("Date: "+date);  
    System.out.println("Days Of Month: "+date.getDayOfMonth());
    System.out.println("Day Of Week: "+date.getDayOfWeek());
    System.out.println("Month Name: "+date.getMonth());
    System.out.println("Year: "+date.getYear());
  }    
} 

Output

Date: 2023-07-06
Days Of Month: 6
Day Of Week: THURSDAY
Month Name: JULY
Year: 2023

14. What is LocalTime in Java 8?

In Java 8, LocalTime is an immutable date-time object that is used to represent only the time without any date or time zone. It is an immutable and thread-safe object.. The default format of LocalTime is an hour-minute-second.
Some important function of LocalTime are plusHours(), minusHours(), plusMinutes(), minusMinutes() etc. 

Key Points of LocalTime:

  • Represents time only (e.g., 14:30:25).
  • Default format is HH:mm:ss (hours, minutes, seconds).
  • Does not store date or time zone info.
  • Useful when you only care about time-related operations (like setting reminders or comparing times).

Example of LocalTime Program

import java.time.LocalTime;    
public class Main {    
  public static void main(String[] args) {    
    LocalTime time = LocalTime.now();    
    System.out.println("Current Time: "+time);  
    System.out.println("Added one hour : "+time.plusHours(1));
    System.out.println("Minus one hour: "+time.minusHours(1));
    System.out.println("Added 5 minutes: "+time.plusMinutes(5));
    System.out.println("Minus 5 minutes: "+time.minusMinutes(5));
  }    
} 

Output

Current Time: 12:32:08.335274
Added one hour : 13:32:08.335274
Minus one hour: 11:32:08.335274
Added 5 minutes: 12:37:08.335274
Minus 5 minutes: 12:27:08.335274

15. What is the LocalDateTime in Java 8?

In Java 8, LocalDateTime is an immutable and thread-safe class from the java.time package that is used to represent a both date and time but without time zone information. Default format of LocalDateTime is year-month-day-hour-minute-second.

Some important functions of LocalDateTime are plusDays(), minusDays(), now(), of() etc.

Key Points of LocalDateTime:

  • Combines both date and time (e.g., 2025-06-18T14:30:15).
  • Default format: yyyy-MM-ddTHH:mm:ss
  • Does not include time zone information.
  • Useful for representing timestamps like created/updated time, appointments, logs, etc.

Example of Java 8 LocalDateTime

import java.time.LocalDateTime;    
import java.time.format.DateTimeFormatter; 
public class Main {    
  public static void main(String[] args) {    
    LocalDateTime now = LocalDateTime.now();  
    System.out.println("Date Time: " + now);  
    DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");  
    String formatDateTime = now.format(format);  
    System.out.println("Formated Date Time: " + formatDateTime);  
    System.out.println("Date Time Plus One: " + now.plusDays(1));
    System.out.println("Date Time Minus One: " + now.minusDays(2));
  }    
}

Output

Date Time: 2023-07-06T12:32:48.641509
Formated Date Time: 06-07-2023 12:32:48
Date Time Plus One: 2023-07-07T12:32:48.641509
Date Time Minus One: 2023-07-04T12:32:48.641509

16. What is the Difference between Predicate and Function?

In Java 8, both Predicate and Function are functional interfaces used in lambda expressions, but they serve different purposes.

  • A predicate can take one parameter that represents the input type or return type. The function takes two parameters one represents input type and the second represents return type.
  • The predicate has one test() function which means “test this function” Whereas the function has one apply() function means “apply this function”.
  • Predicate returns only Boolean value but Function can return any value.
  • If we want to perform some conditional checks we go with Predicates. But if we want to perform some operation, we should go with Function.

Key Differences:

FeaturePredicate<T>Function<T, R>
PurposeUsed to test a conditionUsed to transform or compute a value
Methodtest(T t)apply(T t)
Return TypeAlways returns a booleanReturns a value of any type R
ParametersTakes 1 input of type TTakes 1 input of type T, returns output of type R
Example Use CaseFiltering elements (e.g., check if number is even)Converting data (e.g., String to Integer)

Predicate Example Java 8

import java.util.function.Predicate;
public class Main {    
  public static void main(String[] args) {    
    Predicate<Integer> predicate = i -> (i < 10); 
    System.out.println(predicate.test(5)); 
  }    
}

Output

true

Function Example Java 8

import java.util.function.Function;
public class Main {    
  public static void main(String[] args) {    
    Function<String, Integer> function = x -> x.length();
    System.out.println(function.apply("Hello Function"));
  }    
}

Output

14

17. Difference between findFirst() and findAny()?

  • findFirst() returns the first element from List that meets the given criteria.
  • findAny() function returns any element from the list that will meet the criteria. This feature is very useful when we work with a parallel stream.

Example to demonstrate findFirst() and findAny()

import java.util.*;
public class Main {    
  public static void main(String[] args) {    
    List<String> list = Arrays.asList("A","B","C","D","E");
    Optional<String> resultFindAny = list.stream().findAny();
    Optional<String> resultFindFirst = list.stream().findFirst();
    System.out.println(resultFindAny.get());
    System.out.println(resultFindFirst.get());
  }    
}

Output

A
A

18. Tell us the Steps to Create a Functional Interface.

To Create Functional Interface Java 8 Provided @FunctionalInterface Annotation. This annotation is optional but recommended, as it tells the compiler to ensure that the interface contains exactly one abstract method. It can have only one abstract method and can have multiple static and default methods.

Java Program to Create Functional Interface

@FunctionalInterface
interface CustomFunctionalInterface {
   void display();
}
public class Main {    
   public static void main(String[] args) {    
      CustomFunctionalInterface functionalInterface = () -> { 
         System.out.println("Functional Interface Example");
      };
      functionalInterface.display();
   }    
}

Output

Functional Interface Example

Functional Interface Program to Calculate Cube 

@FunctionalInterface
interface Cube {
    int calculate(int x);
}
public class Main {    
    public static void main(String[] args) {    
        int a = 10;
        Cube c = (int x) -> x * x * x;
        int ans = c.calculate(a);
        System.out.println(ans);
   }    
}

Output

1000

19. What is Method Reference in Java 8?

In Java 8, Method Reference is a new feature that provides a short and clean way to refer to methods directly by their names, without calling them. It is used to refer to a method of a class or an object to be used in a lambda expression or functional interface.

Example to demonstrate Method Reference

If our Lambda Expression is written below

str -> System.out.println(str)

Method Reference will be like

System.out::println

“::” is the symbol that used in method reference.

Method Reference Example

import java.util.Collection;
import java.util.Arrays;
class Main {
    public static void main(String args[])
    {
        Collection collection = Arrays.asList("Hello","Method","Reference");
        collection.forEach(System.out::println);
    }
}

Output

Hello
Method
Reference

20. What are the Differences between limit and skip in Java 8?

  • Limit() method is used to return the stream of a given size. Suppose if we have written limit(10) it means total 10 output will be returned only.
  • skip() method is used to return stream after skipping the index starting from 0 to given index. Skip(5) means skip element from starting(0) to 5 elements i.e. index 4.

limit() example Java 8 

import java.util.stream.*;
class Main {
    public static void main(String args[])
    {
        Stream.of(0,1,2,3,4,5,6,7,8,9)
        .limit(5)         
        .forEach(num->System.out.print(num+"\n"));
    }
}

Output

0
1
2
3
4

skip() example Java 8

import java.util.stream.*;
class Main {
    public static void main(String args[])
    {
        Stream.of(0,1,2,3,4,5,6,7,8)
        .skip(5)         
        .forEach(num->System.out.print(num+"\n"));
    }
}

Output

5
6
7
8

21. Difference between Intermediate and Terminal Operations in Stream.

Generally, Stream operations are either Terminal or Intermediate operations. Intermediate Operations return the Stream to perform other operations on it.

  • Intermediate Operations process data when there is a Terminal operation carried out.
  • Some intermediate operations are map(), filter(), distinct(), sorted(), limit(), skip().
  • As an Intermediate return stream value, Terminal Operation returns non-stream values like primitive, object, or collection, or It will return nothing.
  • There might be multiple intermediate operations, but a stream can have only one terminal operation.
  • Some Terminal Operation are forEach(), toArray(), reduce(), collect(), min(), max(), count(), anyMatch(), allMatch(), noneMatch(), findFirst(), findAny() etc.
FeatureIntermediate OperationsTerminal Operations
Type of OperationTransformative. They take a stream and return a new stream.Consumptive. They produce a result or a side-effect from a stream.
StatefulnessCan be stateful or stateless.Always consume the stream, closing it.
Return TypeAlways return a Stream<T>. Allows chaining with other intermediate operations.Vary depending on the operation; can be an Optional, a boolean, a value, or void.
ExecutionLazily executed. Intermediate operations do not run until a terminal operation is invoked.Trigger the processing of the stream pipeline and close it.
Examplesmap, filter, distinct, sortedforEach, collect, reduce, anyMatch

Example of Intermediate & Terminal Operation

import java.util.*;
import java.util.stream.*;
public class Main {
   public static void main(String args[]) {
      List<Integer> arr = Arrays.asList(1,2,3,4,5); 
      List<Integer> output = arr.stream().map(x -> x * x).collect(Collectors.toList());
      System.out.println(output);
   }
}

Output

[1, 4, 9, 16, 25]

22. What is Nashorn in Java 8?

In Java 8,  Nashorn is added as the new default JavaScript engine for the JVM. It is a powerful and lightweight JavaScript engine introduced by Oracle. It allows you to execute JavaScript code directly from Java programs, running on the Java Virtual Machine (JVM).

Nashorn replaces the older Rhino engine and provides better performance and improved compliance with ECMAScript standards.

Key Features of Nashorn:

  • Runs JavaScript code from within Java applications.
  • Supports calling Java methods and accessing Java objects from JavaScript.
  • Enables building hybrid apps using both Java and JavaScript.
  • Integrated into the javax.script package (JSR-223 scripting API).

Example

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class NashornExample {
    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("print('Hello from JavaScript!');");
    }
}

As of Java 15, Nashorn has been deprecated and removed, but it was a significant feature introduced in Java 8 for JVM-based scripting.

23. Difference Between Map and flatMap Stream Operation?

Both map() and flatMap() are intermediate operations used in Java 8 Stream API to transform data, but they work differently.

map() – One-to-One Transformation

  • map() takes each element from the stream and applies a function to it, returning one output for each input.
  • It is used when the function returns a single value or object.
  • Output is a stream of transformed elements
  • One-to-one mapping occurs in a map()

Example of map()

import java.util.*;
import java.util.stream.Collectors;
class Main {
    public static void main(String[] args)
    {
        List<String> animal = Arrays.asList("cat","dog","monkey");
        List list = animal.stream()
                        .map(s -> s.length())
                        .collect(Collectors.toList());
        System.out.println("Character count of each String : " + list);
    }
}

Output

Character count of each String : [3, 3, 6]

flatMap() – One-to-Many Transformation

  • flatMap() is used when each element is mapped to a stream, and all resulting streams are flattened into a single stream.
  • flatMap() produces zero or more output for each input.
  • It is used when the function returns multiple values (as a stream or collection).
  • It helps in flattening nested structures, like List<List<String>>.
  • flatmap() allows one-to-many mapping

Example of flatMap()

import java.util.*;
import java.util.stream.Collectors;
class Main {
    public static void main(String[] args)
    {
        List<List<Integer> > arr = Arrays.asList(
        Arrays.asList(1, 2),Arrays.asList(3, 4), Arrays.asList(5, 6));
        System.out.println("Our 2D List :" + arr);
        List<Integer> flatList
            = arr.stream()
                  .flatMap(list -> list.stream())
                  .collect(Collectors.toList());
        System.out.println("flatMap Output after flatten : "
                           + flatList);
    }
}

Output

Our 2D List :[[1, 2], [3, 4], [5, 6]]
flatMap Output after flatten : [1, 2, 3, 4, 5, 6]

24. What is MetaSpace in Java 8?

MetaSpace is replaced with old PermGen memory space. It is used by the JVM to store class metadata, such as information about class structure, methods, and fields.

The difference between MetaSpace with PermGen is, MetaSpace is able to increase its size dynamically, while PermGen had a fixed size limit, which often led to OutOfMemoryError. MetaSpace stores class metadata in native memory (outside the heap), making memory management more efficient.

🔥 Below, I’ve shared a few handpicked Java 8 coding interview questions that are commonly asked in top MNCs.
💡 To explore the complete list, check out 👉 Java 8 Coding Specific Interview Questions with Solutions — curated specially for cracking real interview rounds.

25. Tell me something about StringJoiner Class in Java 8.

StringJoiner is a new class added in Java 8 under java.util package.

It is used to join multiple strings separated by delimiters along with providing prefix and suffix to them.

Program to demonstrate StringJoiner

import java.util.*;
import java.util.StringJoiner;
import java.util.Arrays; 
public class Main {
    public static void main(String[] args)
    {
        List<String> arr= Arrays.asList("Ram","Shyam","Alice","Bob");
        StringJoiner sj = new StringJoiner(",");
        sj.add(arr.get(0)).add(arr.get(1)).add(arr.get(2));
        System.out.println(sj);
    }
}

Output

Ram,Shyam,Alice

26. Write a Program to add any prefix and suffix to the String in Java 8?

To write a program in Java to add prefixes and suffixes in a given String we will use StringJoiner newly added in Java 8.

We will add “[“ and “]” as a prefix and suffix.

Program to add prefixes and suffix

import java.util.*;
import java.util.StringJoiner;
import java.util.Arrays; 
public class Main {
    public static void main(String[] args)
    {
        List<String> arr= Arrays.asList("Ram","Shyam","Alice","Bob");
        StringJoiner sj = new StringJoiner(",","[","]");
        sj.add(arr.get(0)).add(arr.get(1)).add(arr.get(2));
        System.out.println(sj);
    }
}

Output

[Ram,Shyam,Alice]

27. Print ten random numbers using forEach?

Below is the program to generate 10 random numbers using forEach. Here we are using a Random class to generate a Random number.

Program to generate a random number

import java.util.Random;
public class Main {    
  public static void main(String[] args) {    
    Random random = new Random();
    random.ints().limit(10).forEach(System.out::println);
  }    
} 

Output

-1542135975
418648077
1291667511
1956535422
805649755
-233920670
-8083929
-1654932449
-1616561678
1477724508

28. How you can print the highest number in Array?

import java.util.*;
public class Main {    
  public static void main(String[] args) {    
     List<Integer> numArray = Arrays.asList(3,5,1,9,22);
     int max = numArray.stream().max(Integer::compare).get();
     System.out.println("maximum number is " + max );
  }    
}  

Output

maximum number is 22

29. Print Current date, time, and date time using Java 8 Date and Time API.

class Main {
    public static void main(String[] args) {
        System.out.println("Current Date: " + java.time.LocalDate.now());
        System.out.println("Current Time: " + java.time.LocalTime.now());
        System.out.println("Current Date and Time: " + java.time.LocalDateTime.now());
    }
}

Output

Current Date: 2023-07-06
Current Time: 12:43:14.649560
Current Date and Time: 2023-07-06T12:43:14.650403

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now