Ikaros2205
Ikaros2205

Reputation: 21

Save Value to List from Stream

Currently im learning about stream and want to implement a method which accepts a string. The String starts with a certain word and ends with the same. The given example is "breadtunabread". The method return the word in between the bread.

public String getTopping(String s){
    Stream<String> stream = Stream.of(s);
    stream.filter(t -> t.startsWith("bread") && t.endsWith("bread")).
    forEach(t -> Stream.of(t.split("bread")[1]).collect(Collectors.toList()));
}

I'd like to either save it to a List or change it directly so it returns a String. Is it possible to get the first value from the stream and not use collect? I somehow made it work using forEach and adding the value to an ArrayList and returning it but i'd like to know whether there is a way to do it directly using the stream. Thanks in advance.

Upvotes: 1

Views: 1321

Answers (3)

Michael Kolbasov
Michael Kolbasov

Reputation: 21

And to return just a String:

public String getTopping(String s, String toReplace) {
    Stream<String> stream = Stream.of(s);
    return stream.filter(t -> t.startsWith(toReplace) && t.endsWith(toReplace))
            .findFirst()
            .map(t -> t.replaceAll(toReplace, ""))
            .orElseThrow(RuntimeException::new);
            //.orElseThrow(() -> new NoBreadException("s"));
}

Upvotes: 2

Jason
Jason

Reputation: 5246

Just like @Naman pointed out, you don't need a Stream for this. String#replaceAll will quite literally replace all instances of the String (bread) with empty String values and in the end you get you're topping. Added the base parameter in case you're a monster like me and eat cheese between pieces of ham.

    public static String getTopping(String value, String base) {
        return value.replaceAll(base, "");
    }
    String topping = getTopping("breadtunabread", "bread")

Assuming you have a List of items you want to get the toppings of.

        List<String> sandwhiches = Arrays.asList(
                "breadtunabread",
                "breadchickenbread",
                "breadcheesebread",
                "breadturkeybread",
                "breadlambbread"
        );

        List<String> toppings = sandwhiches.stream()
                .map(sandwhich -> getTopping(sandwhich, "bread"))
                .collect(Collectors.toList());

Result

[tuna, chicken, cheese, turkey, lamb]

Upvotes: 1

Anand Varkey Philips
Anand Varkey Philips

Reputation: 2075

Stream<String> stream = Stream.of("breadtunabread");
List<String> stringList =
    stream
        .filter(t -> t.startsWith("bread") && t.endsWith("bread"))
        .map(t -> (t.split("bread")[1]))
        .collect(Collectors.toList());

Is this what you are looking for? What others mentioned are correct that this is completely unnecessary. I posted this as you have mentioned that yuo are learning streams.

Upvotes: 1

Related Questions