【问题标题】:Sort set with specific elements at beginning ascending在开始升序时具有特定元素的排序集
【发布时间】:2021-03-02 13:18:49
【问题描述】:

我有一组具有name 属性的对象。其中一些对象应该按升序显示在集合的开头,其余的也应该在开头的元素之后按升序排序。集合中的 cmets 是集合的内容。

这里有一些例子:

预期输出为("abc", "hello", "a", "c", "f", "test")

Set<Props> props = handler.getProps(); //("test", "abc", "c", "f", "hello", "a")
Set<Props> unnecessaryProps = handler.getUnnecessaryProps(); //("hello", "abc")

Comparator comparator = new Comparator<Props>() {

    @Override
    public int compare(Props e1, Props e2) {
        if (e1.equals(e2)) {
            return 0;
        }
        if (unnecessaryProps.contains(e1)) {
            return -1;
        }
        if (unnecessaryProps.contains(e2)) {
            return 1;
        }
        return e1.compare(e2);
        }
    };
}

谁能帮帮我?

【问题讨论】:

  • 这个比较器看起来不对:如果 e1 和 e2 都在不必要的属性中,它应该返回 0(或 e1.compare(e2))。

标签: java sorting set comparator


【解决方案1】:

TreeSet 有一个带有比较器参数的构造函数。您可以使用它来创建排序集。然后您可以将两个排序集添加到 LinkedHashSet 以保持正确的顺序。

  • 创建一组name 字段(unlist) 以通过unnecessaryProps 中的元素过滤props
  • 创建一个比较器cmp,通过name 字段比较PropsComparator.comparing(Props::getName)
  • 在构造函数中使用这个比较器创建两个TreeSets: new TreeSet&lt;&gt;(cmp)
  • 现在您有两个按名称排序的集合:[a, c, f, test][abc, hello]
  • 以正确的顺序将这两个集合添加到LinkedHashSet

Set<String> unlist = unnecessaryProps.stream().map(Props::getName).collect(Collectors.toSet());

Set<Props> output = new LinkedHashSet<>();
Comparator<Props> cmp = Comparator.comparing(Props::getName);

Set<Props> propstr = new TreeSet<>(cmp);
propstr.addAll(props.stream().filter(p -> !unlist.contains(p.getName())).collect(Collectors.toSet()));

Set<Props> unstr = new TreeSet<>(cmp);
unstr.addAll(unnecessaryProps);

output.addAll(unstr);
output.addAll(propstr);

System.out.println(output);

输出:

[abc, hello, a, c, f, test]

我假设Props 类有一个toString() 方法来打印name 值:

public class Props {
    // ...

    @Override
    public String toString() {
        return name;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2021-07-26
    相关资源
    最近更新 更多