关于list中如何判断相同值的个数问题的最简单解法

Alex_20 2009-07-22 01:25:49
原帖地址:http://topic.csdn.net/u/20090717/16/a158c5b7-f6b1-40bb-9863-c892e1f767f1.html

代码如下:

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.TreeBag;

public class ApplicationRunner
{
public static void main( String[] args )
{
List < Integer > list = new ArrayList < Integer >();
Bag bag = new TreeBag( list );
Object[] values = bag.uniqueSet().toArray();
for( int i = 0 , count = values.length ; i < count ; i++ )
{
System.out.println( values[i] + "在List中存在" + bag.getCount( values[i] ) + "个" );
}
}
}


使用第三方开源组件5行代码搞定的事情不明白为啥弄的那么复杂,汗!
...全文
207 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Alex_20 2009-07-22
  • 打赏
  • 举报
回复
没事,兄弟。
Java的精华都在开源组件里了。
bigbug9002 2009-07-22
  • 打赏
  • 举报
回复
哦,我真的不知道你说的你那个第三方的组件的详细情况。我还以为楼主在寻求最短的代码呢。

我真心的向楼主道个歉。我太自以为是了。
Alex_20 2009-07-22
  • 打赏
  • 举报
回复
再补充一句
你最后的那句查找效率非常的低
System.out.println(i+" 在List中存在" + Collections.frequency(myList,i) + "个");
这句话要遍历整个List数组,你看下Bag的源代码就知道了。
Alex_20 2009-07-22
  • 打赏
  • 举报
回复
2楼的用法我也知道,但是实际使用就会有问题,你每次想知道某个对象在List里到底有多少个都需要做Set转换,这本身就是低效的。
Alex_20 2009-07-22
  • 打赏
  • 举报
回复
List里没数自己加上就是了。
一样的结果,Bag数据结构就是用来处理这个问题的,这个问题是典型的购物车问题,我个人感觉用Bag是语义最清晰的。
xinglongjian 2009-07-22
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 bigbug9002 的回复:]
Java codeimport java.util.*;publicclass Test2{publicstaticvoid main(String [] args) {
Integer[] arr={1,1,2,2,3,3,3,4,4};
List<Integer> myList=Arrays.asList(arr);
HashSet<Integer> hs=new HashSet<Integer>(myList);for(Integer i:hs){
System.out.println(i+" 在List中存在"+ Collections.frequency(myList,i)+"个");
}
}
}

不使用第三方开源组件,5行代码搞定的事情不明白为啥弄的那么复杂,汗!
结果如下:
F:\java>java Test2
1 在List中存在2个
2 在List中存在2个
3 在List中存在3个
4 在List中存在2个

不知道楼主和代码的结果是什么。
[/Quote]
顶一下。。。
bigbug9002 2009-07-22
  • 打赏
  • 举报
回复
不知道楼主代码的结果是什么。
bigbug9002 2009-07-22
  • 打赏
  • 举报
回复
import java.util.*; 
public class Test2{
public static void main(String [] args) {
Integer[] arr={1,1,2,2,3,3,3,4,4};
List<Integer> myList=Arrays.asList(arr);
HashSet<Integer> hs=new HashSet<Integer>(myList);
for(Integer i:hs){
System.out.println(i+" 在List中存在" + Collections.frequency(myList,i) + "个");
}
}
}


不使用第三方开源组件,5行代码搞定的事情不明白为啥弄的那么复杂,汗!
结果如下:
F:\java>java Test2
1 在List中存在2个
2 在List中存在2个
3 在List中存在3个
4 在List中存在2个

不知道楼主和代码的结果是什么。
bigbug9002 2009-07-22
  • 打赏
  • 举报
回复
你的list怎么是空的?

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