Showing posts with label Stream Api In Java 8. Show all posts
Showing posts with label Stream Api In Java 8. Show all posts

Wednesday, April 9, 2025

Sort Int Array In Descending Order Using Java 8

 Sort Int Array In Descending Order Using Java 8

package com.demo.example;

import java.util.Arrays;
import java.util.Comparator;

public class SortReverseOrder {

	public static void main(String[] args) {

		/* Sort int array in descending/reverse order using java 8"
		 * 
		 */
		int[] intArray = { 1, 2, 3, 7, 9, 10, 12, 18 };
		System.out.println("####### Given Array : " + Arrays.toString(intArray));
		int[] reverseOrderArr = Arrays.stream(intArray).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i)
				.toArray();
		System.out.println("####### ReverseOrder Array : " + Arrays.toString(reverseOrderArr));

		
		/* nth highest element in array using java 8
		 * 
		 */
		System.out.println("####### nth highest element in array #######");
		int n = 3; // Find the 3rd highest element
		int nthHighestElement = Arrays.stream(intArray).boxed().sorted(Comparator.reverseOrder()).skip(n - 1)
				.findFirst().orElse(-1);
		System.out.println("nth highest element is : " + nthHighestElement);

		
		/* Sort int array in Ascending order using java 8
		 * 
		 */
		int[] sortedOrderArr = Arrays.stream(intArray).boxed().sorted().mapToInt(i -> i).toArray();
		System.out.println("####### sortedOrder Array : " + Arrays.toString(sortedOrderArr));
		
		/* nth smallest element in array using java 8
		 * 
		 */
		System.out.println("####### nth smallest element in array #######");
		int ns = 3; // Find the 3rd smallest element
		int nthHighestSmallest = Arrays.stream(intArray).boxed().sorted().skip(ns - 1).findFirst().orElse(-1);
		System.out.println("nth smallest element is : " + nthHighestSmallest);
	}
}
####### Given Array : [1, 2, 3, 7, 9, 10, 12, 18]
####### ReverseOrder Array : [18, 12, 10, 9, 7, 3, 2, 1]

####### nth highest element in array #######
nth highest element is : 10

####### sortedOrder Array : [1, 2, 3, 7, 9, 10, 12, 18]
####### nth smallest element in array #######
nth smallest element is : 3

Saturday, July 20, 2019

Stream Operation On Object In Java

In This example i am going to do some different stream operation on Employee Class Object.

package com.shubh.stream.api;

import java.util.Date;

public class Employee {

 private int id;
 private String name;
 private int age;
 private String email;
 private Date dateOfJoining;
 public String department;
 public int salary;

