Friday, 29 October 2021

Java: How to find the minimum element in a collection?

In this post, I am going to explain different approaches to find the maximum element from a collection.

 


Approach 1: Iterate over a collection and find the minimum element.

private static <T extends Comparable<T>> T findMinElement(Collection<T> elements) {
	if (elements == null || elements.isEmpty()) {
		return null;
	}

	T min = null;

	for (T ele : elements) {

		if (min == null) {
			min = ele;
			continue;
		}

		if (min.compareTo(ele) < 0) {
			min = ele;
		}

	}

	return min;

}


Find the below working application.

 

FindMinElement1.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class FindMinElement1 {

	private static <T extends Comparable<T>> T findMinElement(Collection<T> elements) {
		if (elements == null || elements.isEmpty()) {
			return null;
		}

		T min = null;

		for (T ele : elements) {

			if (min == null) {
				min = ele;
				continue;
			}

			if (min.compareTo(ele) < 0) {
				min = ele;
			}

		}

		return min;

	}

	public static void main(String args[]) {

		List<Integer> integers = Arrays.asList(1, 3, 5, 2, 31, 87, 6, 5);
		Integer minInteger = findMinElement(integers);

		System.out.println("minInteger -> " + minInteger);

	}

}

 

Output

minInteger -> 1

 

Approach 2: Using 'Collections.min' method.

 

Collections class provides ‘min' method to get the minimum element from a collection.

 

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

Returns the maximum element of the given collection, according to the natural ordering of its elements. To use this method, elements in the collection must implement Comparable interface.

 

public static <T> T min(Collection<? extends T> coll,Comparator<? super T> comp)

Returns the maximum element of the given collection, according to the logic supplied by the custom comparator.

 

FindMinElement2.java

 

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class FindMinElement2 {
	private static <T extends Comparable<T>> T findMinElement(Collection<T> elements) {
		if (elements == null || elements.isEmpty()) {
			return null;
		}

		return Collections.min(elements);

	}

	public static void main(String args[]) {

		List<Integer> integers = Arrays.asList(3, 5, 2, 1, 31, 87, 6, 5);
		Integer minInteger = findMinElement(integers);

		System.out.println("minInteger -> " + minInteger);

	}

}

 

Output

minInteger -> 1

 

Let’s supply a custom comparator and find out the minimum person object from the collection of persons. A person p1 is lesser than person p2, if p1’s age is less than p2.

 

Example

 

Person minPerson = Collections.min(persons, (person1, person2) -> {
	return person1.age.compareTo(person2.age);
});

 

Find the below working application.

 

FindMinElement3.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FindMinElement3 {

	private static class Person {
		private String name;
		private Integer age;
		private Integer id;

		public Person(String name, Integer age, Integer id) {
			super();
			this.name = name;
			this.age = age;
			this.id = id;
		}

		@Override
		public String toString() {
			return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
		}

	}

	public static void main(String args[]) {

		Person p1 = new Person("Krishna", 33, 1);
		Person p2 = new Person("Ram", 34, 2);
		Person p3 = new Person("Soundarya", 53, 3);
		Person p4 = new Person("Prahlad", 21, 4);

		List<Person> persons = Arrays.asList(p1, p2, p3, p4);

		Person minPerson = Collections.min(persons, (person1, person2) -> {
			return person1.age.compareTo(person2.age);
		});

		System.out.println("minPerson -> " + minPerson);
	}

}

Output

minPerson -> Person [name=Prahlad, age=21, id=4]

 


You may like

Interview Questions

What is bridge method in Java?

How HashSet behave while adding a duplicate value?

How to call a method asynchronously in Java?

How method overloading works with null values in Java?

Java: How to find maximum element in a collection?

Java: How to find maximum element in a collection?

In this post, I am going to explain different approaches to find the maximum element from a collection.

 


Approach 1: Iterate over a collection and find the maximum element.

private static <T extends Comparable<T>> T findMaxElement(Collection<T> elements) {
	if (elements == null || elements.isEmpty()) {
		return null;
	}

	T max = null;

	for (T ele : elements) {

		if (max == null) {
			max = ele;
			continue;
		}

		if (max.compareTo(ele) < 0) {
			max = ele;
		}

	}

	return max;

}

 

Find the below working application.

 

FindMaxElement1.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class FindMaxElement1 {

	private static <T extends Comparable<T>> T findMaxElement(Collection<T> elements) {
		if (elements == null || elements.isEmpty()) {
			return null;
		}

		T max = null;

		for (T ele : elements) {

			if (max == null) {
				max = ele;
				continue;
			}

			if (max.compareTo(ele) < 0) {
				max = ele;
			}

		}

		return max;

	}

	public static void main(String args[]) {

		List<Integer> integers = Arrays.asList(1, 3, 5, 2, 31, 87, 6, 5);
		Integer maxInteger = findMaxElement(integers);

		System.out.println("maxInteger -> " + maxInteger);

	}

}

