Example CodeJavaTips

String Utility Methods: Merging two String arrays

1 Mins read

This is another simple Java String utility/util method, which can be used to merge two arrays of String values. This takes care of eliminating the duplicates and also does null checking. If you are dealing with multiple String arrays then it could be useful method.

/**
  * This String utility or util method can be used to merge 2 arrays of
  * string values. If the input arrays are like this array1 = {"a", "b" ,
  * "c"} array2 = {"c", "d", "e"} Then the output array will have {"a", "b" ,
  * "c", "d", "e"}
  * 
  * This takes care of eliminating duplicates and checks null values.
  * 
  * @param values
  * @return
  */
 public static String[] mergeStringArrays(String array1[], String array2[]) {
  if (array1 == null || array1.length == 0)
   return array2;
  if (array2 == null || array2.length == 0)
   return array1;
  List array1List = Arrays.asList(array1);
  List array2List = Arrays.asList(array2);
  List result = new ArrayList(array1List);  
  List tmp = new ArrayList(array1List);
  tmp.retainAll(array2List);
  result.removeAll(tmp);
  result.addAll(array2List);  
  return ((String[]) result.toArray(new String[result.size()]));
 }
Related posts
KubernetesTips

3 Tips to Troubleshoot Readiness Probe Failed Errors Effectively : Kubernetes

4 Mins read
A Kubernetes readiness probe can improve your service’s quality and reduce operational issues, making your service more resilient and robust. However, the…
GadgetsSoftwareTechnologyTips

Is It good to Wear Eyeglasses for Software Engineers?

2 Mins read
As technology continues to be a fundamental tool in our day-to-day lives, we spend more time staring at digital screens. This may…
Tips

The 3 Things It Takes To Become A Digital Nomad

3 Mins read
There is so little reason to sit in a cubicle in an office that takes hours out of your day commuting to…
Power your team with InHype

Add some text to explain benefits of subscripton on your services.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *