Java 8
Q: What are the new features of java 8 ?
Ans:
1. Stream API:Question: Write a Java 8 function that takes a list of integers and returns a list of even integers sorted in descending order.Follow-Up: How would you modify the function to return only the first 3 even integers?Example Solution:
import java.util.List;import java.util.stream.Collectors;
public class Example { public List<Integer> getEvenNumbersDescending(List<Integer> numbers) { return numbers.stream() .filter(n -> n % 2 == 0) .sorted((a, b) -> b - a) // Sorting in descending order .collect(Collectors.toList()); } public List<Integer> getFirstThreeEvenNumbersDescending(List<Integer> numbers) { return numbers.stream() .filter(n -> n % 2 == 0) .sorted((a, b) -> b - a) // Sorting in descending order .limit(3) // Limiting to the first 3 results .collect(Collectors.toList()); }}
2. Functional Interfaces:Question: Create a custom functional interface that takes two integers and returns their sum. Then, use it in a lambda expression.Example Solution:
@FunctionalInterfaceinterface Adder { int add(int a, int b);}
public class Example { public static void main(String[] args) { Adder adder = (a, b) -> a + b; System.out.println("Sum: " + adder.add(5, 3)); // Output: Sum: 8 }}
3. Optional:Question: Write a method that finds the first string in a list that starts with the letter "A". If no such string is found, return "Not found" using Optional.Example Solution:
import java.util.List;import java.util.Optional;
public class Example { public String findFirstStringStartingWithA(List<String> strings) { return strings.stream() .filter(s -> s.startsWith("A")) .findFirst() .orElse("Not found"); }}
4. Map and Reduce:Question: Given a list of integers, write a method to find the product of all integers using Java 8 streams.Example Solution:
import java.util.List;
public class Example { public int findProduct(List<Integer> numbers) { return numbers.stream() .reduce(1, (a, b) -> a * b); // Multiply all elements }}
5. Default and Static Methods in Interfaces:Question: Create an interface with a default method that returns a greeting message. Then, implement this interface in a class and demonstrate the usage of the default method.Example Solution:
interface Greeter { default String greet() { return "Hello!"; }}
public class Example implements Greeter { public static void main(String[] args) { Example example = new Example(); System.out.println(example.greet()); // Output: Hello! }}
6. Lambda Expressions and Method References:Question: Given a list of strings, write a method that converts all strings to uppercase using method references.Example Solution:
import java.util.List;import java.util.stream.Collectors;
public class Example { public List<String> convertToUpper(List<String> strings) { return strings.stream() .map(String::toUpperCase) // Using method reference .collect(Collectors.toList()); }}
7. Parallel Streams:Question: What are parallel streams, and how would you use them to find the sum of a large list of integers?Example Answer: Parallel streams are a feature in Java 8 that allow you to process data in parallel, potentially improving performance on large datasets by utilizing multiple CPU cores. However, they should be used carefully due to possible thread-safety issues.
Example Solution:
import java.util.List;
public class Example { public int sumWithParallelStream(List<Integer> numbers) { return numbers.parallelStream() .mapToInt(Integer::intValue) .sum(); }}
8. Collectors Grouping:Question: Write a method that groups a list of strings by their length using Collectors.groupingBy().Example Solution:
import java.util.List;import java.util.Map;import java.util.stream.Collectors;
public class Example { public Map<Integer, List<String>> groupByLength(List<String> strings) { return strings.stream() .collect(Collectors.groupingBy(String::length)); }}
Q: What distinguishes a collection from a stream?
A Collection contains its elements, whereas a Stream does not, and this is the primary distinction between the two types of data structures.
Unlike other views, Stream operates on a view whose elements are kept in a collection or array, but any changes made to Stream do not affect the original collection.
Q: What is the function map() used for? You use it, why?
In Java, functional map operations are performed using the map() function. This indicates that it can apply a function to change one type of object into another.
Use map(), for instance, to change a List of String into a List of Integers if you have one already.
It will apply to all elements of the List and give you a List of Integer if you only supply a function to convert String to Integer, such as parseInt() or map(). The map can change one object into another.
Q: What distinguishes a Java functional interface from a conventional interface?
Ans: While the functional interface in Java can only contain one abstract method, the normal interface can contain any number of abstract methods.
They wrap a function in an interface, which is why they are termed functional interfaces. The one abstract method on the interface serves as the function's representation.
Q: Print odd/even numbers from Array and List with java Stream
Ans:
public static void main(String[] args)
{
List<Integer> numbers = Arrays.asList(1, 4, 8, 40, 11, 22, 33, 99);
List<Integer> oddNumbers = numbers.stream().filter(o -> o % 2 != 0).collect(Collectors.toList());
List<Integer> evenNumbers = numbers.stream().filter(o -> o % 2 = 0).collect(Collectors.toList());
System.out.println(oddNumbers);
System.out.println(evenNumbers);
}
Q: How to use stream in Map ?
Q: What does the Java 8 StringJoiner Class mean? How can we use the StringJoiner Class to join several Strings?
Q: How does a lambda expression relate to a functional interface? What is a lambda expression in Java?
Q: Write some sample program to use stream functions
Q: A Stream API: What Is It? Why is the Stream API necessary?
- Processing is straightforward since it offers aggregate operations.
- Programming in the functional style is supported.
- The processing speed is accelerated. It is, therefore, suitable for greater performance.
- Parallel operations are possible.
Q: Can you convert an array to Stream? How?
Q: Operation on map with stream API
Q: What are the build-in functions present in Stream API ?
Q: Write a program to print prime number with java stream
- We use IntStream.rangeClosed to create a stream of integers from 3 up to the square root of the number. This is because a larger factor of the number must be paired with a smaller factor that would have already been checked.
- We filter out even numbers since we’ve already handled divisibility by 2.
- We use noneMatch to check if there is any number in the range that divides the given number without a remainder. If there is no such number, the number is prime.
Comments
Post a Comment