 public Employee(int id, String name, int age, String email, Date dateOfJoining, int salary) {
  this.id = id;
  this.name = name;
  this.age = age;
  this.email = email;
  this.dateOfJoining = dateOfJoining;
  this.salary = salary;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public Date getDateOfJoining() {
  return dateOfJoining;
 }

 public void setDateOfJoining(Date dateOfJoining) {
  this.dateOfJoining = dateOfJoining;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getDepartment() {
  return department;
 }

 public void setDepartment(String department) {
  this.department = department;
 }

 public int getSalary() {
  return salary;
 }

 public void setSalary(int salary) {
  this.salary = salary;
 }

 @Override
 public String toString() {
  return "Employee{ id " + id + ", name='" + name + '\'' + ", age=" + age + ", email " + email + ", DOJ "
    + dateOfJoining + ", Salary " + salary + "}";
 }
}
Now Create different stream operations on Employee Class Objects like sorting by name, age, DateOfJoining etc.

package com.shubh.stream.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collectors;

public class StreamApplication {

 public static void main(String[] args) throws ParseException {

  // Employee(int id, String name, int age,String email, Date dateOfJoining);
  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
  List Employees = Arrays.asList(
    new Employee(1, "C", 30, "C@xyz.com", formatter.parse("01/08/1999"), 15000),
    new Employee(2, "A", 40, "A@xyz.com", formatter.parse("01/08/1955"), 5000),
    new Employee(3, "A", 10, "A1@xyz.com", formatter.parse("01/08/1979"), 3000),
    new Employee(3, "A", 10, "A2@xyz.com", formatter.parse("01/08/1978"), 2000),
    new Employee(4, "B", 20, "B@xyz.com", formatter.parse("01/08/1989"), 2000),
    new Employee(5, "E", 50, "E@xyz.com", formatter.parse("01/08/1985"), 10000));

  /*
   * List sortedList = Employees.stream() .sorted((o1, o2) -> o1.getAge() - o2.getAge()) .collect(Collectors.toList());
   */

  System.out.println("//Sort by Age.");
  List sortedByAge = Employees.stream().sorted(Comparator.comparingInt(Employee::getAge))
    .collect(Collectors.toList());
  sortedByAge.forEach(System.out::println);

  System.out.println("\n//Sort by Name.");

  /*
   * List sortedList = Employees.stream() .sorted((o1, o2) -> o1.getName().compareTo(o2.getName())) .collect(Collectors.toList());
   */

  List sorteByName = Employees.stream().sorted(Comparator.comparing(Employee::getName))
    .collect(Collectors.toList());
  sorteByName.forEach(System.out::println);

  // Sort by Name then Age.
  System.out.println("\n//Sort by Name then Age.");
  List sorteByNameThenAge = Employees.stream()
    .sorted(Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge))
    .collect(Collectors.toList());
  sorteByNameThenAge.forEach(System.out::println);

  // Sort by Name then Age then dateOfJoining.
  System.out.println("\n//Sort by Name then Age then dateOfJoining.");
  List sorteByNameThenAgeThenDoj = Employees.stream().sorted(Comparator.comparing(Employee::getName)
    .thenComparingInt(Employee::getAge).thenComparing(Employee::getDateOfJoining))
    .collect(Collectors.toList());
  sorteByNameThenAgeThenDoj.forEach(System.out::println);

  // Salary > 10000.
  System.out.println("\n//Salary > 10000");
  // find employees whose salaries are above 10000
  /* Filter and print
   * Employees.stream().filter(emp->emp.getSalary() > 10000).forEach(System.out::println);
   */
  /* filter and collect in List
   * List salaryGT10000 = Employees.stream().filter(emp ->emp.getSalary() > 10000) .collect(Collectors.toList());
   */
  List salaryGT10000 = Employees.stream().filter(emp -> emp != null)
    .filter(emp -> emp.getSalary() > 10000).collect(Collectors.toList());
  salaryGT10000.forEach(System.out::println);

  // find max sarary
  // Optional maxSalary = Employees.stream().max(Comparator.comparing(Employee::getSalary));
  // System.out.println(maxSalary);
  Employee maxSalary1 = Employees.stream().max(Comparator.comparing(Employee::getSalary))
    .orElseThrow(NoSuchElementException::new);
  System.out.println("Max salary of employee: " + maxSalary1);

  Employee minSalary1 = Employees.stream().min(Comparator.comparing(Employee::getSalary))
    .orElseThrow(NoSuchElementException::new);
  System.out.println("Min salary of employee: " + minSalary1);
 }
}
Output of above operations.

//Sort by Age.
Employee{ id 3, name='A', age=10, email A1@xyz.com, DOJ Mon Jan 08 00:00:00 IST 1979, Salary 3000}
Employee{ id 3, name='A', age=10, email A2@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1978, Salary 2000}
Employee{ id 4, name='B', age=20, email B@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1989, Salary 2000}
Employee{ id 1, name='C', age=30, email C@xyz.com, DOJ Fri Jan 08 00:00:00 IST 1999, Salary 15000}
Employee{ id 2, name='A', age=40, email A@xyz.com, DOJ Sat Jan 08 00:00:00 IST 1955, Salary 5000}
Employee{ id 5, name='E', age=50, email E@xyz.com, DOJ Tue Jan 08 00:00:00 IST 1985, Salary 10000}

//Sort by Name.
Employee{ id 2, name='A', age=40, email A@xyz.com, DOJ Sat Jan 08 00:00:00 IST 1955, Salary 5000}
Employee{ id 3, name='A', age=10, email A1@xyz.com, DOJ Mon Jan 08 00:00:00 IST 1979, Salary 3000}
Employee{ id 3, name='A', age=10, email A2@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1978, Salary 2000}
Employee{ id 4, name='B', age=20, email B@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1989, Salary 2000}
Employee{ id 1, name='C', age=30, email C@xyz.com, DOJ Fri Jan 08 00:00:00 IST 1999, Salary 15000}
Employee{ id 5, name='E', age=50, email E@xyz.com, DOJ Tue Jan 08 00:00:00 IST 1985, Salary 10000}

//Sort by Name then Age.
Employee{ id 3, name='A', age=10, email A1@xyz.com, DOJ Mon Jan 08 00:00:00 IST 1979, Salary 3000}
Employee{ id 3, name='A', age=10, email A2@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1978, Salary 2000}
Employee{ id 2, name='A', age=40, email A@xyz.com, DOJ Sat Jan 08 00:00:00 IST 1955, Salary 5000}
Employee{ id 4, name='B', age=20, email B@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1989, Salary 2000}
Employee{ id 1, name='C', age=30, email C@xyz.com, DOJ Fri Jan 08 00:00:00 IST 1999, Salary 15000}
Employee{ id 5, name='E', age=50, email E@xyz.com, DOJ Tue Jan 08 00:00:00 IST 1985, Salary 10000}

//Sort by Name then Age then dateOfJoining.
Employee{ id 3, name='A', age=10, email A2@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1978, Salary 2000}
Employee{ id 3, name='A', age=10, email A1@xyz.com, DOJ Mon Jan 08 00:00:00 IST 1979, Salary 3000}
Employee{ id 2, name='A', age=40, email A@xyz.com, DOJ Sat Jan 08 00:00:00 IST 1955, Salary 5000}
Employee{ id 4, name='B', age=20, email B@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1989, Salary 2000}
Employee{ id 1, name='C', age=30, email C@xyz.com, DOJ Fri Jan 08 00:00:00 IST 1999, Salary 15000}
Employee{ id 5, name='E', age=50, email E@xyz.com, DOJ Tue Jan 08 00:00:00 IST 1985, Salary 10000}

//Salary > 10000
Employee{ id 1, name='C', age=30, email C@xyz.com, DOJ Fri Jan 08 00:00:00 IST 1999, Salary 15000}
Max salary of employee: Employee{ id 1, name='C', age=30, email C@xyz.com, DOJ Fri Jan 08 00:00:00 IST 1999, Salary 15000}
Min salary of employee: Employee{ id 3, name='A', age=10, email A2@xyz.com, DOJ Sun Jan 08 00:00:00 IST 1978, Salary 2000}

Wednesday, July 17, 2019

String Operations with Java Streams

Q- Check if a string contains an element from a list of strings?
Q- Convert List of Characters to String in java?

package com.shubh.stream.api;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class StringOperationWithStream {

 public static void main(String[] args) {

  String input = "A hardworking person must relax";
  Predicate startsWithA = (text) -> text.startsWith("A");
  Predicate endsWithX = (text) -> text.endsWith("x");

  // Way-1 (Using Built-in Functional interface --Predicate)
  Predicate startsWithAAndEndsWithX = (text) -> startsWithA.test(text) && endsWithX.test(text);
  boolean result = startsWithAAndEndsWithX.test(input);
  System.out.println(result);

  // Way-2 (Using Predicate Composition "and()")
  Predicate composed = startsWithA.and(endsWithX);
  boolean result2 = composed.test(input);
  System.out.println(result2);

  // Way-3 (Using Predicate Composition "or()")
  Predicate composed2 = startsWithA.or(endsWithX);
  boolean result3 = composed2.test(input);
  System.out.println(result3);

// Using Functional Composition "compose()" example
  Function multiply = (value) -> value * 2;
  Function add = (value) -> value + 3;
  Function addThenMultiply = multiply.compose(add);
  Integer result4 = addThenMultiply.apply(3);
  System.out.println(result4);

// Using Functional Composition "andThen()" example
  // Function multiply = (value) -> value * 2;
  // Function add = (value) -> value + 3;
  Function multiplyThenAdd = multiply.andThen(add);
  Integer result5 = multiplyThenAdd.apply(3);
  System.out.println(result5);

// Find the string in string array which Start with A and End With C
  System.out.println("// String Start with A and End With C");
  String str[] = { "AAA", "AAB", "AAC", "ABC" };
  Predicate strStartsWithA = (text) -> text.startsWith("A");
  Predicate strEndWithC = (text) -> text.endsWith("C");
  Predicate strStartsWithAAndEndsWithC = (text) -> strStartsWithA.test(text) && strEndWithC.test(text);
  Arrays.asList(str).stream().filter(strStartsWithAAndEndsWithC).forEach(s -> System.out.println(s));
  

//Find the string in string array which Contains B and C
  System.out.println("\n// String Contains B and C");
  String str2[] = { "AAA", "AAB", "AAC", "ABC" };
  Predicate strContainB = (text) -> text.contains("B");
  Predicate strContainC = (text) -> text.contains("C");
  // Predicate strContainAandC = (text) -> strContainB.test(text) &&
  // strContainC.test(text);
  // Using Predicate Composition
  Predicate strContainAandC = strContainB.and(strContainC);
  Arrays.asList(str2).stream().filter(strContainAandC).forEach(s -> System.out.println(s));
  

// Find the string in string array which Contains B or C
  System.out.println("\n// String Contains B or C");
  String str3[] = { "AAA", "AAB", "AAC", "ABC" };
  Predicate strContain_B = (text) -> text.contains("B");
  Predicate strContain_C = (text) -> text.contains("C");
  // Predicate strContainA_or_C = (text) -> strContain_B.test(text) ||
  // strContain_C.test(text);
  // Using Predicate Composition
  Predicate strContainA_or_C = strContain_B.or(strContain_C);

  // Print filtered records
  Arrays.asList(str3).stream().filter(strContainA_or_C).forEach(s -> System.out.println(s));

  System.out.println("\n// Iterate using forEach()");
  List result6 = Arrays.asList(str3).stream().filter(strContainA_or_C).collect(Collectors.toList());
  result6.forEach(s -> System.out.println(s));
 }
}
Output of above operations.

true
true
true
12
9
// String Start with A and End With C
AAC
ABC

// String Contains B and C
ABC

// String Contains B or C
AAB
AAC
ABC

// Iterate using forEach()
AAB
AAC
ABC

Sunday, July 14, 2019

How To Sort HashMap using stream in java 8

Sort HashMap by values in ascending and descending order using stream api.

Important points to Remember
There are some points to remember once you are sorting a map by value using stream api.