Output

maxInteger -> 87


Approach 2: Using 'Collections.max' method.

Collections class provides ‘max' method to get the maximum element from a collection.

 

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

Returns the maximum element of the given collection, according to the natural ordering of its elements. To use this method, elements in the collection must implement Comparable interface.

 

public static <T> T max(Collection<? extends T> coll,Comparator<? super T> comp)

Returns the maximum element of the given collection, according to the logic supplied by the custom comparator.

 

FindMaxElement2.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class FindMaxElement2 {
	private static <T extends Comparable<T>> T findMaxElement(Collection<T> elements) {
		if (elements == null || elements.isEmpty()) {
			return null;
		}

		return Collections.max(elements);

	}

	public static void main(String args[]) {

		List<Integer> integers = Arrays.asList(1, 3, 5, 2, 31, 87, 6, 5);
		Integer maxInteger = findMaxElement(integers);

		System.out.println("maxInteger -> " + maxInteger);

	}

}


Output

maxInteger -> 87


Let’s supply a custom comparator and find out the maximum person object from the collection of persons. A person p1 is greater than person p2, if p1’s age is greater than p2.

 

Example

Person maxPerson = Collections.max(persons, (person1, person2) -> {
	return person1.age.compareTo(person2.age);
});


FindMaxElement3.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FindMaxElement3 {

	private static class Person {
		private String name;
		private Integer age;
		private Integer id;

		public Person(String name, Integer age, Integer id) {
			super();
			this.name = name;
			this.age = age;
			this.id = id;
		}

		@Override
		public String toString() {
			return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
		}

	}

	public static void main(String args[]) {

		Person p1 = new Person("Krishna", 33, 1);
		Person p2 = new Person("Ram", 34, 2);
		Person p3 = new Person("Soundarya", 53, 3);
		Person p4 = new Person("Prahlad", 21, 4);

		List<Person> persons = Arrays.asList(p1, p2, p3, p4);

		Person maxPerson = Collections.max(persons, (person1, person2) -> {
			return person1.age.compareTo(person2.age);
		});

		System.out.println("maxPerson -> " + maxPerson);
	}

}


Output

maxPerson -> Person [name=Soundarya, age=53, id=3]

 

 

You may like

Interview Questions

Synthetic constructs in Java

What is bridge method in Java?

How HashSet behave while adding a duplicate value?

How to call a method asynchronously in Java?

How method overloading works with null values in Java?

Pydantic: Apply validator on every item of a collection (set, list, dict etc.,)

By passing the argument 'each_item=True' to the validator decorator, we can validate every item in the collection.

 

Let’s see it with an example.

 

validator_demo_5.py

from pydantic import BaseModel, ValidationError, validator
from typing import List

class Test(BaseModel):
    even_numbers: List[int]

    @validator('even_numbers', each_item=True)
    def evenNumValidator(cls, value):
        if(value % 2 != 0):
            raise ValueError('number must be even')
        return value

try:
    t1 = Test(even_numbers = [2, 4, 6])
    print(t1)

    t2 = Test(even_numbers = [2, 4, 5, 6, 7])
    print(t2)
except ValidationError as e:
    print(e.json())

 

Output

even_numbers=[2, 4, 6]
[
  {
    "loc": [
      "even_numbers",
      2
    ],
    "msg": "number must be even",
    "type": "value_error"
  },
  {
    "loc": [
      "even_numbers",
      4
    ],
    "msg": "number must be even",
    "type": "value_error"
  }
]

 

On validation failure, it return the failed position element from the list.

 

 

Previous                                                    Next                                                    Home

FastAPI: Add numeric validations on path parameter

You can specify numeric validations on Path parameters. You can supply attributes gt, ge, lt and le to perform numeric checks.

 

a.   gt: greater than

b.   ge: greater than or equal

c.    lt: less than

d.   le: less than or equal

 

Example

@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

main.py

from fastapi import FastAPI, Path

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32
    },
    2 : {
        "name" : "Ram",
        "age": 33
    }
}

# Create an endpoint
@app.get("/")
def home():
    return {"name" : "Hello World app", "version": "2.0.0"}

# Employees REST APIs
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

Run main.py by executing the command ‘uvicorn main:app --reload’.

$uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [78097] using statreload
INFO:     Started server process [78099]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://127.0.0.1:8000/docs’ in browser, expand the REST api /emps/by-id/{empId} and try with employee id <= 0 or > 2, you will see validation error messages.

 

  

Previous                                                    Next                                                    Home