Usage of map,max,sorted,comparing java 8 methods

 

Java 8 Stream Methods: map, max, sorted, and comparing

Java 8 introduced powerful functional programming features with its Stream API, allowing developers to write more expressive and readable code. Some of the key methods provided by this API include map, max, sorted, and comparing.

  1. map: The map method is used to transform each element of a stream into another form. It takes a function as a parameter, which is applied to each element in the stream, producing a new stream of transformed elements. This is particularly useful for converting data types or extracting certain properties from objects.

  2. max: The max method is used to find the maximum element in a stream according to the specified comparator. It returns an Optional containing the maximum element, or an empty Optional if the stream is empty. This method is commonly used for finding the largest value or object based on a specific attribute.

  3. sorted: The sorted method is used to sort the elements of a stream. It can be called without arguments to sort elements in their natural order, or with a comparator to sort them according to a custom order. This method is useful for arranging data in a particular sequence, such as alphabetical or numerical order.

  4. comparing: The comparing method is a static utility method from the Comparator class. It is used to create a comparator based on a key extractor function. This method can be used with the sorted method to sort elements by specific fields or properties, making it flexible for different sorting needs.

These methods, when used together, enable concise and expressive code for data processing tasks, leveraging the full power of functional programming in Java 8.


Question 1:

Return highest salary number from the list of employees object. ?


  
     List employeeList = List.of(new Employee("jhon", 29),
                                            new Employee("mic", 90),
                                            new Employee("leonard",80),
                                            new  Employee("jessy",60),
                                            new Employee("ganga",100));
                                            
                                            
        int highestSal= employeeList.stream()
                    .map(Employee::getSalary)
                     .max(Comparator.naturalOrder())
                    .get();

        System.out.println(highestSal);
 
  

 

Question 2:

Return Employee name who has highest salary from the list of employees object. ?



Employee employee= employeeList.stream()
                        .sorted(Comparator.comparing(employee1 -> employee1.getSalary(),Comparator.reverseOrder()))
                    .findFirst().get();
        System.out.println(employee.getName());
        
     
  

Comments

Popular posts from this blog

First Repeating character in a string

Index of first repeated character in a string.