TCS Java Interview Questions

Published by user on

In this post, we covered the TCS java interview questions. The candidate got asked about the Java 8 Stream operations where he was given two list and he has to do concatenation of two lists.

After that he has to find the unique elements from the list and finally he has to find the minimum and maximum numbers from the list using streams.

package interview;

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

public class JavaStreamOperations {
	public static void main(String[] args) {
		List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6);
		List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8, 9);

		Stream<Integer> fullList = Stream.concat(list1.stream(), list2.stream());

		List<Integer> allElements = fullList.collect(Collectors.toList());
		System.out.println(allElements);

		Set<Integer> uniqueElements = allElements.stream().collect(Collectors.toSet());
		System.out.println("Unique elements");
		System.out.println(uniqueElements);

		Integer max = uniqueElements.stream().max((x1, x2) -> x1 - x2).get();
		System.out.println(max);

	}
}

Output:

[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
Unique elements
[1, 2, 3, 4, 5, 6, 7, 8, 9]
9
Categories: Java