How to Get Least Value Element From TreeSet in Java


In this example,  we will learn how to get least value element from least value element. Here we can use the first() method in the TreeSet object to obtain the smallest element.

Source Code

– User class

package com.beginner.examples;

public class User implements Comparable {

	private String username;
	private int age;

	public User() {

	}

	public User(String username, int age) {
		this.age = age;
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public int compareTo(User u) {
		
		//Comparative age first
		int num1 = this.getAge() - u.getAge();
		
		//Compare names of the same age
		int num2 = num1==0?this.getUsername().compareTo(u.getUsername()):num1;
		
		return num2;
	}

}

– GetLeastFromTreeSet

package com.beginner.examples;

import java.util.TreeSet;

public class GetLeastFromTreeSet {

	public static void main(String[] args) {

		TreeSet userSet = new TreeSet();

		userSet.add(new User("Tom", 22));
		userSet.add(new User("Ruth", 20));
		userSet.add(new User("Jerry", 21));
		userSet.add(new User("John", 19));

		// Get the smallest element in the set using first() because it's sorted
		User user = userSet.first();

		System.out.println(user.getUsername()+","+user.getAge());

	}

}

Output:

John,19

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments