允许重复的TreeSet或TreeMap [英] A TreeSet or TreeMap that allow duplicates
问题描述
我需要一个集合
排序元素,但不会删除重复项。
I need a Collection
that sorts the element, but does not removes the duplicates.
TreeSet
。
c $ c>实际上将值添加到支持的
TreeMap
:
code> public boolean add(E e){
return m.put(e,PRESENT)== null;
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
TreeMap使用
/ code>
比较
逻辑
c $ c> Comparator 在等于元素的情况下返回1而不是0。
因此在等于元素的情况下, TreeSet
与此 Comparator
将不会覆盖重复,
I have written a Comparator
that returns 1 instead of 0 in case of equal elements.
Hence in the case of equal elements the TreeSet
with this Comparator
will not overwrite the duplicate and will just sort it.
我已经测试过简单的 String
对象,但我需要一组自定义对象。 / p>
I have tested it for simple String
objects, but I need a Set of Custom objects.
public static void main(String[] args)
{
List<String> strList = Arrays.asList( new String[]{"d","b","c","z","s","b","d","a"} );
Set<String> strSet = new TreeSet<String>(new StringComparator());
strSet.addAll(strList);
System.out.println(strSet);
}
class StringComparator implements Comparator<String>
{
@Override
public int compare(String s1, String s2)
{
if(s1.compareTo(s2) == 0){
return 1;
}
else{
return s1.compareTo(s2);
}
}
}
有更好的方法来实现这个?
Is this approach fine or is there a better way to achieve this?
EDIT
以下类的ArrayList:
Actually I am having a ArrayList of the following class:
class Fund
{
String fundCode;
BigDecimal fundValue;
.....
public boolean equals(Object obj) {
// uses fundCode for equality
}
}
我需要所有 fundCode
fundValue
I need all the fundCode
with highest fundValue
推荐答案
我需要所有fundCode具有最高fundValue
I need all the fundCode with highest fundValue
如果这是你想要排序的唯一原因,我会建议不要排序。排序主要具有 O(n log(n))的复杂性。找到最大值只有一个复杂的 O(n),并在您的列表上的一个简单的迭代实现:
If that's the only reason why you want to sort I would recommend not to sort at all. Sorting comes mostly with a complexity of O(n log(n)). Finding the maximum has only a complexity of O(n) and is implemented in a simple iteration over your list:
List<Fund> maxFunds = new ArrayList<Fund>();
int max = 0;
for (Fund fund : funds) {
if (fund.getFundValue() > max) {
maxFunds.clear();
max = fund.getFundValue();
}
if (fund.getFundValue() == max) {
maxFunds.add(fund);
}
}
第三级库,如 Guava 。请参阅:如何从List中获取max()元素
You can avoid that code by using a third level library like Guava. See: How to get max() element from List in Guava
这篇关于允许重复的TreeSet或TreeMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!