Java integer, string array to repeat

Front often comma-parameters to the background, to be screened background operation duplicate values, and then filtered off operation

For integer array to an array of strings and weight, respectively, by the following ways:

  • An array of strings to heavy
    //字符串去重
    public String distinctString(String str) {
	   String[] array = str.split(",");
    	   List<String> list = new ArrayList<String>();  
		for(int i=0;i<array.length;i++){  
		    for(int j=i+1;j<array.length;j++){  
		        if(array[i].equals(array[j])){  
		            j = ++i; 
		        }  
		    }  
		    list.add(array[i]);  
		}
	   String newStr="";
	   for(String s:list){
	     newStr=newStr+s+",";
	   }
	   return newStr;
    }
  • Integer array deduplication

1. List interface:

int[] attr = { 1, 2, 3, 3, 5, 5, 7, 9 };
List<Integer> list = new ArrayList<Integer>();
for (int i : attr) {
   if (!list.contains(i)) {//boolean contains(Object o):
	   list.add(i);
   }
}
System.out.println(list);

2. Set interface:

int[] attr = { 1, 2, 3, 3, 5, 5, 7, 9 };
List<Integer> list = new ArrayList<Integer>();
for (int i : attr) {
    list.add(i);
}
Set<Integer> set = new HashSet<Integer>();
set.addAll(list);
System.out.println(set);


 

Guess you like

Origin blog.csdn.net/m0_37787662/article/details/92574900