Home > Net >  How to rewrite a Java program using Stream API methods, such as filter and map?
How to rewrite a Java program using Stream API methods, such as filter and map?

Time:01-29

I have a small program that iterates over an array of strings and then prints either true or false depending whether the string from array is included into another string. How to rewrite this program using Stream API methods, such as filter and map?

    String mainString = new String ("qrfghjtysd");
    String container = new String ("qre fgh ty np");
    String[] smallStrings = container.split("\\s  ");
    StringBuilder res = new StringBuilder();
    Arrays.stream(smallStrings).  forEach(str -> {
        if (mainString.contains(str)) {
            res.append("true"   System.lineSeparator());
        }
        else {
            res.append("false"   System.lineSeparator());
        }
    });
    System.out.println(res);

CodePudding user response:

It seems like you want to transform each string s in the array to either "true" or "false" depending on mainString.contains(s), and then join them together with new lines as the separator. The transformation can be done with a map, and the joining can be done with the joining collector.

String res = Arrays.stream(smallStrings)
    .map(s -> Boolean.toString(mainString.contains(s)))
    .collect(Collectors.joining(System.lineSeparator(), "", System.lineSeparator()));

Like your original code, this adds a trailing new line to the resulting string. If you don't care about the trailing new line, you can just pass a single System.lineSeparator() argument to the joining collector, calling the other overload.

CodePudding user response:

I would suggest something like this:

final String mainString = "qrfghjtysd";
final String container = "qre fgh ty np";
final String res = Arrays.stream(container.split("\\s  "))
    .map(mainString::contains)
    .map(String::valueOf)
    .collect(Collectors.joining(System.lineSeparator()));
System.out.println(res);

CodePudding user response:

String mainString = new String ("qrfghjtysd");
String container = new String ("qre fgh ty np");
String[] smallStrings = container.split("\\s  ");
StringBuilder res = new StringBuilder();
Arrays.stream(smallStrings).map(str -> mainString.contains(str)).forEach(flag -> res.append(flag   System.lineSeparator()));
System.out.println(res);

CodePudding user response:

try use "anyMatch":

String mainString = new String ("qrfghjtysd");
String container = new String ("qre fgh ty np");

boolean result = Arrays.stream(container.split("\\s  "))
                .anyMatch(s -> s.equals(mainString));
  • Related