  • We should Use LinkedHashMap for collecting the result to keep the sorting intact.
  • Use static import for better readability e.g. static import Map.Entry nested class.
  • We should use method from Map.Entry like comparingByValue() and comparingByKey() which was added in Java to make sorting by key and value in Java 8.
  •  To sort map in descending order use reversed() method. 
  • To print map use forEach()
  • Use Collectors to collect the result into a Map but always use LinkedHashMap because it maintains the insertion order. 


package com.shubh.stream.list.to.map;

import java.util.*;
import java.util.stream.*;

public class MapToStream {

 public static <K, V> Stream<Map.Entry<K, V>> convertMapToStream(Map<K, V> map) {
  return map.entrySet().stream();
 }

 public static void main(String args[]) {

  Map<Integer, String> map = new HashMap<>();
  map.put(1, "Sandeep");
  map.put(2, "Suman");
  map.put(3, "Aman");
  map.put(4, "Kamal");
  map.put(5, "Raj");

  // Print the Map
  System.out.println("Map: " + map);

  // Convert the Map to Stream
  // Stream<Map.Entry<Integer, String>> stream = map.entrySet().stream();

  // Convert the Map to Stream using keySet()
  // Stream<Integer> streamKey = map.keySet().stream();
  
  // Convert the Map to Stream using values()
  // Stream<String> streamValue = map.values().stream();

  // Print
  // System.out.println("Stream: " + Arrays.toString(stream.toArray()));

  // Compare By Value and print.
  map.entrySet().stream().sorted(Map.Entry.<Integer, String>comparingByValue()).forEach(System.out::println);

  // collect the sorted entries in Map
  System.out.println("// collect the sorted entries in Map");
  Map<Integer, String> sortedByValue = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue())
    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

