String_diff () method in JAVA

1

In PHP there is the array_diff() method that checks values of two arrays and returns the items for the difference between them. For example:

$arrExclusion = array('as', 'coisas', 'acontece', 'no', 'tempo', 'certo');

$arr = array('tudo', 'as', 'coisas' 'acontece', 'me', 'é', 'no', 'lícito',
'mas', 'seu', 'nem', 'tudo', 'tempo', 'me', 'convém', 'certo' );

$new_array = array_diff($arr, $arrExclusion);

The values of array $new_array will be:

  

'everything', 'me', 'is', 'lawful', 'but', 'nor', 'everything', 'me'

Is there any method equivalent to array_diff() in JAVA? If so, which one? If not, how could I do this?

    
asked by anonymous 06.03.2017 / 02:08

2 answers

1

You can use the Commons Collections library the removeAll method of class < a collection of the elements of an array of another, coming from the following way:

List<String> arrExclusion = Arrays.asList("as", "coisas", "acontece", "no", "tempo", "certo");

List<String> arr = Arrays.asList("tudo", "as", "coisas", "acontece", "me", "é", "no", "lícito","mas", "seu", "nem", "tudo", "tempo", "me", "convém", "certo");

Collection<String> new_array = CollectionUtils.removeAll(arr, arrExclusion);

Generating the following result:

  

[everything, me, is, licit, but, your, nor, everything, suits me]

    
06.03.2017 / 18:36
0

Arrays do not have a diff method between arrays.

To do this we can do the following:

String[] s1 = {"ram", "raju", "seetha"};
String[] s2 = {"ram"};
List<String> s1List = new ArrayList(Arrays.asList(s1));
for (String s : s2) {
  if (s1List.contains(s)) {
    s1List.remove(s);
  }
  else {
    s1List.add(s);
  }
}

demo

described in the equivalent question in English: link

    
06.03.2017 / 17:02