[Go to site: main page, start]

0% found this document useful (0 votes)
2 views57 pages

Java 8 Coding

Uploaded by

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

Java 8 Coding

Uploaded by

Lednes K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Master Java 8 Interviews with 100+ Coding

Questions and Solutions

By Rambathri Vishal
Q1. How do you convert a List to a Set in Java 8?

java

List<Integer> list = [Link](1, 2, 2, 3, 3, 4);

// Method 1 - Constructor

Set<Integer> set = new HashSet<>(list);

// Method 2 - Stream

Set<Integer> set2 = [Link]()

.collect([Link]());

[Link](set); // [1, 2, 3, 4]

Q2. How do you convert a List to a LinkedHashSet to preserve insertion order?

java

List<Integer> list = [Link](3, 1, 2, 1, 3);

Set<Integer> set = [Link]()

.collect([Link](LinkedHashSet::new));

[Link](set); // [3, 1, 2]

Q3. How do you convert a Set to a List in Java 8?

java

Set<String> set = new HashSet<>([Link]("banana", "apple", "cherry"));


// Method 1 - Constructor

List<String> list = new ArrayList<>(set);

// Method 2 - Stream

List<String> list2 = [Link]()

.collect([Link]());

[Link](list2);

Q4. How do you convert a Set to a sorted List?

java

Set<Integer> set = new HashSet<>([Link](5, 3, 1, 4, 2));

List<Integer> sortedList = [Link]()

.sorted()

.collect([Link]());

[Link](sortedList); // [1, 2, 3, 4, 5]

Q5. How do you convert a List to a Map using Java 8 Streams?

java

List<String> words = [Link]("apple", "banana", "kiwi");

Map<String, Integer> map = [Link]()

.collect([Link](w -> w, String::length));

[Link](map); // {apple=5, banana=6, kiwi=4}


Q6. How do you convert a Map to a List of keys and values separately?

java

Map<String, Integer> map = new HashMap<>();

[Link]("Alice", 90);

[Link]("Bob", 85);

List<String> keys = new ArrayList<>([Link]());

List<Integer> values = new ArrayList<>([Link]());

// OR using streams

List<String> keys2 = [Link]().stream()

.collect([Link]());

[Link](keys); // [Alice, Bob]

[Link](values); // [90, 85]

Q7. How do you find the second highest number in a list?

java

List<Integer> list = [Link](10, 5, 8, 20, 15, 20);

int secondHighest = [Link]()

.distinct()

.sorted([Link]())

.skip(1)

.findFirst()

.orElseThrow(() -> new RuntimeException("Not enough elements"));

[Link](secondHighest); // 15
Q8. How do you find the most frequent element in a list?

java

List<String> list = [Link]("a", "b", "a", "c", "a", "b");

String mostFrequent = [Link]()

.collect([Link](s -> s, [Link]()))

.entrySet().stream()

.max([Link]())

.map([Link]::getKey)

.orElse(null);

[Link](mostFrequent); // a

Q9. How do you group strings by their first character and count them?

java

List<String> words = [Link]("apple","avocado","banana","blueberry","cherry");

Map<Character, Long> result = [Link]()

.collect([Link](

w -> [Link](0),

[Link]()

));

[Link](result); // {a=2, b=2, c=1}

Q10. How do you flatten a nested list and get distinct sorted elements?

java
List<List<Integer>> nested = [Link](

[Link](3, 1, 2),

[Link](5, 3, 4),

[Link](2, 6, 1)

);

List<Integer> result = [Link]()

.flatMap(Collection::stream)

.distinct()

.sorted()

.collect([Link]());

[Link](result); // [1, 2, 3, 4, 5, 6]

Q11. How do you partition a list into even and odd numbers?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8);

Map<Boolean, List<Integer>> partitioned = [Link]()

.collect([Link](n -> n % 2 == 0));

[Link]("Even: " + [Link](true)); // [2, 4, 6, 8]

[Link]("Odd: " + [Link](false)); // [1, 3, 5, 7]

Q12. How do you find the sum of digits of a number using streams?

java

int number = 12345;


int sumOfDigits = [Link](number)

.chars()

.map(c -> c - '0')

.sum();

[Link](sumOfDigits); // 15

Q13. How do you reverse each word in a sentence using streams?

java

String sentence = "Java is awesome";

String result = [Link]([Link](" "))

.map(word -> new StringBuilder(word).reverse().toString())

.collect([Link](" "));

[Link](result); // avaJ si emosewa

Q14. How do you find duplicate characters in a string using streams?

java

String str = "programming";

Set<Character> duplicates = [Link]()

.mapToObj(c -> (char) c)

.collect([Link](c -> c, [Link]()))

.entrySet().stream()

.filter(e -> [Link]() > 1)

.map([Link]::getKey)

.collect([Link]());
[Link](duplicates); // [r, g, m]

Q15. How do you check if two strings are anagrams using streams?

java

String s1 = "listen";

String s2 = "silent";

boolean isAnagram = [Link]().sorted().boxed()

.collect([Link]())

.equals(

[Link]().sorted().boxed()

.collect([Link]())

);

[Link](isAnagram); // true

Q16. How do you find the top N most frequent words in a string?

java

String text = "java stream java lambda stream java";

List<String> top2 = [Link]([Link](" "))

.collect([Link](w -> w, [Link]()))

.entrySet().stream()

