Sorting a LinkedHashSet

后端 未结 4 1690
旧巷少年郎
旧巷少年郎 2020-12-20 11:24

I\'m wondering if it\'s possible to sort a LinkedHashSet. I\'ve tried the statement

Collections.sort((List paragraph);

Howeve

相关标签:
4条回答
  • 2020-12-20 11:51

    You can add LinkedHashSet object (linkedHashSet) to TreeSet and it will be sorted.

    TreeSet<T> treeSet = new TreeSet<t>();
    treeSet.addAll(linkedHashSet);
    

    treeSet is the sorted set.

    Note that you need to make these T type comparable(by implementing Comparator interface).

    0 讨论(0)
  • 2020-12-20 11:53

    You should use a SortedSet such as TreeSet or ConcurrentSkipListSet if you care about ordering based on comparison (e.g., sorted order).

    A LinkedHashSet preserves order based on insertion order.

    If you really want to use Collections.sort you can convert the LHS into a List by actually constructing a List (though the question doesn't tell us the type of paragraph so I'll assume it is String)

    List<String> listParagraph = new ArrayList<String>(paragraph);
    Collections.sort(listParagraph)
    

    but that's probably not the best approach.

    0 讨论(0)
  • 2020-12-20 11:54

    Yes, You can. Java 8 has made our life easier :)

    creating a linked list (it looks simple to me, you can directly insert in LinkedHashSet)

    LinkedList<String> lList = new LinkedList<String>();
    lList.add("Ravi");
    lList.add("Vijay");
    lList.add("Ravi");
    lList.add("Ajay");
    lList.add(null);
    
    LinkedHashSet<String> lHashSet = new LinkedHashSet<>();
    lHashSet.addAll(lList);
    

    let's sort now

    lHashSet.stream().sorted((String s1,String s2)->{       
        return s1.compareTo(s2);
    });
    
    //now print it
    System.out.println("----");
    lHashSet.forEach(action->{
       System.out.println(action);
    });
    System.out.println("----");
    

    Output-

    ----
    Ravi
    Vijay
    Ajay
    null
    ----
    

    Happy Coding :)

    0 讨论(0)
  • 2020-12-20 12:04

    Collections.sort does not work on Sets, only on Lists. If you need to sort the data that is already in a Set, you might want to first add them into a List.

    0 讨论(0)
提交回复
热议问题