Java/컬렉션

[Java]HashSet 최소값 최대값 구하기

DevStory 2022. 4. 4.

이번 포스팅에서는 Java의 HashSet에서 최소 또는 최대 값을 가져오는 방법들을 소개합니다.


컬렉션에서 최소 또는 최댓값을 찾는 방법

HashSet은 Java Collection Framework에 존재하는 클래스입니다. 그러므로 컬렉션의 최소 또는 최댓값 구하는 방법을 알고 계신다면 HashSet에 응용할 수 있습니다.

 

컬렉션의 최소 또는 최댓값 구하는 방법은 소개한 적이 있으므로 메서드에 대한 설명은 간략하게 진행합니다.


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

Collections.min()과 Collections.max() 메서드는 HastSet의 최소 또는 최대 값을 반환합니다.


기본 타입에서 사용

HashSet의 제네릭 타입이 기본 타입인 경우 Collections.min() 메서드와 Collections.max() 메서드에 컬렉션 객체를 전달하면 됩니다.

Set<Integer> hSetInt = new HashSet<Integer>();

hSetInt.add(40);
hSetInt.add(0);
hSetInt.add(20);
hSetInt.add(33);
hSetInt.add(14);

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

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

실행 결과

Min Integer: 0
Max Integer: 40

 

HashSet의 요소가 문자열로 구성된 경우 사전 순으로 비교합니다.

Set<String> hSetString = new HashSet<String>();

hSetString.add("ABC");
hSetString.add("BBB");
hSetString.add("AB");
hSetString.add("BBC");

String minStr = Collections.min(hSetString);
String maxStr = Collections.max(hSetString);

System.out.println("Min String: " + minStr);
System.out.println("Max String: " + maxStr);

실행 결과

Min String: AB
Max String: BBC
반응형

객체에서 사용

HashSet의 요소들이 클래스 객체인 경우 해당 클래스는 Comparable 인터페이스를 구현하거나 Comparator 객체를 지정해야 합니다.

 

다음 예제의 Person 클래스는 Comparable 인터페이스를 구현하였으며 나이(age)를 비교하기 위해 compareTo() 메서드를 재정의(Override)합니다.

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

 

제네릭 타입이 Person 클래스인 HashSet에서 나이가 최소 또는 최대인 요소를 찾습니다.

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}

반복문 사용

Java Collection Framework, Comparable, Stream 사용 방법이 어렵다고 느껴진다면 반복문을 사용하여 최소 또는 최대 요소를 찾을 수 있습니다.

 

Person 클래스에서 Comparable 인터페이스와 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 +
           '}';
  }
}

반복문에서 나이(age)를 비교하여 최소 요소와 최대 요소를 찾습니다.

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);
Person max = person.get(0);

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

for (Person obj : person) {
  if (obj.getAge() > max.getAge()) {
    max = obj;
  }
}

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

실행 결과

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

댓글