0% found this document useful (0 votes)
23 views4 pages

Java 8 Problems and Solutions

This document contains 17 questions and solutions related to string and array manipulation using Java 8 streams and other features. The questions cover topics like finding the longest/shortest words in a string, counting character and word occurrences, partitioning arrays, rearranging array elements, and more. The solutions provided use streams, collectors, regex, and other Java 8 constructs to concisely solve the problems in 1-2 lines of code.

Uploaded by

khushivansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

Java 8 Problems and Solutions

This document contains 17 questions and solutions related to string and array manipulation using Java 8 streams and other features. The questions cover topics like finding the longest/shortest words in a string, counting character and word occurrences, partitioning arrays, rearranging array elements, and more. The solutions provided use streams, collectors, regex, and other Java 8 constructs to concisely solve the problems in 1-2 lines of code.

Uploaded by

khushivansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

1) Remove duplicates from string and return in same order".

String s = "dabfcadef"; -> dabfce

s.chars().distinct().mapToObj( c-> (char) c ).forEach(System.out::println);

Arrays.stream(s.split("")).distinct().forEach(System.out::print);

2) Given a sentence find the word that has the highest length. The solution is:

String s = "I am interested123455 to grow in my organization";


String maxString = Arrays.stream(s.split("
")).max(Comparator.comparing(String::length)).get();
System.out.println("The maxString is: " + maxString);

3) Given a sentence find the word that has the 2nd (Nth) highest length.

Answer is below: skip(N). N =0 (highest) N =1 (2nd Highest) N =2 (3rd


Highest...)

String a =
Arrays.stream(s.split("")).sorted(Comparator.comparing(String::length).reversed()).
skip(0).findFirst().get();

System.out.println(a);

This question asked in SNP. They will tweak the same question with list of Employee
Objects. But this is the base logic.

Q4) Find the length of the longest word

Solution : Arrays.stream(s.split(" ")).mapToInt(l -> l.length()).max().getAsInt();

Q5). Find the 2nd highest length word in the given sentence

Solution : Arrays.stream(s.split(" ")).map(l ->


l.length()).sorted(Comparator.reverseOrder()).skip(1).findFirst().get();

Q6) Given a sentence, find the number of occurrence of each word.

Solution:

String input = "the quick brown fox jumps right over the little lazy dog little";
Map<String, Long> collect = Arrays.stream(input.split(" "))
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
System.out.println(collect);

Q7) Given a word, find the occurrence of Each Character

Q8) There is a list of Employees and Employee object has a field called e-mail.
Find the list of domains ( gmail.com, yahoo.com..) and the no of occurrences for
each domain.

Q9) Given a string, find the words with the maximum number of vowels.
"The quick brown fox jumps right over the little lazy dog."
Maximum Number of Vowels: 2
output Words: quick, over, little ( because each word has maximum of 2
vowels)

Solution is:

String s = "The quick brown fox jumps right over the little lazy dog.";
Arrays.stream(s.split(" "))
.filter(e -> e.replaceAll("[^aeiouAEIOU]", "").length() == 2)
.forEach(System.out::println);

NOTE: Please understand the REGEX solution here

Q10) Reverse a string with speical characters and Speical characters position
shouldn't be changed".

Solution is:

public static String reverseString(String input) {

String reversedString = new StringBuffer(input.replaceAll("[^a-zA-Z]",


"")).reverse().toString();
String replacedString = input.replaceAll("[a-zA-Z]", "_");

char ch[] = reversedString.toCharArray();


for(char c:ch) {
replacedString = replacedString.replaceFirst("_", String.valueOf(c));
}
System.out.println("-------> " + replacedString);
return replacedString;
}

public static void main(String[] args) {


String input = "Swa$pn&il";
String[] arr = input.split("");
String regex = "[^0-9a-zA-Z]";

StringBuilder reversed=new StringBuilder(input.replaceAll(regex,


"")).reverse();

IntStream.range(0, input.length()-1)
.filter(i->arr[i].matches(regex))
.forEach(i->reversed.insert(i, arr[i]));

System.out.println(reversed);
}
Q11) Given a list of integers, divide into two lists one having even numbers and
other having odd numbers.

Solutions:

List<List<Integer>> lists = intList.stream()


.collect(Collectors.groupingBy(key->key%2==0,Collectors.toList()))
.entrySet().stream().map(e->e.getValue()).collect(Collectors.toList());

System.out.println(lists);

2. intList.stream()
.collect(Collectors.partitioningBy(integerValue->integerValue
%2==0))
.entrySet().stream().map(mapValue-
>mapValue.getValue()).collect(Collectors.toList());

3. Map<Boolean, List<Integer>> partitions = ints.stream()


.collect(Collectors.partitioningBy(x -> x % 2 == 0));
List<Integer> evens = partitions.get(true);
List<Integer> odds = partitions.get(false);
The entryset logic in solution 1 and 2 is to process the map. and also please know
the difference between partitionBy and groupBy and when to use.

Q12) Given an array of integers (2, 34, 54, 23, 33, 20, 59, 11, 19, 37 ) group the
numbers by the range they belong to. The put put should be {0=[2], 50=[54,59],
20=[23,20], 10=[11,19], 30=[34,33,37]}

Solution is:
Map<Integer, List<Integer>> map =
Stream.of(2, 34, 54, 23, 33, 20, 59, 11, 19,37).collect(Collectors.groupingBy (i -
> i/10 * 10 ));
System.out.println(map);

Q13) Given a List of Strings ["as", "123", "32", "2as"], create another Integer
list that contains only integers. The output shoul be: List<Integer> iList =
[123,32]
Solution:
listOfStrings.stream().filter( ss -> ss.matches("[0-
9]*")).map(Integer::valueOf).collect(Collectors.toList());

Q14) Given an array of integers arr = {5,6,7,8,5,5,8,8,7) find the sum of the
unique elements. The output should be in this case is: 26.

Solution : Arrays.stream(arr).distinct().sum();

Q15 ) Given a numeric array , re arrange the elements to form a smallest possible
value.

input is: int arr[] = {1, 34, 3, 98, 9, 76, 45, 4};

output is: 133444576998


Solution is: Arrays.stream(arr).mapToObj(i->
i+"").sorted().forEach(System.out::print);

Q16) Given a numeric array , re arrange the elements to form a highest possible
value.

input is: int arr[] = {1, 34, 3, 98, 9, 76, 45, 4};

output is: 998764543431

Solution is: Arrays.stream(arr).mapToObj(i-> i+"").sorted((o1,o2) ->


(o2+o1).compareTo(o1+o2)).forEach(System.out::print)

2) Arrays.stream(arr12).mapToObj(i->
i+"").sorted(Collections.reverseOrder()).forEach(System.out::print);

Q17) Given a String = The quick brown fox jumps over the lazy dog, find the first
non repeated character. (Google interview)

Solution with java 8 :

String res = Arrays.stream(str.split("")).filter(c -> str.indexOf(c) ==


str.lastIndexOf(c)).findFirst().get();
System.out.println(res);

You might also like