Java Stream Examples


### Problem #1: Given an integer array sorted in increasing order, return an array of the squares of each number sorted in increasing order.
### Solution:
```
    public static int[] sortedSquaresArray(int[] numbers) {
        return Arrays.stream(numbers).boxed()
                .map(val -> val * val)
                .sorted()
                .mapToInt(value -> value.intValue())
                .toArray();
    }

```

If you want to return the squares of each number sorted in descending order then you can use *.sorted(Collections.reverseOrder())*


### Problem #2: Given ArrayList of Employee (name, age) object. Print the names of employees having age greater than 20 saperated with comma. 
### Solution:
```
	String str = employeeList.stream()
                        .filter(e -> e.age >20)
                        .map(e -> e.name)
                        .collect(Collectors.joining(","));

    System.out.println(str);
```

### Problem#3: Create a reverse map in Java	, which means change the key as value and value as key.
### Solution:
```
 	sourceMap.forEach((key,value) -> inverseMap.put(value,key))
```
This is equivalent to:

```
 		for (Map.Entry entry : sourceMap.entrySet()){
            inverseMap.put(entry.getValue(), entry.getKey());
        }
```

### Problem#4: Given a List of Integer. Find out sum of top 3 elements in the given list.
### Solution:

```
	 List intList = new ArrayList<>();
      
      intList.add(34);
      intList.add(45);
      intList.add(50);
      intList.add(300);
      
     int topElementSum = intList.stream().sorted(Comparator.reverseOrder())
              .limit(3)
              .mapToInt(Integer::intValue)
              .sum();
     System.out.println(topElementSum);
```
We create a stream of Integer objects via *Collection.stream()* and then perform *Stream.sorted()* to sort the stream in descending order followed by *Stream.limit()* to get first 3 element.
Then convert stream to IntStream using *Stream.mapToInt()* to get sum() of elements.

### Problem#5:Use stream API to filter out all even numbers from a list of integers?
### Solution:

```
	 List numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
      
     List evenNumbers = intList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());

```

### Problem#6:What is difference between map and flatMap in Stream API?
### Solution: 
It is one of the most common question asked during interview.
#### Map:
map is an intermediate operation used to transforms each element of stream into another object, maintaining the *one-to-one* relationship.

```
Stream.of("apple", "banana", "carrot").map(e -> e.length());
-- output will be - [5, 6, 6].
```
#### FlatMap:
FlatMap is an intermediate operation used when one element can result in multiple elements. It flaten the structure into one stream.

Example: 
The list before flattening:[ [8, 1, 6], [10, 11, 12], [13, 14, 15] ]
After Flattening: [ 8, 1, 6, 10, 11, 12, 12, 14, 15 ] 

```
  List> listOfStringList = Arrays.asList(
            Arrays.asList("Hello", "how"),
            Arrays.asList("are", "you"),
            Arrays.asList("welcome", "to"),
            Arrays.asList("Java", "Stream programming")
        );

  listOfStringList.stream()
                   .flatMap(list -> list.stream())
                   .forEach(System.out::println);
                   
Output:
Hello
how
are
you
welcome
to
Java
Stream programming
```

### Problem#7:What is the use of reduce method in stream?
### Solution: 
reduce operation performs a reduction on the elements of the stream, using a binary operation to combine them. 

Example:
```
Optional sum = Stream.of(1, 2, 3, 4).reduce(Integer::sum);

```
Here the stream of numbers is reduce to single element which is sum of all numbers in stream.

Comments

Popular posts from this blog

Creating simple Maven multi module project in Java

Tricky Java Questions

How to update existing CCDT file (AMQCLCHL.TAB) for successful MQueue connection