0

I have an array which shows the cities selected in database as cities=["1","3"] where 1 is Bombay and 3 is bangalore

Now while editing the user deselects Bombay and selects chennai, The new array is ["2","3"]

HTML:

<select name="cities">

<option value="1">Bombay</option>
<option value="2">Chennai</option>
<option value="3">Bangalore</option>
<option value="4">Delhi</option>
<option value="5">Calcutta</option>
</select>

How to get an array which contains the missing values(1) and an array for newly selected (2) so that when compared with selected array, if it is missing should update else should insert in database

2
  • 5
    Like a set difference? Commented Nov 19, 2014 at 6:39
  • yes should the get missing in one array and newly selected in one array and later if missing array then should update in database else insert Commented Nov 19, 2014 at 6:48

2 Answers 2

3

You can use guava libraries for getting the difference between the sets. What you can do is convert bothe the arrays to Set

new HashSet(Arrays.asList(array)); And similalarly for the sencond array as well

Then pass the Sets to guava difference method

public static Sets.SetView difference(Set set1, Set set2)

.If you don't want to use any 3rd party libraries, You can check out this question question

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

Comments

0
public class Main {

public static void main(String[] args) {
  final String[] arr1 = {"1", "3"};
  final String[] arr2 = {"2", "3"};
  List<String> missing = new ArrayList<String>(); // the missing vals
  List<String> have = new ArrayList<String>();    // the common vals
  List<String> newV = new ArrayList<String>();    // the new entries

  Set<String> aSet = new HashSet<String>(Arrays.asList(arr1));
  Set<String> bSet = new HashSet<String>(Arrays.asList(arr2));

  for (String s : aSet) {
    if (bSet.contains(s)) {
      have.add(s);
    } else {
      missing.add(s);
    }
  }

  for (String s : bSet) {
    if (!aSet.contains(s)) {
      newV.add(s);
    }
  }
}
}

3 Comments

can you tell me only using list instead of set
kindly help me doing using list alone
Just replace Set<String> aSet = new HashSet<String>(Arrays.asList(arr1)); with List<String> aSet = Arrays.asList(arr1); but this won't weed out the duplicates.

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.