1

I am storing Identification addresses in my ArrayList. The problem is I am storing it repeatedly.

Here is the relevant code:

public void storeIDs(final String emailAddress) {
    SharedPreferences.Editor editor = context.getSharedPreferences("storeIds", MODE_PRIVATE).edit();
    IDAddresses.add(emailAddress);

    for(int i=0;i<IDAddresses.size();i++)
    {
        editor.putString("value"+i,IDAddresses.get(i));
    }
    editor.putInt("emailListSize",IDAddresses.size());
    editor.apply();
}

How do I check if the emailAddress already exists in the ArrayList IDAddresses and if it exists, then dont store it?

Daniel
  • 2,355
  • 9
  • 23
  • 30
MagdHo0506
  • 73
  • 8

5 Answers5

2

From what you described, Set is the datastructure you should choose.

  • Set will not store duplicated (equals() ) elements, so you don't have to check and add
  • If you need check if an element exists in your collection, a Hashtable based Set (E.g. HashSet) contains() O(1) will be faster than ArrayList.contains() O(n)
Kent
  • 189,393
  • 32
  • 233
  • 301
0
//use this :
if( !IDAddresses.contains(emailAddress) ){

    IDAddresses.add(emailAddress);

}

//instead of just this :
IDAddresses.add(emailAddress);
Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37
0
SharedPreferences sh = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);   
if(sh.Contains(IDAddresses.get(i)){//do nothing}
else editor.putString("value"+i,IDAddresses.get(i));
0

As @Kent suggested, you should use a Set for this.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

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

And then:

IDAddresses.add(emailAddress);

Another way to do this, which is not recommended but if you're going to use ArrayList anyways:

List<String> noDupes = Lists.newArrayList(Sets.newHashSet(IDAddresses));

Basically removes duplicates by converting the ArrayList into a HashSet. Uses Guava.

If you're using Java 8 you can also make use of lamdas:

List<String> noDupes= IDAddresses.stream().distinct().collect(Collectors.toList());
px06
  • 2,256
  • 1
  • 27
  • 47
0

Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:

 if (IDAddresses.contains(i)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}

I didn't tried this method.You have to use this method ArrayList.contains(desiredElement) for checking the value exists in arraylist or not.

Please go through this link Check if a value exists in ArrayList

Community
  • 1
  • 1
Prabha Karan
  • 1,309
  • 3
  • 17
  • 35