Skip to content

Instantly share code, notes, and snippets.

@bsharathchand
Last active August 29, 2015 14:26
Show Gist options
  • Save bsharathchand/3351c34b886eb31c6745 to your computer and use it in GitHub Desktop.
Save bsharathchand/3351c34b886eb31c6745 to your computer and use it in GitHub Desktop.
StringJoiner merge with different delimiters

StringJoiner class merge operation exampe

Merge 2 instance of StringJoiner will use the delimiters of both the instances.

    /**
     * Test of main method, of class StringJoinerSample.
     */
    @org.junit.Test
    public void mergingWithDifferentDelimiters() {
        System.out.println("main");
        final String[] pstStates = {"CA", "NV", "NB"};
        final String[] estStates = {"NY", "NJ", "FL"};

        StringJoiner instance1 = new StringJoiner(" AND ", "[", "]");
        StringJoiner instance2 = new StringJoiner(" OR ", "{", "}");
        Arrays.asList(pstStates).forEach(state -> instance1.add(state));
        Arrays.asList(estStates).forEach(state -> instance2.add(state));
      
        instance1.merge(instance2);

        final String expected = "[CA AND NV AND NB AND NY OR NJ OR FL]";
        final String actual = instance1.toString();
        System.out.println("Actual Output : " + actual);
        assertThat(actual, CoreMatchers.startsWith("["));
        assertThat(actual, CoreMatchers.endsWith("]"));
        assertEquals("Same delimiter should be used when merging.", expected, actual);
    }

Using StringJoiner#add method

     @org.junit.Test
    public void additionInsteadOfMerge() {
        System.out.println("main");
        final String[] pstStates = {"CA", "NV", "NB"};
        final String[] estStates = {"NY", "NJ", "FL"};

        StringJoiner instance1 = new StringJoiner(" AND ", "[", "]");
        StringJoiner instance2 = new StringJoiner(" OR ", "{", "}");
        Arrays.asList(pstStates).forEach(state -> instance1.add(state));
        Arrays.asList(estStates).forEach(state -> instance2.add(state));
      
        instance1.add(instance2.toString());

        final String expected = "[CA AND NV AND NB AND {NY OR NJ OR FL}]";
        final String actual = instance1.toString();
        System.out.println("Actual Output : " + actual);
        assertThat(actual, CoreMatchers.startsWith("["));
        assertThat(actual, CoreMatchers.endsWith("]"));
        assertEquals("Same delimiter should be used when merging.", expected, actual);
    }

Note : When using add instead of merge the prefix and suffix of the merged instance will be appended.

@0xae
Copy link

0xae commented Jul 31, 2015

UOU StringJoiner rocks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment