java去除反复的字符串和移除不想要的字符串

在java开发中碰到了有些字符串是反复的,假设在进行业务处理要所有遍历太对的数据就会反复,所以在进行业务处理前进行一个去重操作。


这里因为业务须要所以先将字符串转化为string数组,使用split切割。然后将string数组一个个放到list里(list的remove能够将你不要的字符串删除掉。代參数的哦)

能够看到我使用的是list,在list里包括了一个contains函数,表示当前字符串是否与list里的元素有同样没有就add进list里

在最后还将list里的元素转化为string数组就将反复的字符串去除了,在最后使用了substring将字符串截取。在这里假设你的otherAppid太长的话会造成内存溢出,由于substring

的实现是先将字符串复制到还有一块内存。然后将字符串截取(这也是我看了支付宝的支付dom有个疑问然后查找资料得到的有兴趣的能够找下资料看下大笑)所以能够使用

int i=0;

if (i == newStr.length-1) {//拼接时,不包含最后一个,字符
otherAppid=otherAppid+commercial_account;
} else {
      otherAppid=otherAppid+commercial_account+",";
 }
i++;

推断下。

贴出代码

String otherAppid="";
String tmp="123,234,123,234,567,789,adb,asc,dcf,adb";
String[] commercial_accounts=tmp.split(",");


List<String> list = new ArrayList<String>();  
for (int i=0; i<commercial_accounts.length; i++) {  
System.out.print("commercial_accounts:"+commercial_accounts[i]);
System.out.print("\n");
if(!list.contains(commercial_accounts[i])){
       //去除反复的字符串
        list.add(commercial_accounts[i]);
 } 
}  
//list.remove(1);  去除不想要的字符串
String[] newStr =  list.toArray(new String[0]); //返回一个数组    

int i = 0;
for(String commercial_account:newStr){
//otherAppid=otherAppid+commercial_account+",";

if (i == newStr.length-1) {//拼接时。不包含最后一个,字符
otherAppid=otherAppid+commercial_account;
  } else {
      otherAppid=otherAppid+commercial_account+",";
}
i++;
}
System.out.print("otherAppid:"+otherAppid);
System.out.print("\n");
//otherAppid=otherAppid.substring(0,otherAppid.length()-1);
System.out.print("otherAppid:"+otherAppid);



posted @ 2017-06-08 18:57  zhchoutai  阅读(2019)  评论(0编辑  收藏  举报