Java QA

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 11

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.

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.

What distinguishes Stream's intermediate and terminal operations?


You can call additional methods of the Stream class to build a pipeline because the
intermediary Stream action returns another Stream.
For instance, you can still call the filter() method on a Stream after calling
map() or flatMap().
The terminal action, on the other hand, generates results other than streams, such
as a value or a Collection.
You cannot call any other Stream methods or reuse the Stream once a terminal method
like forEach() or collect() has been called.

By "Stream is lazy," what do you mean?


When we state that a stream is lazy, we mean that the majority of its methods,
which are described in the Java.util. Stream.Stream classes, will not function if
they are simply added to the stream pipeline.
They only function when a terminal method on the Stream is called, and rather than
searching through the entire collection of data, and they stop as soon as they
locate the data they are looking for.

What distinguishes a Java functional interface from a conventional interface?


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.

What does "Predicate interface" mean?


A function that takes an Object and returns a boolean is represented by a
Predicate, a functional interface. Several Stream methods, like filter(), which
employs Predicate to filter out undesirable components, use it.
Here is an example of a predicate function:
lic boolean test(T object){
return boolean;
}

Can an array be converted to a stream? How?


Yes, you can use Java to transform an array into a stream. The Stream class offers
a factory method to make a Stream from an array, such as Stream.of(T...), which
accepts a variable parameter, meaning you may also supply an array to it, as
demonstrated in the example below:
String[] languages = {"Java", "Python", "JavaScript"};
Stream numbers = Stream.of(languages);
numbers.forEach(System.out::println);

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[]) {

Integer highest = Stream.of(1, 2, 3, 77, 6, 5)


.max(Comparator.comparing(Integer::valueOf))
.get();
/* We have used max() method with Comparator.comparing() method
to compare and find the highest number
*/
Integer lowest = Stream.of(1, 2, 3, 77, 6, 5)
.min(Comparator.comparing(Integer::valueOf))
.get();
/* We have used max() method with Comparator.comparing() method
to compare and find the highest number
*/
System.out.println("The highest number is: " + highest);
System.out.println("The lowest number is: " + lowest);
}
}

What does Java’8 Stream pipelining mean?


Chaining together operations is the idea behind Stream pipelining. To do this, we
divide the possible operations on a stream into two groups: intermediate operations
and terminal operations.
When an intermediate action completes, it produces an instance of Stream. As a
result, we can create a processing pipeline with any number of intermediary
processes to process data.
The pipeline must then be terminated by a terminal operation that returns a final
value.

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 iterate a Stream using the forEach method?


import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> str =
Arrays.asList("Hello","Interview","Questions","Answers");
str.stream().forEach(System.out::println);
}
}

Java 8 program to find the Minimum number of a Stream?


import java.util.Comparator;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Integer min = Stream.of(1, 2, 3, 4, 5, 6,7)
.min(Comparator.comparing(Integer::valueOf))
.get();
System.out.println("The Minimum number is: " + min);
}
}

Java 8 program to find the Maximum number of a Stream?


import java.util.Comparator;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Integer max = Stream.of(1, 2, 3, 4, 5, 6,7)
.max(Comparator.comparing(Integer::valueOf))
.get();
System.out.println("The Maximum number is: " + max);
}
}
Java 8 program to Count Strings whose length is greater than 3 in List using
Stream?
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> stringList =
Arrays.asList("Hello","Interview","Questions","Answers","Ram","for");
long count = stringList.stream().filter(str -> str.length() > 3).count();
System.out.println("String count with greater than 3 digit : " + count);
}
}

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 perform concatenation on two Streams?


import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> integerList1 = Arrays.asList(1,2,3,4);
List<Integer> integerList2 = Arrays.asList(5,6,7);
Stream<Integer> concatStream = Stream.concat(integerList1.stream(),
integerList2.stream());
concatStream.forEach(System.out::print);
}
}

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 use map to convert object into Uppercase in Java 8?


public static void main(String[] args) {
List<String> nameLst = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(nameLst);
}

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

Write a program to print the count of each character in a String?


Input: String s = "string data to count each character";
Output: {s=1, t=5, r=3, i=1, n=2, g=1, =5, d=1, a=5, o=2, c=4, u=1, e=2, h=2}
public static void findCountOfChars(String s) {
Map<String, Long> map = Arrays.stream(s.split(""))
.map(String::toLowerCase)
.collect(Collectors
.groupingBy(str -> str,
LinkedHashMap::new, Collectors.counting()));
}

What are the default methods?