.sorted([Link].<String, Long>comparingByValue().reversed())

.limit(2)

.map([Link]::getKey)

.collect([Link]());
[Link](top2); // [java, stream]

Q17. How do you filter a Map by value using streams?

java

Map<String, Integer> scores = new HashMap<>();

[Link]("Alice", 90);

[Link]("Bob", 55);

[Link]("Charlie", 80);

Map<String, Integer> passed = [Link]().stream()

.filter(e -> [Link]() >= 60)

.collect([Link]([Link]::getKey, [Link]::getValue));

[Link](passed); // {Alice=90, Charlie=80}

Q18. How do you sort a Map by value in descending order?

java

Map<String, Integer> scores = new HashMap<>();

[Link]("Alice", 90);

[Link]("Bob", 55);

[Link]("Charlie", 80);

Map<String, Integer> sorted = [Link]().stream()

.sorted([Link].<String, Integer>comparingByValue().reversed())

.collect([Link](

[Link]::getKey,

[Link]::getValue
));

// Correct way

LinkedHashMap<String, Integer> sortedMap = [Link]().stream()

.sorted([Link].<String, Integer>comparingByValue().reversed())

.collect([Link](

[Link]::getKey,

[Link]::getValue,

(e1, e2) -> e1,

LinkedHashMap::new

));

[Link](sortedMap); // {Alice=90, Charlie=80, Bob=55}

Q19. How do you merge two maps and handle duplicate keys?

java

Map<String, Integer> map1 = new HashMap<>();

[Link]("Alice", 90);

[Link]("Bob", 80);

Map<String, Integer> map2 = new HashMap<>();

[Link]("Bob", 95); // duplicate key

[Link]("Charlie", 85);

Map<String, Integer> merged = new HashMap<>(map1);

[Link]((k, v) -> [Link](k, v, Integer::max)); // keep max on duplicate

[Link](merged); // {Alice=90, Bob=95, Charlie=85}


Q20. How do you find all prime numbers up to N using streams?

java

int N = 50;

List<Integer> primes = [Link](2, N)

.filter(n -> [Link](2, (int) [Link](n))

.allMatch(i -> n % i != 0))

.boxed()

.collect([Link]());

[Link](primes);

// [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Q21. How do you generate Fibonacci series using [Link]?

java

List<Long> fibonacci = [Link](new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})

.limit(10)

.map(f -> f[0])

.collect([Link]());

[Link](fibonacci); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Q22. How do you implement pagination using streams?

java

List<Integer> data = [Link](1, 100)

.boxed()

.collect([Link]());
int pageNumber = 3;

int pageSize = 10;

List<Integer> page = [Link]()

.skip((long)(pageNumber - 1) * pageSize)

.limit(pageSize)

.collect([Link]());

[Link](page); // [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

Q23. How do you use Optional to avoid NullPointerException?

java

// BAD - throws NullPointerException

String name = null;

[Link]([Link]()); // NPE

// GOOD - using Optional

String result = [Link](name)

.map(String::toUpperCase)

.orElse("DEFAULT");

[Link](result); // DEFAULT

Q24. How do you chain multiple Predicates in Java 8?

java

Predicate<Integer> isEven = n -> n % 2 == 0;

Predicate<Integer> isPositive = n -> n > 0;


Predicate<Integer> isLt100 = n -> n < 100;

List<Integer> numbers = [Link](-4, 0, 6, 50, 102, 77, 88);

List<Integer> result = [Link]()

.filter([Link](isPositive).and(isLt100))

.collect([Link]());

[Link](result); // [6, 50, 88]

Q25. How do you use [Link] and [Link]?

java

Function<Integer, Integer> doubleIt = x -> x * 2;

Function<Integer, Integer> addTen = x -> x + 10;

// andThen → doubleIt THEN addTen

[Link]([Link](addTen).apply(5)); // (5*2)+10 = 20

// compose → addTen THEN doubleIt

[Link]([Link](addTen).apply(5)); // (5+10)*2 = 30

Q26. How do you collect statistics (min, max, avg, sum, count) in one pass?

java

List<Integer> numbers = [Link](10, 20, 30, 40, 50);

IntSummaryStatistics stats = [Link]()

.collect([Link](Integer::intValue));
[Link]("Count: " + [Link]()); // 5

[Link]("Sum: " + [Link]()); // 150

[Link]("Min: " + [Link]()); // 10

[Link]("Max: " + [Link]()); // 50

[Link]("Avg: " + [Link]()); // 30.0

Q27. How do you find common elements between two lists?

java

List<Integer> list1 = [Link](1, 2, 3, 4, 5);

List<Integer> list2 = [Link](3, 4, 5, 6, 7);

List<Integer> common = [Link]()

.filter(new HashSet<>(list2)::contains) // HashSet for O(1) lookup

.collect([Link]());

[Link](common); // [3, 4, 5]

Q28. How do you find elements present in list1 but not in list2?

java

List<Integer> list1 = [Link](1, 2, 3, 4, 5);

List<Integer> list2 = [Link](3, 4, 5);

Set<Integer> set2 = new HashSet<>(list2);

List<Integer> diff = [Link]()

.filter(n -> ![Link](n))

.collect([Link]());
[Link](diff); // [1, 2]

Q29. How do you group employees by department and get highest paid in each?

java

Map<String, Optional<Employee>> topEarnerByDept = [Link]()

