重新排序 LinkedHashSet

huangapple go评论89阅读模式
英文:

Re-sort a LinkedHashSet

问题

有一种方法可以对LinkedHashSet中的链接进行排序吗?我知道它会保留元素添加的顺序,但是否有一种方法可以对这些链接进行重新排序,就像对链表进行排序一样,并且仍然表现出HashMap的行为呢?

英文:

Is there a method to sort the links in a LinkedHashSet? I know it preserves order in which the elements were added, but is there a way to re-sort those links as if it were a linked list, and have it still exhibit HashMap behaviors?

答案1

得分: 1

很遗憾,由于sort()方法来自于List接口,而LinkedHashSet未实现该接口。它实现了Set -> Collection接口。

不过,有一个解决方法,您可以将数据放入ArrayList或LinkedList中,在那里对其进行排序,然后将它们放入LinkedHashSet,但此时顺序将会被排序。示例:

ArrayList<> list = ..<放入您的数据>..
list.sort(...); // 使用比较器
Set<> set = new LinkedHashSet(list);

结果将会是一个完全排序的LinkedHashSet

英文:

Unfortunately no, since sort() comes from List interface, which is not implemented by LinkedHashSet. It implements Set -> Collection interfaces.

But, there is a workaround, you can put data to ArrayList or LinkedList, sort it there and then put them to LinkedHashSet but now order will be sorted. Example:

ArraysList&lt;&gt; list = ..&lt;put_your_data_here&gt;..
list.sort(...); // with comparator
Set&lt;&gt; set = new LinkedHashSet(list);

As a result, you will have fully sorted LinkedHashSet.

答案2

得分: 0

方法 1: 将 LinkedHashSet 转换为 TreeSet 实现自然排序

步骤:

  • 创建新的 LinkedHashSet 对象
  • 将内容存储/添加到 LinkedHashSet
  • 创建新的 TreeSet 对象
  • 将 LinkedHashSet 的内容作为参数传递给 TreeSet 的互相转换构造函数
package in.cj.resources.collection;

import java.util.LinkedHashSet;
import java.util.TreeSet;

public class SortingLinkedHashSetUsingTreeSet {

    public static void main(String[] args) {

        // 创建 String 类型的 LinkedHashSet 对象
        LinkedHashSet<String> lhsCompanies =
                new LinkedHashSet<String>();

        // 向 LinkedHashSet 对象中添加元素
        lhsCompanies.add("Dutchview");
        lhsCompanies.add("Oracle");
        lhsCompanies.add("Microsoft");

        // 使用增强型 for 循环进行迭代
        System.out.println("插入顺序:"
                + " 迭代 LinkedHashSet\n");
        for (String company : lhsCompanies) {
            System.out.println(company);
        }

        // 将 LinkedHashSet 转换为 TreeSet
        TreeSet<String> tSet = new TreeSet<String>(lhsCompanies);

        // 使用增强型 for 循环进行迭代
        System.out.println("\n\n升序排序顺序:"
                + " 迭代 TreeSet\n");
        for (String company : tSet) {
            System.out.println(company);
        }
    }
}

方法 2: 将 LinkedHashSet 转换为 TreeSet 实现逆序排序

步骤:

  • 创建新的 LinkedHashSet 对象,将内容存储/添加到 LinkedHashSet
  • 创建新的 TreeSet 对象,并使用 Comparator 提供逆序排序逻辑
  • 使用 addAll() 方法将 LinkedHashSet 的内容添加到 TreeSet
package in.cj.resources.collection;

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

public class ReverseSortingLinkedHashSetUsingTreeSet {

    public static void main(String[] args) {

        // 创建 String 类型的 LinkedHashSet 对象
        LinkedHashSet<String> lhsCompanies =
                new LinkedHashSet<String>();

        // 向 LinkedHashSet 对象中添加元素
        lhsCompanies.add("Dutchview");
        lhsCompanies.add("Amazon");
        lhsCompanies.add("Google");

        // 使用增强型 for 循环进行迭代
        System.out.println("插入顺序:"
                + " 迭代 LinkedHashSet\n");
        for (String company : lhsCompanies) {
            System.out.println(company);
        }

        // 创建新的 TreeSet 对象并提供逆序排序逻辑
        TreeSet<String> tSet = new TreeSet<String>(
                new Comparator<String>() {

                    @Override
                    public int compare(String str1, String str2) {
                        return str2.compareTo(str1);
                    }
                });

        // 使用 addAll() 方法将 LinkedHashSet 的内容添加到 TreeSet 实现逆序排序
        tSet.addAll(lhsCompanies);

        // 使用增强型 for 循环进行迭代
        System.out.println("\n\n降序排序顺序:"
                + " 迭代 TreeSet\n");
        for (String company : tSet) {
            System.out.println(company);
        }
    }
}
英文:

