Tuesday, August 27, 2024

Stream API Coding Interview-1

 Java Stream API Coding Interview: Part 1

Q. Find the longest string from a list of string using stream API:

package com.demo.example;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class StreamApiOnListOfString {

	public static void main(String[] args) {
		// Way-1
		List<String> listStr = Arrays.asList("apple", "banana", "orange", "pineapple", "grapefruit");
		Optional<String> longestString = listStr.stream().max(Comparator.comparingInt(String::length));
		System.out.println(longestString);

		// we can get string from optional as below
		String s1 = String.valueOf(longestString.get());
		System.out.println("Optional To Strin: " + s1);

		// Way-2
		// OR we can get string as below
		String largeString = listStr.stream().max(Comparator.comparingInt(String::length)).orElse(null);
		System.out.println(largeString);
	}
}

// Optput
Optional[grapefruit]
Optional To Strin: grapefruit
grapefruit

Q. Find the smallest string from a list of string using stream API:

package com.demo.example;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class StreamApiOnListOfString {

	public static void main(String[] args) {
		// Way-1
		List<String> listStr = Arrays.asList("apple", "banana", "orange", "pineapple", "grapefruit");
		Optional<String> longestString = listStr.stream().min(Comparator.comparingInt(String::length));
		System.out.println(longestString);

		// we can get string from optional as below
		String s1 = String.valueOf(longestString.get());
		System.out.println("Optional To Strin: " + s1);

		// Way-2
		// OR we can get string as below
		String largeString = listStr.stream().min(Comparator.comparingInt(String::length)).orElse(null);
		System.out.println(largeString);
	}
}

// Optput
Optional[apple]
Optional To Strin: apple
apple

Q. Find the frequency of each word using Java streams, from a list of strings.

package com.demo.example;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FrequencyOfEachWordInList {

	public static void main(String[] args) {
		List<String> words = Arrays.asList("apple", "pineapple", "banana", "orange", "pineapple", "grapefruit", "apple",
				"orange", "pineapple");
		Map<String, Long> mapFrequency = words.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
		System.out.println(mapFrequency.toString());

		// OR
		Map<String, Long> mapFrequency2 = words.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting()));
		System.out.println(mapFrequency2.toString());

		// Way-1
		System.out.println("############ Print Map Using Stream : Way-1 ###### ");
		words.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet()
				.forEach(System.out::println);

		// Way-2
		System.out.println("############ Print Map Using Stream : Way -2 ###### ");
		words.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet()
				.forEach(e -> System.out.println(e));
	}
}
// output 
{orange=2, banana=1, apple=2, pineapple=3, grapefruit=1}
{orange=2, banana=1, apple=2, pineapple=3, grapefruit=1}

############ Print Map Using Stream : Way-1 ###### 
orange=2
banana=1
apple=2
pineapple=3
grapefruit=1

############ Print Map Using Stream : Way -2 ###### 
orange=2
banana=1
apple=2
pineapple=3
grapefruit=1

Q. Convert Map to List using stream API:

package com.demo.example;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MapToListStreamApiExample {

	public static void main(String[] args) {

		Map<Integer, String> studentMap = new HashMap<>();
		studentMap.put(101, "Ram");
		studentMap.put(102, "Shyam");
		studentMap.put(103, "Mohan");
		System.out.println("Print Map: " + studentMap);

		System.out.println("############ Map to list of String");
		List<String> nameList = studentMap.values().stream().collect(Collectors.toList());
		System.out.println("List of names from Map :" + nameList);

		// OR
		System.out.println("############ Print using forEach");
		studentMap.values().stream().collect(Collectors.toList()).forEach(System.out::println);

		System.out.println("############ Map to list of integers");
		List<Integer> idsList = studentMap.keySet().stream().collect(Collectors.toList());
		System.out.println("List of ids from Map :" + idsList);

		// OR
		System.out.println("############  Print using forEach");
		studentMap.keySet().stream().forEach(System.out::println);

		// Convert Map to singleList
		System.out.println("############  Convert Map to singleList");
		List<Map.Entry<Integer, String>> singleList = studentMap.entrySet().stream().collect(Collectors.toList());
		System.out.println("Map to singleList: " + singleList);

		
		System.out.println("############  Use of toCollection instead of toList ");
		// In place Collectors.toList() you can use Collectors.toCollection() method,
		// which allows us to chose the particular List implementation it can be
		// ArrayList or LinkedList as per requirement:
		List<Integer> idsList1 = studentMap.keySet().stream().collect(Collectors.toCollection(LinkedList::new));
		List<String> nameList1 = studentMap.values().stream().collect(Collectors.toCollection(LinkedList::new));
		System.out.println("ids list: " + idsList);
		System.out.println("name list: " + nameList1);
	}
}

// Output
Print Map: {101=Ram, 102=Shyam, 103=Mohan}
############ Map to list of String
List of names from Map :[Ram, Shyam, Mohan]
############ Print using forEach
Ram
Shyam
Mohan
############ Map to list of integers
List of ids from Map :[101, 102, 103]
############  Print using forEach
101
102
103
############  Convert Map to singleList
Map to singleList: [101=Ram, 102=Shyam, 103=Mohan]
############  Use of toCollection instead of toList 
ids list: [101, 102, 103]
name list: [Ram, Shyam, Mohan]

Q. Convert a String to a List of Characters in Java 8:

String input = "Java is object oriented language";
		input = input.replaceAll("\\s+", ""); // Remove whitespace from string
		
		List<Character> charArryList = input.chars() // Stream of String
				.mapToObj(s -> Character.toLowerCase(Character.valueOf((char) s))).collect(Collectors.toList());
		System.out.println("##########  List of Characters in String : "+charArryList);

// Output
##########  List of Characters in String : [j, a, v, a, i, s, o, b, j, e, c, t, o, r, i, e, n, t, e, d, l, a, n, g, u, a, g, e]

Q. Find the list of Unique Characters in a String using stream API:

Output

Output

Q. Find value that occurs in odd number of elements means (the value of the unpaired element. like 7 is unpaired in array).:

int[] arr = { 9, 3, 9, 3, 9, 7, 9 };
		
// using stream API
Arrays.stream(arr).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
			.entrySet().stream().filter(ent -> ent.getValue() % 2 == 1)
			.forEach(e -> System.out.println(e.getKey()));

// output
7

Q. Find the list of duplicate characters in a string using stream API:

Output

Output

No comments:

Post a Comment