.collect([Link](

Employee::getDepartment,

[Link]([Link](Employee::getSalary))

));

[Link]((dept, emp) ->

[Link](dept + " -> " + [Link]().getName()));

Q30. How do you group anagrams together using streams?

java

List<String> words = [Link]("eat", "tea", "tan", "ate", "nat", "bat");

Map<String, List<String>> anagramGroups = [Link]()

.collect([Link](w -> {

char[] chars = [Link]();

[Link](chars);

return new String(chars);

}));

[Link](anagramGroups);

// {aet=[eat, tea, ate], ant=[tan, nat], abt=[bat]}

Q31. How do you count word frequency in a sentence using streams?


java

String sentence = "java is great and java is fast";

Map<String, Long> frequency = [Link]([Link](" "))

.collect([Link](w -> w, [Link]()));

[Link](frequency);

// {java=2, is=2, great=1, and=1, fast=1}

Q32. How do you remove null values from a list using streams?

java

List<String> list = [Link]("Alice", null, "Bob", null, "Charlie");

List<String> noNulls = [Link]()

.filter(Objects::nonNull)

.collect([Link]());

[Link](noNulls); // [Alice, Bob, Charlie]

Q33. How do you use [Link] with duplicate key handling?

java

List<String> words = [Link]("apple", "avocado", "banana");

// Without handling → throws IllegalStateException on duplicate key

// With merge function → keep longest word on duplicate first letter

Map<Character, String> map = [Link]()

.collect([Link](

w -> [Link](0),
w -> w,

(existing, replacement) ->

[Link]() >= [Link]() ? existing : replacement

));

[Link](map); // {a=avocado, b=banana}

Q34. How do you use peek() for debugging a stream pipeline?

java

List<Integer> result = [Link](1, 2, 3, 4, 5, 6).stream()

.peek(n -> [Link]("Before filter : " + n))

.filter(n -> n % 2 == 0)

.peek(n -> [Link]("After filter : " + n))

.map(n -> n * n)

.peek(n -> [Link]("After map : " + n))

.collect([Link]());

[Link](result); // [4, 16, 36]

Q35. How do you use Comparator chaining to sort by multiple fields?

java

// Sort employees: first by department (asc), then by salary (desc)

List<Employee> sorted = [Link]()

.sorted([Link](Employee::getDepartment)

.thenComparing([Link](Employee::getSalary)

.reversed()))

.collect([Link]());
[Link](e ->

[Link]([Link]() + " | " + [Link]() + " | " + [Link]()));

Q36. How do you use flatMap to get all unique skills from a list of employees?

java

// Each Employee has List<String> skills

List<String> allUniqueSkills = [Link]()

.flatMap(e -> [Link]().stream())

.distinct()

.sorted()

.collect([Link]());

[Link](allUniqueSkills);

Q37. How do you use reduce() to concatenate a list of strings?

java

List<String> words = [Link]("Java", "8", "Streams", "are", "powerful");

String sentence = [Link]()

.reduce("", (a, b) -> [Link]() ? b : a + " " + b);

[Link](sentence); // Java 8 Streams are powerful

Q38. How do you use IntStream to calculate factorial?

java

int n = 5;

long factorial = [Link](1, n)


.reduce(1L, Long::multiply);

[Link](factorial); // 120

Q39. How do you use [Link] to generate a sequence?

java

// First 10 multiples of 3

List<Integer> multiples = [Link](3, n -> n + 3)

.limit(10)

.collect([Link]());

[Link](multiples); // [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

Q40. How do you use parallel streams and when should you avoid them?

java

List<Integer> numbers = [Link](1, 1_000_000)

.boxed()

.collect([Link]());

// GOOD use case - large data, stateless, order doesn't matter

long sum = [Link]()

.mapToLong(Integer::longValue)

.sum();

[Link](sum); // 500000500000

// AVOID parallel streams when:

// 1. Small data sets


// 2. Operations have side effects (shared mutable state)

// 3. Order of result matters (use forEachOrdered if needed)

// 4. Blocking I/O operations inside stream

Employee class for reference:

java

