VRaj
VRaj

Reputation: 49

Java String utility/method to union two strings

Is there any helper method or utility that actually gives me union of two strings. For instance, if i have two strings as below:

String s1 = "Isabella,tom,hardy";
String s2 = "Isabella,tom,hardy,victor,smith";

I'm looking for a solution which will take above two strings as input and outputs the result as below:

General syntax:  s1.{method/utility}(s2);
output : Isabella,tom,hardy,victor,smith

Upvotes: 1

Views: 3111

Answers (9)

shmosel
shmosel

Reputation: 50726

Well, someone's got to provide a streams solution:

Stream.of(s1, s2)
        .flatMap(Pattern.compile(",")::splitAsStream)
        .distinct()
        .collect(Collectors.joining(","))

Upvotes: 0

Shafin Mahmud
Shafin Mahmud

Reputation: 4081

First, there is no method or utility provided by JDK to address the problem so straight forward.

Second, just for this simple utility importing a 3rd party jar or dependency is not a wise choice.

In this case its always a wise choice to write your own method of purpose.

public static String mergeString(String s1, String s2) {
        //check for null as the method doesnt fall in NPE
        if(s1 == null || s2 == null) {
            return null;
        }

        //split the given String to some list
        List<String> s1List = Arrays.asList(s1.split(","));
        List<String> s2List = Arrays.asList(s2.split(","));

        //get a Set and add the list items to it. LinkedHashSet
        //is used to maintain the given order.
        Set<String> stringSet = new LinkedHashSet<>(s1List);
        stringSet.addAll(s2List);

        //Then join them using java 8 provided Utility
        return String.join(",", stringSet);
    }

NB: as you mentioned in the comments you may need this type of utility only once in your project. But despite, this logic should be separated from out of your business method. This will make your code more clean and readable.

Upvotes: 6

Zia
Zia

Reputation: 1011

        String s1 = "Isabella,tom,hardy";
        String s2 = "Isabella,tom,hardy,victor,smith";
        Set<String> result = new TreeSet<String>();
        result.addAll(Arrays.asList(s1.split((","))));
        result.addAll(Arrays.asList(s2.split((","))));
        System.out.println(result);

Upvotes: 0

loadP
loadP

Reputation: 404

With the java api, you might try :

