想实现names中没有重复的元素这是自己写的一段代码,运行后仍旧有重复的元素,希望大家帮我指出错误!//删除重复的用户名
Set<String> names = new HashSet<String>();
List<String> sendUserNames = new ArrayList();
for(UserEvent ue : userEventByFeedIdList){
sendUserNames.add(ue.getSendUserName());
}
names.addAll(sendUserNames);
sendUserName = StringUtils.collToStr(names);
Set<String> names = new HashSet<String>();
List<String> sendUserNames = new ArrayList();
for(UserEvent ue : userEventByFeedIdList){
sendUserNames.add(ue.getSendUserName());
}
names.addAll(sendUserNames);
sendUserName = StringUtils.collToStr(names);
解决方案 »
- JAVA聊天室--昨天通过的口令验证出问题了,时间快到了求救~~
- 怎么样可以让Java源文件和数据库可以直接被运行(类似.exe文件)
- 我想写个管理系统,如何代码实现,,面板左边用Jtree,我想和sql联结,面板右面有jtext,jbutton,ect..
- SWT:程序中开启了一个线程,要改变界面,抛出: org.eclipse.swt.SWTException: Invalid thread access
- jcombobox弹出颜色选择的问题。
- 帮偶看看这个程序有什么错误?
- 在问关于Thread.sleep的问题!
- JTree问题
- 在jpanel中用jfilechooser方法来获取图片怎么办?
- 关于环境变量设置问题
- 大神求助,算法问题
- 关于BOM的问题
names.addAll(sendUserNames);这段代码不可以么?
List<String> list = new ArrayList<String>();
list.add("123");
list.add("456");
list.add("123");
list.add("789");
System.out.println(list);
nameSet.addAll(list);
System.out.println(nameSet);输出:[123, 456, 123, 789]
[123, 456, 789]
或者你直接用names.add(ue.getSendUserName());放到Set里不也行吗,省的后面再addALl了
HashSet<String> hs = new HashSet<String>();
hs.add(new String("123"));
hs.add(new String("123"));
hs.add(new String("123"));
hs.add(new String("123"));
System.out.println(hs.size());
if(Collections.frequecy(list,元素)>1的时候说明元素重复,那就可以不必add了,所以在你循环后add进的新元素不久没有重复的了??) {
……………………
}
Set<String> names = new HashSet<String>();
for(UserEvent ue : userEventByFeedIdList) {
names.add(ue.getSendUserName());
}
sendUserName = StringUtils.collToStr(names);
Set<String> set = new HashSet<String>();
set.addAll(userEventByFeedIdList);
--这个set里面就没有重复的了。
然后把List集合一个个放入到新集合里
每次放入的时候判断新集合里是否有此元素
contains 方法