0

I need to save some Words in a TreeSet and print them depending on thier length where words with smaller length come first and if 2 Words have the same length, then both should be printed in any order, but my code skips the next word with the same length and prints only the first word with that length.

import java.util.*;

public class Test {
           
   static Comparator<String> comparator = Comparator.comparing(s -> s.length());

   public static void main(String[] args) {
      Set<String> buch = new TreeSet <>(comparator);
      buch.addAll(List.of("a", "test", "ab", "z", "lol", "aaa"));
      buch.forEach(System.out::println);
    }
}
  • 1
    Dont use `TreeSet` , because if consider Your `2 Words have the same length` as duplicates and that class prevent duplicates that has the same value ( from the comparator ) witch is the length ! Check [this](https://stackoverflow.com/a/54738425/14629458) answer if you have to keep it a `TreeSet` – Yasser CHENIK Aug 12 '22 at 19:35
  • Can't i modify the Comparator in a way that makes this work? – nullPointer Aug 12 '22 at 19:38
  • Poor title. Rewrite to summarize your *specific* technical issue. – Basil Bourque Aug 12 '22 at 20:31

2 Answers2

2

You could change the comparator to something like:

static Comparator<String> comparator = Comparator.comparing(String::length)
                                                 .thenComparing(Comparator.naturalOrder());
Eritrean
  • 15,851
  • 3
  • 22
  • 28
1

Like someone said, a set doesn't allow duplicates. In your case, since you are using the length of the string, you may have strings that have the same length.

But here's an example of using a comparator with TreeSet.

import java.util.*;
public class Main {
   public static void main(String[] args) {
      Set<String> buch = new TreeSet <>((s1,s2)->s1.length()-s2.length());
      buch.addAll(List.of("a", "test", "ab", "cd", "z", "lol", "aaa"));
      buch.forEach(System.out::println);
    }
}
Cheng Thao
  • 1,467
  • 1
  • 3
  • 9