Java QA
Java QA
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.
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.
What is the function flatmap() used for? Why do you require it?
The map function has been expanded with the flatmap function. It can flatten an
object in addition to changing it into another.
If you already have a list of lists but wish to integrate them all into a single
list, for instance. You can flatten using flatMap() in this situation. The map()
function can be used to transform an object at the same time.
To determine the lowest and greatest number in a stream, write a Java 8 program.
To obtain the highest and lowest integer from a Stream in this application, we used
the min() and max() functions. First, with the aid of the Comparator, we
initialized a stream that contains integers. We have compared the components of the
Stream using the comparing() function.
The highest and lowest integers will be returned when this function is combined
with max() and min(). When comparing the Strings, it will also function.
import java.util.Comparator;
import java.util.stream.*;
public class Java8{
public static void main(String args[]) {
Can one interface extend or inherit from another? o/p of the following program.
interface i1{
void i1();
}
@FunctionalInterface
interface i2 extends i1{
void i2();
}
public class Intv1 implements i2 {
public static void main(String[] args) {
Intv1 i=new Intv1();
i.i1();
i.i2();
}
@Override
public void i1() {
System.out.println("i1");
}
@Override
public void i2() {
System.out.println("i2");
}
}
Java 8 Program to add prefixe and suffix to the String using stringjoiner?
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
StringJoiner stringJoiner = new StringJoiner(",", "#", "#");
stringJoiner.add("Interview");
stringJoiner.add("Questions");
stringJoiner.add("Answers");
System.out.println("String after adding # in suffix and prefix :");
System.out.println(stringJoiner);
}
}
Java 8 program to multiply 3 to all elements in the list and print the list?
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7);
System.out.println(integerList.stream().map(i ->
i*3).collect(Collectors.toList()));
}
}
Java 8 program to remove the duplicate elements from the list using Stream?
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1,2,3,4,1,2,3);
System.out.println("After removing duplicates : ");
integerList.stream().collect(Collectors.toSet()).forEach(System.out::print);
}
}
import java.util.*;
import java.util.stream.*;
public class Main
{
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(
Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
list.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);
;
}
}
Java 8 program to perform cube on list elements and filter numbers greater than 50.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(4,5,6,7,1,2,3);
integerList.stream().map(i -> i*i*i).filter(i ->
i>50).forEach(System.out::println);
}
}
Given a list of integers, find out all the numbers starting with 1 using Stream
functions?
import java.util.*;
import java.util.stream.*;
public class NumberStartingWithOne{
public static void main(String args[]) {
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,32);
myList.stream()
.map(s -> s + "") // Convert integer to String
.filter(s -> s.startsWith("1"))
.forEach(System.out::println);
}
}
How to find duplicate elements in a given integers list in java using Stream
functions?
import java.util.*;
import java.util.stream.*;
public class DuplicateElements {
public static void main(String args[]) {
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
Set<Integer> set = new HashSet();
myList.stream()
.filter(n -> !set.add(n))
.forEach(System.out::println);
}
}
Given the list of integers, find the first element of the list and print it using
Stream functions?
public class FindFirstElement{
public static void main(String args[]) {
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
myList.stream()
.findFirst()
.ifPresent(System.out::println);
}
}
Given a String, find the first non-repeated character in it using Stream functions?
public class FirstNonRepeated{
public static void main(String args[]) {
String input = "Java articles are Awesome";
Character result = input.chars() // Stream of String
.mapToObj(s -> Character.toLowerCase(Character.valueOf((char) s))) //
First convert to Character object and then to lowercase
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.counting())) //Store the chars in map with count
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
}
Given a String, find the first repeated character in it using Stream functions?
public class FirstRepeated{
public static void main(String args[]) {
String input = "Java Articles are Awesome";
Character result = input.chars() // Stream of String
.mapToObj(s ->
Character.toLowerCase(Character.valueOf((char) s))) // First convert to Character
object and then to lowercase
.collect(Collectors.groupingBy(Function.identity(
), LinkedHashMap::new, Collectors.counting())) //Store the chars in map with count
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);
}
Given a list of integers, sort all the values present in it in descending order
using Stream functions?
public class SortDescending{
public static void main(String args[]) {
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
myList.stream()
.sorted(Collections.reverseOrder())
.forEach(System.out::println);
}
}
Given an integer array nums, return true if any value appears at least twice in the
array, and return false if every element is distinct.
public boolean containsDuplicate(int[] nums) {
List<Integer> list = Arrays.stream(nums)
.boxed()
.collect(Collectors.toList());
Set<Integer> set = new HashSet<>(list);
if(set.size() == list.size()) {
return false;
}
return true;
}
How to check if list is empty in Java 8 using Optional, if not null iterate through
the list and print the object?
Optional.ofNullable(noteLst)
.orElseGet(Collections::emptyList) // creates empty immutable list: []
in case noteLst is null
.stream().filter(Objects::nonNull) //loop throgh each object and
consider non null objects
.map(note -> Notes::getTagName) // method reference, consider only tag
name
.forEach(System.out::println); // it will print tag names
Is there anything wrong with the following code? Will it compile or give any
specific error?
@FunctionalInterface
public interface Test<A, B, C> {
public C apply(A a, B b);
Write a Java 8 program to square the list of numbers and then filter out the
numbers greater than 100 and then find the average of the remaining numbers?
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
public class Java8 {
public static void main(String[] args) {
Integer[] arr = new Integer[] { 100, 100, 9, 8, 200 };
List<Integer> list = Arrays.asList(arr);
// Stored the array as list
OptionalDouble avg = list.stream().mapToInt(n ->; n * n).filter(n -> n >
100).average();
/* Converted it into Stream and filtered out the numbers
which are greater than 100. Finally calculated the average
*/
if (avg.isPresent())
System.out.println(avg.getAsDouble());
}
}
Explain StringJoiner Class in Java 8? How can we achieve joining multiple Strings
using StringJoiner Class?
Answer: In Java 8, a new class was introduced in the package java.util which was
known as StringJoiner. Through this class, we can join multiple strings separated
by delimiters along with providing prefix and suffix to them.
In the below program, we will learn about joining multiple Strings using
StringJoiner Class. Here, we have “,” as the delimiter between two different
strings. Then we have joined five different strings by adding them with the help of
the add() method. Finally, printed the String Joiner.
class StringDemo
{
public static void main (String[]args)
{
String s1 = new String ("This is infotel Material");
String s2 = new String ("This is infotel Material");
System.out.println (s1 == s2);
String s3 = "This is infotel Material";
System.out.println (s1 == s3);
String s4 = "This is infotel Material";
System.out.println (s3 == s4);
String s5 = "This is ";
String s6 = s5 + "infotel Material";
System.out.println (s3 == s6);
final String s7 = "This is ";
String s8 = s7 + "infotel Material";
System.out.println (s3 == s8);
System.out.println (s5 == s7);
}
}
Answer:
false false true false true true