class Employee {

private String name;

private double salary;

private String department;

private List<String> skills;

public Employee(String name, double salary, String department) {

[Link] = name;

[Link] = salary;

[Link] = department;

public String getName() { return name; }

public double getSalary() { return salary; }

public String getDepartment() { return department; }

public List<String> getSkills() { return skills; }



You said: Continue

Continue

17:10




Claude responded: Continuing from Q41:

Continuing from Q41:

Q41. How do you find the longest string in a list?

java

List<String> words = [Link]("java", "streams", "are", "powerful", "and", "fast");

String longest = [Link]()

.max([Link](String::length))

.orElseThrow(() -> new RuntimeException("List is empty"));

[Link](longest); // powerful

Q42. How do you find all strings longer than a given length?

java

List<String> words = [Link]("java", "streams", "are", "powerful", "go");

int minLength = 4;

List<String> result = [Link]()

.filter(w -> [Link]() > minLength)

.collect([Link]());

[Link](result); // [streams, powerful]

Q43. How do you convert a list of strings to a single comma-separated string?


java

List<String> names = [Link]("Alice", "Bob", "Charlie", "David");

String result = [Link]()

.collect([Link](", "));

[Link](result); // Alice, Bob, Charlie, David

// With prefix and suffix

String result2 = [Link]()

.collect([Link](", ", "[", "]"));

[Link](result2); // [Alice, Bob, Charlie, David]

Q44. How do you split a comma-separated string into a sorted list?

java

String csv = "banana,apple,cherry,mango,kiwi";

List<String> sorted = [Link]([Link](","))

.map(String::trim)

.sorted()

.collect([Link]());

[Link](sorted); // [apple, banana, cherry, kiwi, mango]

Q45. How do you count vowels in a string using streams?

java

String str = "Hello World Java";


long vowelCount = [Link]().chars()

.filter(c -> "aeiou".indexOf(c) != -1)

.count();

[Link](vowelCount); // 5

Q46. How do you remove vowels from a string using streams?

java

String str = "Hello World Java";

String result = [Link]()

.filter(c -> "aeiouAEIOU".indexOf(c) == -1)

.mapToObj(c -> [Link]((char) c))

.collect([Link]());

[Link](result); // Hll Wrld Jv

Q47. How do you check if a list is sorted using streams?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5);

boolean isSorted = [Link](0, [Link]() - 1)

.allMatch(i -> [Link](i) <= [Link](i + 1));

[Link](isSorted); // true

Q48. How do you find the sum of all salaries grouped by department?
java

Map<String, Double> totalSalaryByDept = [Link]()

.collect([Link](

Employee::getDepartment,

[Link](Employee::getSalary)

));

[Link]((dept, total) ->

[Link](dept + " -> " + total));

Q49. How do you get distinct elements from a list while preserving order?

java

List<Integer> numbers = [Link](5, 3, 1, 3, 5, 2, 1, 4);

List<Integer> distinct = [Link]()

.distinct() // preserves encounter order

.collect([Link]());

[Link](distinct); // [5, 3, 1, 2, 4]

Q50. How do you rotate a list by N positions using streams?

java

List<Integer> list = [Link](1, 2, 3, 4, 5);

int n = 2;

List<Integer> rotated = [Link](

[Link]().skip(n),

[Link]().limit(n)
).collect([Link]());

[Link](rotated); // [3, 4, 5, 1, 2]

Q51. How do you find numbers that appear exactly once in a list?

java

List<Integer> numbers = [Link](1, 2, 2, 3, 4, 4, 5);

List<Integer> unique = [Link]()

.collect([Link](n -> n, [Link]()))

.entrySet().stream()

.filter(e -> [Link]() == 1)

.map([Link]::getKey)

.collect([Link]());

[Link](unique); // [1, 3, 5]

Q52. How do you convert a list of integers to their squares?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5);

List<Integer> squares = [Link]()

.map(n -> n * n)

.collect([Link]());

[Link](squares); // [1, 4, 9, 16, 25]

Q53. How do you find the average of a list of doubles?


java

List<Double> values = [Link](10.5, 20.0, 30.5, 40.0, 50.5);

double average = [Link]()

.mapToDouble(Double::doubleValue)

.average()

.orElse(0.0);

[Link](average); // 30.3

Q54. How do you use Supplier to create objects lazily?

java

Supplier<List<String>> listSupplier = ArrayList::new;

List<String> list1 = [Link](); // new instance every time

List<String> list2 = [Link]();

[Link]("Java");

[Link]("Python");

[Link](list1); // [Java]

[Link](list2); // [Python] — different instances

Q55. How do you use Consumer and andThen to chain operations?

java

Consumer<String> print = [Link]::println;

Consumer<String> toUpper = s -> [Link]([Link]());


Consumer<String> combined = [Link](toUpper);

[Link]("hello");

// hello

// HELLO

Q56. How do you check if all, any, or none of the elements satisfy a condition?

java

List<Integer> numbers = [Link](2, 4, 6, 8, 10);

boolean allEven = [Link]().allMatch(n -> n % 2 == 0);

boolean anyAbove8 = [Link]().anyMatch(n -> n > 8);

boolean noneNeg = [Link]().noneMatch(n -> n < 0);

[Link]("All even: " + allEven); // true

[Link]("Any above 8: " + anyAbove8); // true

[Link]("None neg: " + noneNeg); // true

Q57. How do you use [Link] to build a list-valued map?

java

List<String> words = [Link]("apple", "banana", "avocado", "blueberry", "cherry");

Map<Character, List<String>> grouped = new HashMap<>();

[Link](w ->

[Link]([Link](0), k -> new ArrayList<>()).add(w)

);
[Link](grouped);

// {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}

Q58. How do you use [Link] to count frequencies?

java

String[] words = {"java", "python", "java", "go", "python", "java"};

Map<String, Integer> freq = new HashMap<>();

[Link](words)

.forEach(w -> [Link](w, 1, Integer::sum));

[Link](freq); // {java=3, python=2, go=1}

Q59. How do you use replaceAll and removeIf on collections?

java

List<String> names = new ArrayList<>(

[Link]("alice", "bob", "charlie", "dave")

);

// replaceAll - transform each element in-place

[Link](String::toUpperCase);

[Link](names); // [ALICE, BOB, CHARLIE, DAVE]

// removeIf - remove elements matching condition

[Link](n -> [Link]() > 4);

[Link](names); // [BOB, DAVE]


Q60. How do you implement a custom Comparator using Java 8?

java

List<String> words = [Link]("banana", "Apple", "cherry", "kiwi");

// Sort by length, then alphabetically (case-insensitive) on tie

List<String> sorted = [Link]()