Answer: Default methods are the methods of the Interface which has a body. These
methods, as the name suggests, use the default keywords. The use of these default
methods is “Backward Compatibility” which means if JDK modifies any Interface
(without default method) then the classes which implement this Interface will
break.
On the other hand, if you add the default method in an Interface then you will be
able to provide the default implementation. This won’t affect the implementing
classes.
Syntax:
public interface questions{

default void print() {


System.out.println("www.softwaretestinghelp.com");
}
}

What is a SAM Interface?


Answer: Java 8 has introduced the concept of FunctionalInterface that can have only
one abstract method. Since these Interfaces specify only one abstract method, they
are sometimes called as SAM Interfaces. SAM stands for “Single Abstract Method”.

Explain the following Syntax


String:: Valueof Expression
Answer: It is a static method reference to the ValueOf method of the String class.
System.out::println is a static method reference to println method of out object of
System class.
It returns the corresponding string representation of the argument that is passed.
The argument can be Character, Integer, Boolean, and so on.

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);

default void printString() {


System.out.println("softwaretestinghelp");
}
}
Answer: Yes. The code will compile because it follows the functional interface
specification of defining only a single abstract method. The second method,
printString(), is a default method that does not count as an abstract method.

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());
}
}

What is the difference between Iterator and Spliterator?


Answer: Below is the differences between Iterator and Spliterator.
Iterator Spliterator
It was introduced in Java version 1.2 It was introduced in Java SE 8
It is used for Collection API. It is used for Stream API.
Some of the iterate methods are next() Spliterator method is tryAdvance().
and hasNext() which are used to iterate
elements.
We need to call the iterator() method on We need to call the spliterator() method
on Stream Object.
Collection Object.
Iterates only in sequential order. Iterates in Parallel and sequential
order.

What is the Consumer Functional Interface?


Answer: Consumer Functional Interface is also a single argument interface (like
Predicate<T> and Function<T, R>). It comes under java.util.function.Consumer. This
does not return any value.
In the below program, we have made use of the accept method to retrieve the value
of the String object.
import java.util.function.Consumer;
public class Java8 {
public static void main(String[] args)
Consumer<String> str = str1 -> System.out.println(str1);
str.accept("Saket");
/* We have used accept() method to get the
value of the String Object
*/
}
}

What is the Supplier Functional Interface?


Answer: Supplier Functional Interface does not accept input parameters. It comes
under java.util.function.Supplier. This returns the value using the get method.
In the below program, we have made use of the get method to retrieve the value of
the String object.
import java.util.function.Supplier;
public class Java8 {
public static void main(String[] args) {
Supplier<String> str = () -> "Saket";
System.out.println(str.get());
/* We have used get() method to retrieve the
value of String object str.
*/
}
}

What is the Difference Between Map and flatMap Stream Operation?


In Java, the Stream interface has a map() and flatmap() methods and both have
intermediate stream operation and return another stream as method output. Both of
the functions map() and flatMap are used for transformation and mapping operations.
map() function produces one output for one input value, whereas flatMap() function
produces an arbitrary no of values as output (ie zero or more than zero) for each
input value.
map() flatMap()
The function passed to map() operation returns a single value for a single input.
The
function you pass to flatmap() operation returns an arbitrary number of values
as the output.
One-to-one mapping occurs in map(). One-to-many
mapping occurs in flatMap().
Only perform the mapping.
Perform mapping as well as flattening.
Produce a stream of value.
Produce a stream of stream value.
map() is used only for transformation. flatMap() is
used both for transformation and mapping.

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.

What will be the output of the following program ?


class Parent
{
public void display ()
{
System.out.println ("Parent");
}
}
class Child extends Parent
{
public void display ()
{
System.out.println ("Child");
}
}
class Main
{

public static void doDisplay (Parent p)


{
p.display ();
}

public static void main (String[]args)


{
Parent a = new Parent ();
Parent b = new Child ();
Child c = new Child ();
doDisplay (a);
doDisplay (b);
doDisplay (c);
}
}
Answe: Parent Child Child

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

public class Main extends Thread implements Runnable


{
public void run ()
{
System.out.println ("Infotel");
}

public static void main (String[]args) throws InterruptedException


{
Main obj = new Main ();
obj.start ();
obj.run ();
}
}
Answer:
Infotel Infotel

public class Main


{
public static void main (String[]args)
{
Map < integer, String > student = new HashMap < Integer, String > ();

student.put (101, "Rahit");


student.put (102, "Sudhir");
student.put (103, "Adithya");
student.put (104, "Sakshi");
System.out.println (student.remove (102));
}
}
Answer:
Sudhir

What does the following method do?


public static int func (int no)
{
Deque<Integer> q = new ArrayDeque<Integer> ();
while (no > 0)
{
q.push (no % 10);
no = no / 10;
}
int result = 0;
while (q.peek () != null)
result = result + q.pop ();
return result;
}
Answer:
Takes a number as a input and returns the sum of its digits

You might also like