首页 \ 问答 \ 排序Java集合(Sort Java Collection)

排序Java集合(Sort Java Collection)

我有一个Java集合:

Collection<CustomObject> list = new ArrayList<CustomObject>();

CustomObject在显示列表之前有一个id字段,我想通过该id对这个集合进行排序。

有没有办法我这样做?


I have a Java collection:

Collection<CustomObject> list = new ArrayList<CustomObject>();

CustomObject has an id field now before display list I want to sort this collection by that id.

Is there any way I could that do that?


原文:https://stackoverflow.com/questions/6957631
更新时间:2023-05-15 07:05

最满意答案

一种可能的方案:

dl.xpath('dt').each_with_index do |dt, i|
  dds = dt.xpath("following-sibling::dd[not(../dt[#{i + 2}]) or " +
                     "following-sibling::dt[1]=../dt[#{i + 2}]]")
  puts "#{dt.text}: #{dds.map(&:text).join(', ')}"
end

这依赖于dt元素的比较,并且当存在重复时将失败。 以下(更复杂的)表达式不依赖于唯一的dt值:

following-sibling::dd[not(../dt[$n]) or 
    (following-sibling::dt[1] and count(following-sibling::dt[1]|../dt[$n])=1)]

注意:您对self使用失败,因为您没有正确使用它作为轴( self:: 。 另外, self总是只包含上下文节点,因此它将引用由表达式检查的每个dd ,而不是返回到原始dt


One possible solution:

dl.xpath('dt').each_with_index do |dt, i|
  dds = dt.xpath("following-sibling::dd[not(../dt[#{i + 2}]) or " +
                     "following-sibling::dt[1]=../dt[#{i + 2}]]")
  puts "#{dt.text}: #{dds.map(&:text).join(', ')}"
end

This relies on a value comparison of dt elements and will fail when there are duplicates. The following (much more complicated) expression does not depend on unique dt values:

following-sibling::dd[not(../dt[$n]) or 
    (following-sibling::dt[1] and count(following-sibling::dt[1]|../dt[$n])=1)]

Note: Your use of self fails because you're not properly using it as an axis (self::). Also, self always contains just the context node, so it would refer to each dd inspected by the expression, not back to the original dt

相关问答

更多