.sorted([Link](String::length)

.thenComparing(String.CASE_INSENSITIVE_ORDER))

.collect([Link]());

[Link](sorted); // [kiwi, Apple, banana, cherry]

Q61. How do you find the nth largest element in a list?

java

List<Integer> numbers = [Link](10, 40, 30, 50, 20);

int n = 3; // 3rd largest

int nthLargest = [Link]()

.distinct()

.sorted([Link]())

.skip(n - 1)

.findFirst()

.orElseThrow(() -> new RuntimeException("Not enough elements"));

[Link](nthLargest); // 30

Q62. How do you merge two lists into a Map of key-value pairs?
java

List<String> keys = [Link]("a", "b", "c");

List<Integer> values = [Link](1, 2, 3);

Map<String, Integer> map = [Link](0, [Link]())

.boxed()

.collect([Link](keys::get, values::get));

[Link](map); // {a=1, b=2, c=3}

Q63. How do you find the sum of only positive numbers in a list?

java

List<Integer> numbers = [Link](-5, -3, 0, 2, 4, 6, -1, 8);

int sum = [Link]()

.filter(n -> n > 0)

.mapToInt(Integer::intValue)

.sum();

[Link](sum); // 20

Q64. How do you capitalize the first letter of each word in a sentence?

java

String sentence = "java streams are very powerful";

String result = [Link]([Link](" "))

.map(w -> [Link]([Link](0)) + [Link](1))

.collect([Link](" "));
[Link](result); // Java Streams Are Very Powerful

Q65. How do you find the character with maximum frequency in a string?

java

String str = "programming";

char maxFreqChar = [Link]()

.mapToObj(c -> (char) c)

.collect([Link](c -> c, [Link]()))

.entrySet().stream()

.max([Link]())

.map([Link]::getKey)

.orElseThrow();

[Link](maxFreqChar); // g

Q66. How do you use [Link], ifPresentOrElse?

java

Optional<String> opt = [Link]("Java 8");

// ifPresent

[Link](v -> [Link]("Value: " + v)); // Value: Java 8

// ifPresentOrElse (Java 9 but commonly asked)

Optional<String> empty = [Link]();

[Link](

v -> [Link]("Value: " + v),


() -> [Link]("No value present") // No value present

);

Q67. How do you convert Optional to a Stream?

java

Optional<String> opt = [Link]("hello");

// Use in stream pipeline — filters out empty optionals

List<Optional<String>> optionals = [Link](

[Link]("java"),

[Link](),

[Link]("streams")

);

List<String> result = [Link]()

.filter(Optional::isPresent)

.map(Optional::get)

.collect([Link]());

[Link](result); // [java, streams]

Q68. How do you use [Link] inside groupingBy?

java

// Group by department, collect only names (not full Employee objects)

Map<String, List<String>> namesByDept = [Link]()

.collect([Link](

Employee::getDepartment,

[Link](Employee::getName, [Link]())
));

[Link]((dept, names) ->

[Link](dept + " -> " + names));

Q69. How do you zip two lists together using streams?

java

List<String> names = [Link]("Alice", "Bob", "Charlie");

List<Integer> scores = [Link](90, 85, 92);

List<String> zipped = [Link](0, [Link]())

.mapToObj(i -> [Link](i) + " -> " + [Link](i))

.collect([Link]());

[Link](zipped);

// [Alice -> 90, Bob -> 85, Charlie -> 92]

Q70. How do you find all pairs of numbers that sum to a target?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);

int target = 7;

List<String> pairs = [Link]()

.flatMap(i -> [Link]()

.filter(j -> i < j && i + j == target)

.map(j -> "(" + i + ", " + j + ")")

.collect([Link]());
[Link](pairs); // [(1, 6), (2, 5), (3, 4)]

Q71. How do you use [Link]?

java

// Collect to list then make it unmodifiable

List<String> unmodifiable = [Link]("java", "python", "go").stream()

.collect([Link](

[Link](),

Collections::unmodifiableList

));

[Link](unmodifiable); // [java, python, go]

// [Link]("ruby"); // throws UnsupportedOperationException

Q72. How do you find the intersection and union of two sets?

java

Set<Integer> set1 = new HashSet<>([Link](1, 2, 3, 4, 5));

Set<Integer> set2 = new HashSet<>([Link](3, 4, 5, 6, 7));

// Intersection

Set<Integer> intersection = [Link]()

.filter(set2::contains)

.collect([Link]());

// Union

Set<Integer> union = [Link]([Link](), [Link]())

.collect([Link]());
[Link]("Intersection: " + intersection); // [3, 4, 5]

[Link]("Union: " + union); // [1, 2, 3, 4, 5, 6, 7]

Q73. How do you use method references for constructor, static, and instance methods?

java

// Static method reference

Function<String, Integer> parseInt = Integer::parseInt;

[Link]([Link]("123")); // 123

// Instance method reference on type

Function<String, String> toUpper = String::toUpperCase;

[Link]([Link]("hello")); // HELLO

// Instance method reference on object

String prefix = "Hello ";

Function<String, String> greet = prefix::concat;

[Link]([Link]("Alice")); // Hello Alice

// Constructor reference

Supplier<ArrayList<String>> listFactory = ArrayList::new;

ArrayList<String> list = [Link]();

Q74. How do you use [Link] vs [Link]?

java

// [Link] - works with individual elements or array (but gives Stream<int[]> for
primitives)

