Java/컬렉션

[Java]컬렉션(Collection) 최소값 최대값 구하기

DevStory 2022. 4. 5.

이번 포스팅에서는 Java의 컬렉션(Collection)에서 최소 또는 최대 값을 가져오는 방법들을 소개합니다.


Collections.min() 메서드와 Collections.max() 메서드

Java Collection Framework는 개발자가 컬렉션을 쉽게 사용할 수 있도록 다양한 메서드와 속성들을 제공합니다. 다양한 메서드 중에서 Collections.min() 및 Collections.max() 메서드는 컬렉션의 최소 또는 최대 요소를 반환합니다.


기본 타입에서 사용

컬렉션의 요소들이 int, byte, short 등 기본 타입(Primitive type)으로 구성된 경우 최솟값과 최댓값을 상당히 쉽게 찾을 수 있습니다.

 

기본 타입으로 구성된 컬렉션의 최소 또는 최대 요소를 찾으려면 Collections.min() 또는 Collections.max() 메서드에 컬렉션 객체를 전달합니다.

 

다음은 숫자 타입으로 구성된 컬렉션에서 최솟값과 최댓값을 반환합니다.

List<Integer> list = List.of(6, 3, 10, 0, 7);

Integer min = Collections.min(list);
Integer max = Collections.max(list);

System.out.println("Min value: " + min);
System.out.println("Max value: " + max);

실행 결과

Min value: 0
Max value: 10

객체에서 사용

컬렉션의 요소들은 기본 타입이 아닌 객체로 구성될 수 있습니다. 컬렉션의 요소가 객체로 구성된 경우 클래스의 두 인스턴스를 비교하는 Comparable 인터페이스를 구현해야 합니다.

public class Person implements Comparable<Person> {
  private String name;
  private int age;
  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
   
  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;
  }

  @Override
  public int compareTo(Person person) {
    return (this.age > person.age) ? 1 : -1;
  }

  @Override
  public String toString() {
    return "Person{" +
           "name='" + name + '\'' +
           ", age=" + age +
           '}';
  }
}

compareTo() 메서드를 재정의(Override)하여 비교하는 기준을 정의합니다. 위 예제에서는 나이(age)를 기준으로 비교합니다.

 

이제 타입이 Person 클래스인 컬렉션에서 최소 또는 최대 요소를 찾습니다.

List<Person> person = new ArrayList<>();
person.add(new Person("Nick", 52));
person.add(new Person("Ray", 22));
person.add(new Person("Tom", 43));
person.add(new Person("Bob", 28));

Person min = Collections.min(person);
Person max = Collections.max(person);

System.out.println("Min: " + min);
System.out.println("Max: " + max);

실행 결과

Min: Person{name='Ray', age=22}
Max: Person{name='Nick', age=52}
반응형

Comparator 전달

클래스에서 Comparable 인터페이스를 구현하지 않고 Collections.min() 또는 Collections.max() 메서드에 Comparator를 전달하여 객체의 속성을 비교할 수 있습니다.

Person min = Collections.min(person, new Comparator<Person>() {
  @Override
  public int compare(Person o1, Person o2) {
    return (o1.getAge() > o2.getAge()) ? 1 : -1;
  }
});

System.out.println("Min: " + min);

실행 결과

Min: Person{name='Ray', age=22}

위 예제는 람다식을 사용하여 더 간결하게 작성할 수 있습니다.

Person min = Collections.min(person,
  (o1, o2) -> (o1.getAge() > o2.getAge()) ? 1 : -1);

Stream.min() 메서드와 Stream.max() 메서드

Stream은 min() 또는 max() 메서드를 사용하여 최소 또는 최대 요소를 찾을 수 있습니다.

기본 타입에서 사용

Stream을 사용하여 컬렉션의 최소 또는 최대 요소를 찾으려면 먼저 컬렉션을 스트림으로 만들어야 합니다. stream() 메서드를 호출하여 컬렉션을 스트림으로 만든 후 min() 또는 max() 메서드를 호출합니다.

List<Integer> list = List.of(6, 3, 10, 0, 7);

Integer min = list.stream().mapToInt(i -> i).min().getAsInt();
Integer max = list.stream().mapToInt(i -> i).max().getAsInt();

System.out.println("Min value: " + min);
System.out.println("Max value: " + max);

실행 결과

Min value: 0
Max value: 10

min()과 max() 메서드는 기본 타입이 아닌 Optional, OptionalInt, OptionalDouble 등과 같은 클래스의 값을 반환합니다. 정수 값을 추출하기 위해 getAsInt() 메서드를 사용합니다.


객체에서 사용

Stream을 사용하여 객체를 비교하는 경우 더 이상 클래스에서 Comparator 인터페이스를 구현하지 않아도 됩니다.

 

다음은 Person 클래스에서 Comparator 인터페이스와 compareTo() 메서드를 제거하였습니다.

public class Person {
  private String name;
  private int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  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;
  }

  @Override
  public String toString() {
    return "Person{" +
           "name='" + name + '\'' +
           ", age=" + age +
           '}';
  }
}

min() 또는 max() 메서드에 Comparator.comparing() 메서드를 전달하여 특정 필드 기준으로 객체를 비교합니다.

List<Person> person = new ArrayList<>();
person.add(new Person("Nick", 52));
person.add(new Person("Ray", 22));
person.add(new Person("Tom", 43));
person.add(new Person("Bob", 28));

Person min = person.stream().min(Comparator.comparing(Person::getAge)).get();
Person max = person.stream().max(Comparator.comparing(Person::getAge)).get();

System.out.println("Min: " + min);
System.out.println("Min: " + max);

실행 결과

Min: Person{name='Ray', age=22}
Min: Person{name='Nick', age=52}

반복문 사용

가장 간단한 방법은 반복문을 사용하여 최소 또는 최대 요소를 찾습니다.

List<Person> person = new ArrayList<>();
person.add(new Person("Nick", 52));
person.add(new Person("Ray", 22));
person.add(new Person("Tom", 43));
person.add(new Person("Bob", 28));

Person min = person.get(0);

for (Person obj : person) {
  if (obj.getAge() < min.getAge()) {
    min = obj;
  }
}

System.out.println("Min: " + min);

실행 결과

Min: Person{name='Ray', age=22}
반응형

댓글