Skip to main content

APIzation: Replication Package

[Q#27286953][A#27287021] How to get String[] A - String[] B i.e. all elements which are in A but not in B ,In java?

https://stackoverflow.com/q/27286953

I have a String [] allEmps ; String array Of All emps; I have another String [] EmpsWithCompensationDefined Now I want to get employees whom compensation is not defined i.e An entry which is in A but not in B. Solution : I can iterate over both the array and get the difference. But this would be O(n^2) complex. Is there any other way with less asymptotic complexity? Edit:

Answer

https://stackoverflow.com/a/27287021

You can try in this way

APIzation

String [] allEmps={"A","B","C","D"};
String [] listOfEmpsWithCompDefined={"A","D","E"};
Set<String> mySet1 = new HashSet<>(Arrays.asList(allEmps)); // convert to set
Set<String> mySet2 = new HashSet<>(Arrays.asList(listOfEmpsWithCompDefined));
mySet1.removeAll(mySet2);// elements which are in A but not in B 
String[] df = mySet1.toArray(new String[mySet1.size()]);// difference
package com.stackoverflow.api;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Human27287021 {

  public static String[] getEmpsWithoutCompDefined(
    String[] allEmps,
    String[] listOfEmpsWithCompDefined
  ) {
    Set<String> mySet1 = new HashSet<>(Arrays.asList(allEmps)); // convert to set
    Set<String> mySet2 = new HashSet<>(
      Arrays.asList(listOfEmpsWithCompDefined)
    );
    mySet1.removeAll(mySet2); // elements which are in A but not in B
    return mySet1.toArray(new String[mySet1.size()]); // difference
  }
}

package com.stackoverflow.api;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * How to get String[] A - String[] B i.e. all elements which are in A but not in B ,In java?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/27287021">https://stackoverflow.com/a/27287021</a>
 */
public class APIzator27287021 {

  public static String[] getString(
    String[] allEmps,
    String[] listOfEmpsWithCompDefined
  ) throws Exception {
    // convert to set
    Set<String> mySet1 = new HashSet<>(Arrays.asList(allEmps));
    Set<String> mySet2 = new HashSet<>(
      Arrays.asList(listOfEmpsWithCompDefined)
    );
    // elements which are in A but not in B
    mySet1.removeAll(mySet2);
    return mySet1.toArray(new String[mySet1.size()]);
  }
}