  sortedByValue.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));

  System.out.println("// collect the sorted entries in Map");
  Map<Integer, String> sortedByValue2 = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

  sortedByValue2.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));

  // Sorting Map by values on decreasing Order
  System.out.println("//Sorting Map by values on decreasing Order");
  Map<Integer, String> sortedByValueDesc = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue().reversed())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

  sortedByValueDesc.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));

 }
}
Output

Map: {1=Sandeep, 2=Suman, 3=Aman, 4=Kamal, 5=Raj}
3=Aman
4=Kamal
5=Raj
1=Sandeep
2=Suman
// collect the sorted entries in Map
Key: 1 Value: Sandeep
Key: 2 Value: Suman
Key: 3 Value: Aman
Key: 4 Value: Kamal
Key: 5 Value: Raj
// collect the sorted entries in Map
Key: 3 Value: Aman
Key: 4 Value: Kamal
Key: 5 Value: Raj
Key: 1 Value: Sandeep
Key: 2 Value: Suman
//Sorting Map by values on decreasing Order
Key: 2 Value: Suman
Key: 1 Value: Sandeep
Key: 5 Value: Raj
Key: 4 Value: Kamal
Key: 3 Value: Aman




Related Tutorial

Stream API Examples

Q- How to create stream in java 8?
There are number of ways to create steram in java.
  • Stream from an array
  • Stream from an list
  • Stream from individual objects using Stream.of()
  • Using Stream.builder()
  • Stream myStream = Arrays.stream(myArray);