public class StringTest {

private String string1 ="";
private String string2 ="";
private List<String> array1 = new ArrayList<String>();
private List<String> array2 = new ArrayList<String>();
private String[] stringa1;
private String[] stringa2;
private int output3 = 0;
private int output4 = 0;

public static void main(String[] args) {
 new StringTest().startApp();
}

private void startApp() {
 string1 = "Isabella,tom,hardy";
 stringa1 = string1.split("\\s+"); //array to split

 string2 = "Isabella,tom,hardy,victor,smith";
 stringa2 = string2.split("\\s+");

 for(int o = 0; o<stringa1.length; o++) {
  array1.add(stringa1[o]);  //adding to arraylist
 }
 for(int o = 0; o<stringa2.length; o++) {
  array2.add(stringa2[o]);
 }

  for(int outP = 0; outP<array2.size()+array1.size(); outP++) {
  for(output4 = 0; output4<array2.size(); output4++) { //iterating and removing double elements 
   for(output3 = 0; output3<array1.size(); output3++) {
    if(array1.size() > array2.size() && array2.get(output4).equalsIgnoreCase(array1.get(output3))) {
     array1.remove(array1.get(output3));
    }
    if(array1.size() < array2.size() && array2.get(output4).equalsIgnoreCase(array1.get(output3))) {
     array2.remove(array2.get(output4));
    }
   }
  }
 }
 array1.addAll(array2); //merging the lists

 for(String outPres1 : array1) {
  result += " " + outPres1;
 } 
 System.out.println("This is the output: " + result);
}

Upvotes: 0

trappski
trappski

Reputation: 1060

A short version with no sanity checks using LinkedHashSet.

public void printUnion() {
    String s1 = "Isabella,tom,hardy";
    String s2 = "Isabella,tom,hardy,victor,smith";

    Set<String>mySet = new LinkedHashSet<>();
    mySet.addAll(Arrays.asList(s1.split(",")));
    mySet.addAll(Arrays.asList(s2.split(",")));
    mySet.stream().forEach(System.out::println);
}

Upvotes: 0

Michael Markidis
Michael Markidis

Reputation: 4191

Here's a method that will do the union of two strings. You can also pass it a boolean flag to dictate case sensitivity.

public static String union (String s1, String s2, boolean caseInsensitive)
{
    // if either string is null, union is the other string
    if (s1 == null)
        return s2;

    if (s2 == null)
        return s1;

    // use linked set to keep ordering
    Set<String> unique = new LinkedHashSet<>();

    // put all words from string 1 into the set
    for (String word : s1.split(","))
    {
        word = word.trim(); // remove surrounding space on word

        if (caseInsensitive)
        {
            word = word.toLowerCase();
        }
        unique.add(word);
    }

    // put all words from string 2 into the set
    for (String word : s2.split(","))
    {
        word = word.trim(); // remove surrounding space on word

        if (caseInsensitive)
        {
            word = word.toLowerCase();
        }
        unique.add(word);
    }

    // get back the format of comma delimiter for the union
    String ret = unique.toString().replaceAll("[\\[\\] ]", "");
    return ret;
}

Usage:

public static void main(String args[])
{   
    String s1 = "Isabella,tom,hardy";
    String s2 = "Isabella,tom,hardy,victor,smith";

    String union = union(s1, s2, false);
    System.out.println(union);
}

Outputs:

Isabella,tom,hardy,victor,smith

Upvotes: 1

Stamatia Ch
Stamatia Ch

Reputation: 104

public void unionString(String s1, String s2){

        String[] s1Ar = s1.split(",");
        String[] s2Ar = s2.split(",");

        HashSet<String> set = new HashSet<String>();

        for(int i=0;i<s1Ar.length;i++){
            set.add(s1Ar[i]);
        }

        for(int i=0;i<s2Ar.length;i++){
            set.add(s2Ar[i]);
        }

        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }  
    } 

Upvotes: 2

lihongxu
lihongxu

Reputation: 784

You can use org.springframework.util.StringUtils

Add a maven dependency spring-core:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.2.8.RELEASE</version>
</dependency>

Use StringUtils:

public static void main(String[] args) {
        String s1 = "Isabella,tom,hardy";
        String s2 = "Isabella,tom,hardy,victor,smith";
        String[] outputArr=StringUtils.mergeStringArrays(s1.split(","),s2.split(","));
        String output=StringUtils.arrayToCommaDelimitedString(outputArr);
        System.out.println(output);
    }

Output:

Isabella,tom,hardy,victor,smith

Upvotes: 2

pm dubey
pm dubey

Reputation: 1016

You Can Use LinkedHashSet which maintains the insertion Order to get desired output.Below is my code:

 public class UnionJava {
        static LinkedHashSet<String> hashSetString = new LinkedHashSet<>();
        static String s1 = "Isabella,tom,hardy"; static String s2 = "Isabella,tom,hardy,victor,smith";
        public static void main(String args[]){
            String[] set1 = s1.split(","); String[] set2 = s2.split(",");
            for(int i=0; i< set1.length;i++){
                hashSetString.add(set1[i]);
            }
            for(int i=0;i<set2.length;i++){
                hashSetString.add(set2[i]);
            }
            int j=0;
            for(Iterator i = hashSetString.iterator(); i.hasNext();){
                if(j==0){
                    System.out.print(i.next());
                    j++;
                }else{
                    System.out.print(","+i.next());
                }
            }
        }
    }

Upvotes: 1

Related Questions