How to remove duplicate Integer elements in array data structure in java

你离开我真会死。 提交于 2019-12-12 06:45:48

问题


Is there any simple way to remove duplicate elements in Java(will two loops work and how). Thank you:)

IN: int[] arr = {1,3,4,2,3,1,6,7,7};
Output i want is:
{1,3,4,2,6,7}

the only i know is we can traverse it through loop.
 eg.
  for(int i = 0;i < arr.length;i++){
   for(int j = 0;j<arr.length;j++){

        if(    ){
          //what logic i can apply here.      
          }
     }       
   }

回答1:


This should work..

final Integer[] noDuplicates =
    new LinkedHashSet<>(Arrays.asList(arr)).toArray(new Integer[0]);



回答2:


Java 8 provides a nice way to do this using IntStream.

arr = Arrays.stream(arr) // Convert arr to IntStream
        .distinct()      // Get distinct elements (preserves order)
        .toArray();      // Convert back to array



回答3:


You can try this way:

int[]arr = {1,3,4,2,3,1,6,7,7};
Set <Integer> set = new HashSet<Integer>();

for ( int w: arr) {
     set.add(w);
}



回答4:


i think this would be helpful

 public static int[] removeduplicate(int a[])
 {
    int count=0;
    for(int i=0;i<a.length;i++)
    {
         for(int j=i+1;j<a.length;j++)
         {
            if(a[i]==a[j])
            {
              a[j]=-1;
              count++;
            }
         }
     }
      int b[]=new int[a.length-count];
      for(int i=0;i<a.length;i++)
      {
            if(a[i]!=-1)
          {
              for(int j=0;j<(a.length-count);j++)
              {
                   b[j]=a[i];
              }
          }
     }
      return b;
 }



回答5:


You can use set data structure for removing duplicate elements from an array.

   int arr[] = {1, 6, 4, 7, 8, 4, 7, 9, 3, 8};

    Set<Integer> uniqueNumber = new HashSet<>();

    for(int i = 0; i < arr.length; i++) {
        //It only contains unique element
        uniqueNumber.add(arr[i]);
    }

For reference you can check this video tutorial https://www.youtube.com/watch?v=0HBIMjwte7s. I find it very helpful.




回答6:


First u cant change the existing array , so need a new array to hold his unique numbers, again as you dont know the number of element in advance better to use ArrayList rather array. If you dont want to write to much logic or less number of loops , u can try this.

int[] arr = {1,3,4,2,3,1,6,7,7};
        HashSet<Integer> hs = new HashSet<Integer>();
         ArrayList<Integer> unique=new ArrayList<Integer>();

        for(int num:arr){
            if(hs.add(num)){
                unique.add(num);
            }

        }


来源:https://stackoverflow.com/questions/36945065/how-to-remove-duplicate-integer-elements-in-array-data-structure-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!