0

The source code I have uploaded it will join some strings value in a one line. I want a way that I can able to skip a particular string in time of string joining. Here i have stored the strings "This","is","a","test." in a string array. I want that in time of joining a particular string will be skipped. Like I want to skip "a". How can I able to do in Java? I want a generalized way that I will able to apply for any strings.

import java.util.StringJoiner;
public class Test_Joiner_for_seatPlan
    {
    public static void main(String[] args)
        {
            StringJoiner joinString = new StringJoiner( " ");
            String[] testStringArray = {"This","is","a","test."};

            String joinedString = null;

            for(String s : testStringArray)
              {
                joinString.add(s);
              }

            joinedString = joinString.toString();

            System.out.println("After Joining the String:\n"+joinedString);
        }
    }
Black Swan
  • 813
  • 13
  • 35
  • 1
    by a conditional statement. – Stultuske Jan 12 '16 at 11:46
  • 2
    Some way other than `if (!s.equals("a"))` ? – khelwood Jan 12 '16 at 11:46
  • provide a `List` or `Map`(would be faster) of String that should be excluded and just check if the `List` contains the value or if the key for the `Map` has any value in your loop. – SomeJavaGuy Jan 12 '16 at 11:47
  • Question is somewhat related to http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array - at least for some extra reading material. – YoYo Nov 12 '16 at 17:16

5 Answers5

4

Try with not equal condition with string. but its not feasible as its check everytime a value.

for(String s : testStringArray)
{
  if(!s.equals("a")){
      joinString.add(s);
   }
}

If you have a list of values like a,b,c than you can do like this:

 Set<String> exclude =  new HashSet<String>(Arrays.asList("a","b","c"));
 for(String s : testStringArray)
    {
      if(!exclude.contains(s)){
          joinString.add(s);
       }
  }
bNd
  • 7,512
  • 7
  • 39
  • 72
  • 1
    You describe a repeated string comparison as "not feasible", but then repeatedly create an `Arrays.ArrayList`... – Andy Turner Jan 12 '16 at 11:55
  • yeah its true. but explaining way of conditional checking to OP. He may not know how to write condition!! thanks – bNd Jan 12 '16 at 11:56
  • There's nothing about it which is "not feasible". Also: it's more efficient to do contains on a `Set` (e.g. a `HashSet`) since it doesn't have to iterate all elements. – Andy Turner Jan 12 '16 at 12:00
  • @AndyTurner its true. updated answer thanks for feedback. – bNd Jan 12 '16 at 12:08
0

You can do it like this:
Code:

for(String s : testStringArray){ 
    if(!s.equals("a")){  // replace 'a' with the required character or word you want to ignore
       joinString.add(s);
    }
 }
Hamad
  • 5,096
  • 13
  • 37
  • 65
e.doroskevic
  • 2,129
  • 18
  • 25
0

One possible solution is to provide a Map or a List in which you store the String values that should get excluded in your join. Here is an example using a Map.

public static void main(String[] args) {
    String[] testStringArray = {"This","is","a","test."};
    Map<String, String> excludedStrings = createExcludingMap("a");
    System.out.println("After Joining the String:\n" + join(testStringArray, excludedStrings));
}

private static String join(String[] inputData, Map<String, String> excludedStrings){
    StringJoiner joinString = new StringJoiner( " ");

    String joinedString = null;

    for(String s : inputData)
    {
        if(excludedStrings.get(s) == null) // IF this return null, the String is not part of the Strings to be excluded, hence join the string
            joinString.add(s);
    }

    joinedString = joinString.toString();

    return joinString.toString();
}


private static Map<String, String> createExcludingMap(String... values) {
    Map<String, String> output = new HashMap<>();
    for(String s : values) { // Add each value to the map, with s as key
        output.put(s, s);
    }
    return output;
}

output :/

After Joining the String:
This is test.
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
  • Why use a `Map` (and `Map.get`) instead of a `Set` (and `Set.contains`)? – Andy Turner Jan 12 '16 at 12:19
  • Note that `Map` is not a `Collection`: it is part of the collections framework, but doesn't implement the `Collection` interface. – Andy Turner Jan 12 '16 at 12:21
  • Since bmt did already provide a solution i did not want to pick up the solution with a `Set` as well. Yeah i am going to change that wording for the collection. – SomeJavaGuy Jan 12 '16 at 12:36
  • I think that `Map` is not an appropriate choice for this problem - there is no key/value relationship needed, and makes the point of the code harder to understand. – Andy Turner Jan 12 '16 at 12:51
0

Use Split method of string. It returns array. combine each of them to get the string.

for (String retval: Str.split("a")){
         System.out.println(retval);
      }
guestdj
  • 56
  • 3
  • ur answer will just print the value, but what will happen when i want to store the value for further use.. – Black Swan Jan 12 '16 at 12:11
  • str[] st = new string[10]; str = Str.split("a"); . st contains strings without a. so append all using foreach loop and store in a string going through index of st. – guestdj Jan 12 '16 at 12:18
0

The StringJoiner is a utility class that was written specifically to be used with the new Java8 Stream functionality. The documentation of StringJoiner also refers to the Collectors.joining method. It creates the StringJoiner, and wraps it in an object suitable to pass to Stream.collect, actually a Collector.

As part of the Stream API we now also have direct support for filters, it is just a matter of employing the fluent API (fluent because we keep adding .something(...)) to add the .filter method.

You can use it as you did in your answer, but I would suggest doing it as follows:

import static java.util.stream.Collectors.joining;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class App {
  public static String joinString(String [] sa,Predicate<String> filter) {
    return Stream.of(sa).filter(filter).collect(joining(" "));
  }

  public static void main(String[] args) {
    String[] testStringArray = new String [] {"This","is","a","test."};
    System.out.println(joinString(testStringArray,(s)->!s.equals("a")));
  }
}

I have deliberately broken it up by defining an extra method, so you can see the type of the filter passed along, exposing the Predicate. This would also make your function a little more generic making it work as you stated: 'I want a generalized way that I will able to apply for any strings'.

However if the Stream api is flexible enough that I do not see any need to abstract your own API for it. I suggest using it as-is:

import static java.util.stream.Collectors.joining;
import java.util.stream.Stream;

public class App {
  public static void main(String[] args) {
    System.out.println(
      Stream
        .of(new String [] {"This","is","a","test."})
        .filter((s)->!s.equals("a"))
        .collect(joining(" "))
    );
  }
}

I could have written most of it on a single line, but I like to break it up for readability.

YoYo
  • 9,157
  • 8
  • 57
  • 74