You can achieve it in few ways.Sharing few which you can use

Way 1: Convert LinkedHashSet to TreeSet for natural-ordering

Steps:

  • Create new LinkedHashSet object
  • Store/add contents to LinkedHashSet
  • Create new TreeSet object,
  • Pass LinkedHashSet contents as argument to TreeSet’ inter-conversion constructor
package in.cj.resources.collection;
import java.util.LinkedHashSet;
import java.util.TreeSet;
public class SortingLinkedHashSetUsingTreeSet {
public static void main(String[] args) {
// creating LinkedHashSet object of type String
LinkedHashSet&lt;String&gt; lhsCompanies = 
new LinkedHashSet&lt;String&gt;();
// adding elements to LinkedHashSet object
lhsCompanies.add(&quot;Dutchview&quot;);
lhsCompanies.add(&quot;Oracle&quot;);
lhsCompanies.add(&quot;Microsoft&quot;);
// Iterating using enhanced for-loop
System.out.println(&quot;Insertion Order:&quot;
+ &quot; Iterating LinkedHashSet\n&quot;);
for(String company : lhsCompanies) {
System.out.println(company);
}
// convert LinkedHashSet to TreeSet
TreeSet&lt;String&gt; tSet = new TreeSet&lt;String&gt;(lhsCompanies); 
// Iterating using enhanced for-loop
System.out.println(&quot;\n\nAscending sorting-order:&quot;
+ &quot; Iterating TreeSet\n&quot;);
for(String company : tSet) {
System.out.println(company);
}
}
}

Way 2: Convert LinkedHashSet to TreeSet for reverse-ordering

Steps:

  • Create new LinkedHashSet object Store/add contents to LinkedHashSet
  • Create new TreeSet object and provide reverse-order sorting-logic
    using Comparator Add LinkedHashSet contents to TreeSet using
    addAll() method
package in.cj.resources.collection;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.TreeSet;
public class ReverseSortingLinkedHashSetUsingTreeSet {
public static void main(String[] args) {
// creating LinkedHashSet object of type String
LinkedHashSet&lt;String&gt; lhsCompanies = 
new LinkedHashSet&lt;String&gt;();
// adding elements to LinkedHashSet object
lhsCompanies.add(&quot;Dutchview&quot;);
lhsCompanies.add(&quot;Amazon&quot;);
lhsCompanies.add(&quot;Google&quot;);
// Iterating using enhanced for-loop
System.out.println(&quot;Insertion Order:&quot;
+ &quot; Iterating LinkedHashSet\n&quot;);
for(String company : lhsCompanies) {
System.out.println(company);
}
// create new TreeSet object and provide reverse-sorting logic
TreeSet&lt;String&gt; tSet = new TreeSet&lt;String&gt;(
new Comparator&lt;String&gt;() {
@Override
public int compare(String str1, String str2) {
return str2.compareTo(str1);
}
}); 
// add LinkedHashSet to TreeSet for reverse-sorting elements
tSet.addAll(lhsCompanies);
// Iterating using enhanced for-loop
System.out.println(&quot;\n\nDescending sorting-order:&quot;
+ &quot; Iterating TreeSet\n&quot;);
for(String company : tSet) {
System.out.println(company);
}
}
}

答案3

得分: 0

如果出于某种原因确实需要更新现有 LinkedHashSet 的顺序,并且无法创建新的有序集合,您可以创建一个数据的有序副本,清空原始集合,然后添加所有元素。

TreeSet<String> sortedCopy = new TreeSet<>(linkedHashSet);
linkedHashSet.clear();
linkedHashSet.addAll(sortedCopy);
英文:

If for some reason you really need to update an ordering of an existing LinkedHashSet and can't create a new ordered one, you could create a ordered copy of the data, clear the original set, then add all the elements.

TreeSet&lt;String&gt; sortedCopy = new TreeSet&lt;&gt;(linkedHashSet);
linkedHashSet.clear();
linkedHashSet.addAll(sortedCopy);

huangapple
  • 本文由 发表于 2020年4月10日 02:38:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61127999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定