Stream<String> s1 = [Link]("a", "b", "c");


// [Link] - preferred for arrays, handles primitives correctly

int[] arr = {1, 2, 3};

IntStream intStream = [Link](arr); // correctly returns IntStream

int sum = [Link]();

[Link](sum); // 6

// [Link] on int[] gives Stream<int[]>, NOT IntStream

Stream<int[]> wrong = [Link](arr); // wraps whole array as single element

Q75. How do you lazily evaluate a stream pipeline?

java

// Streams are lazy - intermediate ops don't execute until terminal op is called

List<Integer> numbers = [Link](1, 2, 3, 4, 5);

Stream<Integer> stream = [Link]()

.filter(n -> {

[Link]("filter: " + n);

return n % 2 == 0;

})

.map(n -> {

[Link]("map: " + n);

return n * 10;

});

[Link]("Stream created, nothing executed yet");

// Terminal operation triggers execution


List<Integer> result = [Link]([Link]());

[Link](result); // [20, 40]

Q76. How do you handle checked exceptions inside a stream?

java

// Problem - stream lambdas don't allow checked exceptions

// Solution - wrap in a helper method

static <T, R> Function<T, R> wrap(CheckedFunction<T, R> fn) {

return t -> {

try {

return [Link](t);

} catch (Exception e) {

throw new RuntimeException(e);

};

@FunctionalInterface

interface CheckedFunction<T, R> {

R apply(T t) throws Exception;

// Usage

List<String> paths = [Link]("[Link]", "[Link]");

List<String> contents = [Link]()

.map(wrap(path -> new String([Link]([Link](path)))))


.collect([Link]());

Q77. How do you find the product of all elements using reduce?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5);

int product = [Link]()

.reduce(1, (a, b) -> a * b);

[Link](product); // 120

// Using method reference

int product2 = [Link]()

.reduce(1, Math::multiplyExact);

[Link](product2); // 120

Q78. How do you print a multiplication table using streams?

java

int n = 5;

[Link](1, 10)

.forEach(i -> [Link](n + " x " + i + " = " + (n * i)));

// 5 x 1 = 5

// 5 x 2 = 10 ... and so on

Q79. How do you use [Link] iteration with streams?


java

Map<String, List<String>> deptEmployees = new HashMap<>();

[Link]("IT", [Link]("Alice", "Bob"));

[Link]("HR", [Link]("Charlie"));

[Link]("Finance", [Link]("David", "Eve", "Frank"));

// Find department with most employees

String largestDept = [Link]().stream()

.max([Link](e -> [Link]().size()))

.map([Link]::getKey)

.orElse("None");

[Link](largestDept); // Finance

Q80. How do you create an immutable list, set, and map in Java 8?

java

// Immutable List

List<String> list = [Link](

[Link]("a", "b", "c")

);

// Immutable Set

Set<String> set = [Link](

new HashSet<>([Link]("x", "y", "z"))

);

// Immutable Map

Map<String, Integer> map = [Link](


[Link](

new [Link]<>("one", 1),

new [Link]<>("two", 2)

).collect([Link]([Link]::getKey, [Link]::getValue))

);

[Link](list); // [a, b, c]

[Link](set); // [x, y, z]

[Link](map); // { two=2}

Employee class for all examples:

java

class Employee {

private int id;

private String name;

private double salary;

private String department;

private String gender;

private List<String> skills;

public Employee(String name, double salary, String department) {

[Link] = name;

[Link] = salary;

[Link] = department;

public int getId() { return id; }

public String getName() { return name; }


public double getSalary() { return salary; }

public String getDepartment() { return department; }

public String getGender() { return gender; }

public List<String> getSkills() { return skills; }



You said: Continue

Continue

17:12





Claude responded: Continuing from Q81:

Continuing from Q81:

Q81. How do you find all employees whose name starts with a specific letter?

java

List<Employee> employees = [Link](

new Employee("Alice", 60000, "IT"),

new Employee("Bob", 45000, "HR"),

new Employee("Anna", 75000, "IT"),

new Employee("Charlie", 55000, "Finance")

);

char letter = 'A';

List<String> result = [Link]()

.map(Employee::getName)
.filter(name -> [Link]([Link](letter)))

.sorted()

.collect([Link]());

[Link](result); // [Alice, Anna]

Q82. How do you find the total number of characters in all strings in a list?

java

List<String> words = [Link]("java", "streams", "are", "powerful");

int totalChars = [Link]()

.mapToInt(String::length)

.sum();

[Link](totalChars); // 22

Q83. How do you find strings that contain a specific substring?

java

List<String> words = [Link]("java", "javascript", "python", "javafx", "ruby");

String keyword = "java";

List<String> result = [Link]()

.filter(w -> [Link](keyword))

.collect([Link]());

[Link](result); // [java, javascript, javafx]


Q84. How do you convert a list of strings to a list of their lengths?

java

List<String> words = [Link]("apple", "banana", "kiwi", "mango");

List<Integer> lengths = [Link]()

.map(String::length)

.collect([Link]());

[Link](lengths); // [5, 6, 4, 5]

Q85. How do you find the minimum and maximum salary in each department?

java

Map<String, IntSummaryStatistics> statsByDept = [Link]()

.collect([Link](

Employee::getDepartment,

[Link](e -> (int) [Link]())

));

[Link]((dept, stats) ->

[Link](dept

+ " | Min: " + [Link]()

+ " | Max: " + [Link]()

+ " | Avg: " + [Link]()));

Q86. How do you check if two lists are equal using streams?

java

List<Integer> list1 = [Link](1, 2, 3, 4, 5);

List<Integer> list2 = [Link](1, 2, 3, 4, 5);


List<Integer> list3 = [Link](5, 4, 3, 2, 1);

// Exact order match

boolean isEqual = [Link](list2);

[Link](isEqual); // true

// Same elements regardless of order

boolean sameElements = new HashSet<>(list1).equals(new HashSet<>(list3));

[Link](sameElements); // true

Q87. How do you use [Link] to reverse a map?

java

Map<String, Integer> original = new HashMap<>();

[Link]("one", 1);

[Link]("two", 2);

[Link]("three", 3);

Map<Integer, String> reversed = [Link]().stream()

.collect([Link](

[Link]::getValue,

[Link]::getKey

));

[Link](reversed); // {1=one, 2=two, 3=three}

Q88. How do you find the first element matching a condition?

java

List<Integer> numbers = [Link](10, 25, 33, 42, 57, 68);


// findFirst - returns first match in encounter order

Optional<Integer> first = [Link]()

.filter(n -> n > 30)

.findFirst();

[Link]([Link]()); // 33

// findAny - returns any match (better for parallel streams)

Optional<Integer> any = [Link]()

.filter(n -> n > 30)

.findAny();

[Link]([Link]()); // could be any of 33, 42, 57, 68

Q89. How do you create a frequency map from an array?

java

int[] arr = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};

Map<Integer, Long> freqMap = [Link](arr)

.boxed()

.collect([Link](n -> n, [Link]()));

[Link](freqMap); // {1=1, 2=2, 3=3, 4=4}

Q90. How do you convert a map of lists into a flat list?

java

Map<String, List<String>> deptSkills = new HashMap<>();


[Link]("IT", [Link]("Java", "Python", "AWS"));

[Link]("Finance", [Link]("Excel", "SQL"));

[Link]("HR", [Link]("Communication", "Excel"));

List<String> allSkills = [Link]().stream()

.flatMap(Collection::stream)

.distinct()

.sorted()

.collect([Link]());

[Link](allSkills);

// [AWS, Communication, Excel, Java, Python, SQL]

Q91. How do you use reduce to find the longest string?

java

List<String> words = [Link]("java", "streams", "are", "very", "powerful");

String longest = [Link]()

.reduce("", (a, b) -> [Link]() >= [Link]() ? a : b);

[Link](longest); // powerful

Q92. How do you get the last element of a stream?

java

List<Integer> numbers = [Link](10, 20, 30, 40, 50);

// Method 1 - reduce

Optional<Integer> last = [Link]()


.reduce((first, second) -> second);

[Link]([Link]()); // 50

// Method 2 - skip

int last2 = [Link]()

.skip([Link]() - 1)

.findFirst()

.get();

[Link](last2); // 50

Q93. How do you find numbers within a specific range in a list?

java

List<Integer> numbers = [Link](5, 12, 3, 45, 28, 67, 19, 8);

int min = 10;

int max = 50;

List<Integer> inRange = [Link]()

.filter(n -> n >= min && n <= max)

.sorted()

.collect([Link]());

[Link](inRange); // [12, 19, 28, 45]

Q94. How do you use BiFunction and Function together?

java
BiFunction<String, Integer, String> repeat = (s, n) -> [Link](n);

Function<String, String> toUpper = String::toUpperCase;

// andThen chains a Function after BiFunction

BiFunction<String, Integer, String> combined = [Link](toUpper);

[Link]([Link]("java ", 3));

// JAVA JAVA JAVA

Q95. How do you convert a list of objects to a CSV string?

java

List<Employee> employees = [Link](

new Employee("Alice", 60000, "IT"),

new Employee("Bob", 45000, "HR"),

new Employee("Charlie", 75000, "Finance")

);

String csv = [Link]()

.map(e -> [Link]() + "," + [Link]() + "," + [Link]())

.collect([Link]("\n"));

[Link](csv);

// Alice,60000.0,IT

// Bob,45000.0,HR

// Charlie,75000.0,Finance

Q96. How do you transpose a matrix using streams?

java
int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int rows = [Link];

int cols = matrix[0].length;

int[][] transposed = [Link](0, cols)

.mapToObj(col -> [Link](0, rows)

.map(row -> matrix[row][col])

.toArray())

.toArray(int[][]::new);

// Print transposed

[Link](transposed)

.forEach(row -> [Link]([Link](row)));

// [1, 4, 7]

// [2, 5, 8]

// [3, 6, 9]

Q97. How do you use [Link] to build an SQL IN clause?

java

List<Integer> ids = [Link](1, 2, 3, 4, 5);

String inClause = [Link]()

.map(String::valueOf)
.collect([Link](", ", "WHERE id IN (", ")"));

[Link](inClause);

// WHERE id IN (1, 2, 3, 4, 5)

Q98. How do you use [Link] with a predicate? (Java 9 style in Java 8)

java

// Java 9: [Link](seed, predicate, next)

// Java 8 equivalent using limit + filter

List<Integer> result = [Link](1, n -> n + 1)

.limit(1000) // safety cap

.filter(n -> n % 3 == 0) // divisible by 3

.takeWhile(n -> n <= 30) // stop at 30 (Java 9)

.collect([Link]());

// Pure Java 8 way

List<Integer> result8 = [Link](3, n -> n + 3)

.limit(10)

.collect([Link]());

[Link](result8); // [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

Q99. How do you batch/chunk a list into sublists of size N?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int batchSize = 3;
List<List<Integer>> batches = [Link](0, ([Link]() + batchSize - 1) / batchSize)

.mapToObj(i -> [Link](

i * batchSize,

[Link]((i + 1) * batchSize, [Link]())

))

.collect([Link]());

[Link](batches);

// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Q100. How do you build a pipeline to find the highest paid employee per department
whose salary is above average?

java

// Step 1 - find overall average salary

double avgSalary = [Link]()

.mapToDouble(Employee::getSalary)

.average()

.orElse(0);

// Step 2 - filter above average, group by dept, get highest paid in each

Map<String, Optional<Employee>> result = [Link]()

.filter(e -> [Link]() > avgSalary)

.collect([Link](

Employee::getDepartment,

[Link]([Link](Employee::getSalary))

));

[Link]((dept, emp) ->


[Link](e ->

[Link](dept + " -> " + [Link]() + " : " + [Link]())

));

Q101. How do you detect a cycle in a stream using stateful operations?

java

// Track seen elements using external Set in stateful filter

List<Integer> numbers = [Link](1, 2, 3, 2, 4, 3, 5);

Set<Integer> seen = new HashSet<>();

List<Integer> firstOccurrences = [Link]()

.filter(seen::add) // add returns false if already present

.collect([Link]());

[Link](firstOccurrences); // [1, 2, 3, 4, 5]

Set<Integer> duplicates = [Link]()

.filter(n -> ![Link](n))

.collect([Link]());

// Reset seen for duplicate detection

[Link]();

Set<Integer> dups = [Link]()

.filter(n -> ![Link](n))

.collect([Link]());

[Link](dups); // [2, 3]
Q102. How do you perform a multi-level sort on a list of employees?

java

List<Employee> employees = [Link](

new Employee("Alice", 90000, "IT"),

new Employee("Bob", 70000, "IT"),

new Employee("Charlie", 85000, "HR"),

new Employee("David", 70000, "HR"),

new Employee("Eve", 95000, "Finance")

);

// Sort by department ASC → salary DESC → name ASC

List<Employee> sorted = [Link]()

.sorted(

[Link](Employee::getDepartment)

.thenComparing([Link](Employee::getSalary).reversed())

.thenComparing(Employee::getName)

.collect([Link]());

[Link](e ->

[Link]([Link]()

+ " | " + [Link]()

+ " | " + [Link]()));

// Finance | Eve | 95000.0

// HR | Charlie | 85000.0

// HR | David | 70000.0
// IT | Alice | 90000.0

// IT | Bob | 70000.0

Q103. What is the difference between map() and flatMap()?

java

List<String> words = [Link]("Hello", "World");

// map() - one-to-one, wraps each element

List<String[]> mapped = [Link]()

.map(w -> [Link](""))

.collect([Link]());

// Result: [[H,e,l,l,o], [W,o,r,l,d]] — list of arrays

// flatMap() - one-to-many, flattens result

List<String> flatMapped = [Link]()

.flatMap(w -> [Link]([Link]("")))

.distinct()

.collect([Link]());

// Result: [H, e, l, o, W, r, d] — single flat list

[Link](flatMapped);

Q104. What is the difference between findFirst() and findAny()?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5);

// findFirst - always returns first element in encounter order

// safe and deterministic for sequential streams


Optional<Integer> first = [Link]()

.filter(n -> n > 2)

.findFirst();

[Link]([Link]()); // always 3

// findAny - may return any element

// better for parallel streams (no ordering overhead)

Optional<Integer> any = [Link]()

.filter(n -> n > 2)

.findAny();

[Link]([Link]()); // could be 3, 4, or 5

Q105. What is the difference between intermediate and terminal operations?

java

List<Integer> numbers = [Link](1, 2, 3, 4, 5);

// INTERMEDIATE - lazy, return a Stream, don't execute until terminal

// filter, map, flatMap, sorted, distinct, peek, limit, skip

// TERMINAL - eager, trigger execution, return result or void

// collect, forEach, count, reduce, min, max, findFirst, findAny,

// allMatch, anyMatch, noneMatch, toArray, sum, average

// Example showing laziness

long count = [Link]()

.filter(n -> n % 2 == 0) // intermediate - lazy


.map(n -> n * 10) // intermediate - lazy

.count(); // terminal - triggers execution

[Link](count); // 2

Complete Employee class for all examples:

java

import [Link];

class Employee {

private int id;

private String name;

private double salary;

private String department;

private String gender;

private List<String> skills;

public Employee(String name, double salary, String department) {

[Link] = name;

[Link] = salary;

[Link] = department;

public int getId() { return id; }

public String getName() { return name; }

public double getSalary() { return salary; }

public String getDepartment() { return department; }

public String getGender() { return gender; }


public List<String> getSkills() { return skills; }

public void setId(int id) { [Link] = id; }

public void setGender(String gender) { [Link] = gender; }

public void setSkills(List<String> skills) { [Link] = skills; }

All required imports:

java

import [Link].*;

import [Link].*;

import [Link].*;

import [Link];

import [Link].*;

import [Link];

You might also like