Reputation: 27
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
Upvotes: 0
Views: 661
Reputation: 494
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);
}
}
}
}
Upvotes: 0
Reputation: 990
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
Upvotes: 3