0

i am trying to remove duplicate values from my array present i my android project my array is,

String [] standard = {"7", "7", "8", "7", "8", "7", "6"};

i want only unique values that will be stored in an array.like {7, 8, 6}. i am trying to solev this with comparing each element of array with itself and then add it into array. i have tried googling to solve this but i am failed to solve this. means offcourse i am mistaking at somewhere.

how to solve this using the same way that i am trying to solve.

5

4 Answers 4

4

You haven't posted why you are using the array but one solution of the problem is to use set data structure. As follows. Set doesn't allow inserting duplicate values.

 Set<String> setExam = new HashSet<>();

  setExam.add("1");
  setExam.add("2");
  setExam.add("1");

you can also convert array to set as follows

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));

Set will contain only values 1 and 2. It will NOT contain duplicate values.

Sign up to request clarification or add additional context in comments.

1 Comment

@statosdotcom Glad I could help.
0

according to this link link

You can do it in one line in java 7:

String[] unique = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);

and shorter and simpler in java 8:

String[] unique = Arrays.stream(array).distinct().toArray(new String[0]);

1 Comment

What are you adding to Bohemian's answer ? You can flag for duplicate if you want (I think you have enough reputation) or comment with this answer link.
0
HashSet set=new HashSet();   
String [] standard = {"7", "7", "8", "7", "8", "7", "6"};
for(int i=0;i<standard.length;i++){
    set.add(standard[i]);
}
Iterator iter = set.iterator();
while(iter.hasNext()) {
    System.out.println(iter.next());
}

Comments

0

If you want to do this with the help of array only, you can use this.

1) Sort the string array.
2) Use another array to store ans.
3) Store first element of your standard array to new array.
4) Compare from second element of the array, and if two elements are different add that element to ans array.

See the code.

public static void main(String args[]) throws Exception
{       
    String [] standard = {"7", "7", "8", "7", "8", "7", "6"};

    System.out.println();

    Arrays.sort(standard);

    String Ans[] = new String[100];

    int k = 0;

    Ans[k++] = standard[0];

    for(int i = 1 ; i < standard.length ; i++)
    {
        if(!standard[i-1].equals(standard[i]))
            Ans[k++] = standard[i];
    }

    for(int i = 0 ; i < 100 && Ans[i] != null; i++)
        System.out.print(Ans[i] + " ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.