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

StackOverflow https://stackoverflow.com/questions/22480230

  •  16-06-2023
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução 2

You can do this with a stateless transformation function if you start from the indices instead of the list elements. Here's an example with Java 8 streams:

List<String> list = Arrays.asList("a", "b", "c");
IntStream.range(0, list.size())
    .mapToObj(i -> i + list.get(i))
    .forEachOrdered(System.out::println); //or .collect(Collectors.toList()), ...

You can do the same with FluentIterable with a suitable index generator, such as ContiguousSet.create(Range.closedOpen(0, list.size()), DiscreteDomain.integers()).

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top