Filter duplicate data in List

 

1. Declare the List collection and put in the test data

List<String> list=new ArrayList<String>();
  list.add("Test");
  list.add("Test");
  list.add("Test2");
  list.add("Test2" );
  list.add("Test 2");
  list.add("Test 3");
  list.add("Test 3");
  list.add("Test 2");
  list.add("Test 1" );
  list.add("Test");
  list.add("Test");
  list.add("Test");
  list.add("Test");

2. Declare the Map object to store the filtered data
  Map map=new HashMap();
  Map<String,Integer> resultMap=new HashMap<String,Integer>();

3. Perform filtering and store the filtered data in resultMap
   for(String str:list){
   if(map.get(str)!=null){
    resultMap.put(str,resultMap.get(str)== null?2:resultMap.get(str)+1);
   }else{
    map.put(str,str);
   }
  }
  

4. Print the filtered data, format: "repetition information === number of repetitions"


  System.out.println("Repeat information === Repeat times");


  for(String str:resultMap.keySet()){
   System.out.println(str+"==="+resultMap.get(str));
  }

 

5. The results are as follows:

Repetition info === Repetitions
Test === 6
Test 3 === 2
Test 2 === 4

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326711215&siteId=291194637