How to Create a TreeSet with Comparator in Java


In this example we will show how to create a TreeSet with comparator. The first step is to create a custom comparator class that defines the rules for sorting according to your requirements.Then specify the object of this class to create the TreeSet collection.

Source Code

package com.beginner.examples;

import java.util.Comparator;
import java.util.TreeSet;


//Custom comparator
class myComparator implements Comparator{

	@Override
	public int compare(String s1, String s2) {
		
		
		//Compare the length of the string
		int num1 = s1.length()-s2.length();
		
		//If the lengths are the same, compare them in the natural order
		int num2 = num1 ==0?s1.compareTo(s2):num1;
		
		return num2;
		
	}
	
}

public class CreateTreeSetWithComparator {

	public static void main(String[] args) {
	
		TreeSet set = new TreeSet(new myComparator());
		
		set.add("abc");
		set.add("ab");
		set.add("bc");
		set.add("bcde");
		set.add("bcd");
		
		System.out.println(set);
		
		
	}

}

Output:

[ab, bc, abc, bcd, bcde]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments