Site icon

Convert HashSet to TreeSet in java (example)

What is HashSet in java?

Program – Convert HashSet<String> to TreeSet<String>

package org.learn.collection.set.hset;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class DemoHashSetToTreeSet {

	public static void main(String[] args) {
		Set<String> setSports = new HashSet<>();
		setSports.add("Tennis");
		setSports.add("Cricket");
		setSports.add("Tennis");
		setSports.add("Basketball");
		setSports.add("Golf");
		setSports.add("Boxer");		
		
		System.out.println("Set: "+ setSports);
		
		Set<String> hashSetToTreeSet = new TreeSet<>(setSports);
		System.out.println("TreeSet:"+hashSetToTreeSet);		
	}
}

Output – convert HashSet to TreeSet in java

Set: [Tennis, Cricket, Golf, Basketball, Boxer]
TreeSet:[Basketball, Boxer, Cricket, Golf, Tennis]
Exit mobile version