Search code examples
javacollections

Is there a oneliner to create a SortedSet filled with one or multiple elements in Java?


I am just asking myself if there is a more convenient way to create a SortedSet, e.g. a TreeSet in Java than the one liner I am currently using in tests:

new TreeSet<>(Set.of(element1, element2));

Something like SortedSet.of(...) maybe from Apache Commons or the like?


Solution

  • You can use a library like Guava:

    import com.google.common.collect.Sets;
    import java.util.SortedSet;
    
    SortedSet<Integer> sortedSet = Sets.newTreeSet(ImmutableSet.of(1, 2, 3));