Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add index number to each element in collection using FluentIterables in Guava

Tags:

java

guava

I have a list of String elements that i would like to transform using FluentIterables.transform. For the sake of the example let's say it is:

List<String> l = Arrays.asList("a", "b", "c");

Now I would like to add index number to each element so the result would be:

"0a", "1b", "2c"

Is there any way to acomplish this in nice way using Guava?

like image 683
Sebastian Avatar asked Jan 23 '26 12:01

Sebastian


1 Answers

FluentIterable.from(list).transform(new Function<String, String>(){
    private int ct = 0;
    @Override
    public String apply(String input){
        return ct++ + input;
    }

})

While this is easy, I wouldn't necessarily call it "nice", since it's a stateful function, whereas functions should usually be stateless. But it works well enough.

like image 188
Sean Patrick Floyd Avatar answered Jan 25 '26 02:01

Sean Patrick Floyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!