Day 6 - Java

Problem Statement: Search, Sort, and Find in a List

You are given a list of integers and a search key. Your task is to implement a program that finds the minimum and maximum numbers in the list, sorts the list in ascending or descending order based on user input, and searches for a specific number in the list.

Write a Java program named SearchAndSortWithStreams with a method searchAndSort that takes the following parameters:

List<Integer> numbers: A list of integers.

int searchKey: An integer to search for in the list.

char sortOrder: A character representing the sorting order. 'a' for ascending and 'd' for descending.

Your program should perform the following tasks:

Input:

The first line of input contains an integer n, the size of the list.

The next n lines contain space-separated integers representing the elements of the list.

The next line contains an integer searchKey, the number to search for.

The last line contains a character sortOrder, representing the sorting order ('a' for ascending, 'd' for descending).

Output:

Print the minimum and maximum numbers found in the list.

Print the sorted list according to the given sorting order.

Print the position of the search key in the list if found, else print "not found".

Constraints:

1 <= n <= 10^5

-10^9 <= numbers[i] <= 10^9

Each integer in the list is distinct.

Note:

The list is not necessarily sorted initially.

If the sorting order provided is neither 'a' nor 'd', print "Invalid"

Sample Input:

5

3 1 4 5 2

4

a

Sample Output:

Minimum number: 1

Maximum number: 5

Sorted list: [1, 2, 3, 4, 5]

4 found at position: 3

Explanation:

In the given sample, the list contains numbers [3, 1, 4, 5, 2]. The minimum number is 1, and the maximum number is 5. The list sorted in ascending order is [1, 2, 3, 4, 5]. The search key 4 is found at position 3.

Test Case:

Input:

5

18 9 7 3 6

2024

d

Output:

Minimum number: 3

Maximum number: 18

Sorted list: [18, 9, 7, 6, 3]

2024 not found

SOLUTION

import java.util.ArrayList;

import java.util.Comparator;

import java.util.List;

import java.util.Optional;

import java.util.Scanner;

import java.util.stream.Collectors;


public class SearchAndSortWithStreams {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int size = scanner.nextInt();

        List<Integer> numbers = new ArrayList<>();

        for (int i = 0; i < size; i++) {

            numbers.add(scanner.nextInt());

        }

        int searchKey = scanner.nextInt();

        char sortOrder = scanner.next().charAt(0);

        searchAndSort(numbers, searchKey, sortOrder);

    }


    public static void searchAndSort(List<Integer> numbers, int searchKey, char sortOrder) {

        Optional<Integer> minNumber = numbers.stream().min(Comparator.naturalOrder());

        Optional<Integer> maxNumber = numbers.stream().max(Comparator.naturalOrder());

        if (minNumber.isPresent() && maxNumber.isPresent()) {

            System.out.println("Minimum number: " + minNumber.get());

            System.out.println("Maximum number: " + maxNumber.get());

        } else {

            System.out.println("List is empty.");

        }

        List<Integer> sortedList;

        if (sortOrder == 'a') {

            sortedList = numbers.stream().sorted().toList();

        } else if (sortOrder == 'd') {

            sortedList = numbers.stream().sorted(Comparator.reverseOrder()).toList();

        } else {

            System.out.println("Invalid");

            return;

        }

        System.out.println("Sorted list: " + sortedList);

        if (numbers.contains(searchKey)) {

            int position = numbers.indexOf(searchKey);

            System.out.println(searchKey + " found at position: " + (position + 1));

        } else {

            System.out.println(searchKey + " not found");

        }

    }

}

Insights:
  • Optional is used to handle the possibility of an empty list. It ensures that if the list is empty, the program doesn't encounter null values when attempting to find the minimum and maximum numbers.
  • The code utilizes Java Stream API methods such as min(), max(), sorted(), and toList() to perform operations on the list of integers efficiently.
  • The code uses the contains() method to check if the search key exists in the list. If found, it determines the position of the key using indexOf(). This approach provides a straightforward way to search for elements in the list.
  • Comparator.naturalOrder() is used to create a comparator that imposes a natural ordering on integers. Comparator.reverseOrder() is used to create a comparator that imposes the reverse of the natural ordering. These comparators are used in the sorted() method to sort the list of integers either in ascending or descending order.
  • Stream is a sequence of elements supporting sequential and parallel aggregate operations. In the program, numbers.stream() is used to create a stream from the list of integers.
  • toList() is a terminal operation in streams that collects the elements of the stream into an unmodifiable list.
  • Functional programming emphasizes immutable data and pure functions, which can greatly enhance code clarity and robustness.

Enjoy and learn Java! :)

Comments