In below Examples you will see how to create stream and use methods of stream in java 8.


package com.shubh.stream.list.to.map;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StreamMethodExample {

 public static void main(String[] args) {

  String[] myArray = new String[]{"Amar", "Aman", "Kuldeep"};
  // Create stream then sort and collect in list"
  System.out.println(" // Create stream and sort then collect in list");
  List list = Arrays.stream(myArray).sorted().collect(Collectors.toList());
  list.forEach(s -> System.out.println(s));
  
  // Create stream then sort and print
  System.out.println(" // Create stream and sort then print");
  Arrays.stream(myArray).sorted().forEach(s -> System.out.println(s));

  // Create stream using list example
  System.out.println("// Create stream using list example ");
  List items = new ArrayList();
  items.add("Arun");
  items.add("Tarun");
  items.add("Pradeep");
  Stream stream = items.stream();

  // Stream concat() example
  System.out.println("// Stream concat() example ");
  List list1 = Arrays.asList("Raj", "Kumar", "Gupta");
  List list2 = Arrays.asList("Deepak", "Kamal", "Sandeep");
  Stream resStream = Stream.concat(list1.stream(), list2.stream());
  resStream.forEach(s -> System.out.println(s));

  // Stream count() example
  System.out.println("// Stream count() example");
  List list = Arrays.asList("Amar", "Aman", "Kuldeep");
  Predicate predicate = s -> s.startsWith("A");
  long startWithA = list.stream().filter(predicate).count();
  System.out.println("Number of Matching Element:" + startWithA);

  // Stream sorted() example
  System.out.println("// Stream sorted() example ");
  List listToSort = Arrays.asList("Suresh", "Amit", "Boby");
  listToSort.stream().sorted().forEach(s -> System.out.println(s));

  // Stream distinct() example
  System.out.println("// Stream distinct() example ");
  List list3 = Arrays.asList("AAA", "AAA", "BBB");
  long elementCount = list3.stream().distinct().count();
  System.out.println("Number of distinct element:" + elementCount);
 }
}
Output of above program.

