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.

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