// Create stream using list example 
// Stream concat() example 
Raj
Kumar
Gupta
Deepak
Kamal
Sandeep
// Stream count() example
Number of Matching Element:2
// Stream sorted() example 
Amit
Boby
Suresh
// Stream distinct() example 
Number of distinct element:2
We can obtain a stream in different ways.

package com.shubh.stream.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamCreation {

 public static void main(String[] args) throws ParseException {

  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

  Employee arrayOfEmps[] = { new Employee(1, "C", 30, "C@xyz.com", formatter.parse("01/08/1999"), 15000),
    new Employee(2, "A", 40, "A@xyz.com", formatter.parse("01/08/1955"), 5000),
    new Employee(3, "A", 10, "A1@xyz.com", formatter.parse("01/08/1979"), 3000),
    new Employee(3, "A", 10, "A2@xyz.com", formatter.parse("01/08/1978"), 2000),
    new Employee(4, "B", 20, "B@xyz.com", formatter.parse("01/08/1989"), 2000),
    new Employee(5, "E", 50, "E@xyz.com", formatter.parse("01/08/1985"), 10000) };

  // stream from an array:
  Stream.of(arrayOfEmps);

  // stream from an list:
  List empList = Arrays.asList(arrayOfEmps);
  empList.stream();

  // stream from individual objects using Stream.of():
  Stream.of(arrayOfEmps[0], arrayOfEmps[1], arrayOfEmps[2]);

  // using Stream.builder():
  Stream.Builder streamBuilder = Stream.builder();
  streamBuilder.accept(arrayOfEmps[0]);
  streamBuilder.accept(arrayOfEmps[1]);
  streamBuilder.accept(arrayOfEmps[2]);
  Stream employeeStream = streamBuilder.build();
 }
}
Map() And Filter() Example

package com.shubh.stream.comparator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CreateStreamApp {
public static void main(String args[]) {
        
        List myList = new ArrayList();
        myList.add("AAA");
        myList.add("AaA");
        myList.add("aAk");
        
        // Here first it will filter "start with lowercase "a" character then convert into uppercase
        System.out.println("// Here first it will filter startsWith('a') character then convert into uppercase");
        List startWithLowerCase_A_ThenConvertToUpperCase = myList.stream().filter(item->item.startsWith("a")).map(item -> item.toUpperCase()).collect(Collectors.toList());
        startWithLowerCase_A_ThenConvertToUpperCase.forEach(s->System.out.println(s));
        
        // Here fisrt it conver to uppercase then filter--- start with lowercase "a". So there is no output. because there is no lower case character in stting after map operation.  
        System.out.println("// Here fisrt it conver to uppercase then filter--- startsWith('a').So there is no output. because there is no lower case character in stting after map operation.");
        List resultList = myList.stream().map(item -> item.toUpperCase()).filter(item->item.startsWith("a")).collect(Collectors.toList());
        resultList.forEach(s->System.out.println(s));
        
         // Here fisrt it conver to uppercase then filter--- start with uppercase "A".
         System.out.println(" // Here fisrt it conver to uppercase then filter--- startsWith('A').");
        List resultList1 = myList.stream().map(item -> item.toUpperCase()).filter(item->item.startsWith("A")).collect(Collectors.toList());
        resultList1.forEach(s->System.out.println(s));
    }
}

Output of above program.

// Here first it will filter startsWith('a') character then convert into uppercase
AAK
// Here fisrt it conver to uppercase then filter--- startsWith('a').So there is no output. because there is no lower case character in stting after map operation.
 // Here fisrt it conver to uppercase then filter--- startsWith('A').
AAA
AAA
AAK


Related Tutorial