Write a function which takes a list of strings and returns each line prepended by the correct number.
The numbering starts at 1. The format is n: string. Notice the colon and space in between.
Examples:
number(Arrays.asList()) # => []
number(Arrays.asList("a", "b", "c")) // => ["1: a", "2: b", "3: c"]
my solution according to: https://github.com/RomanBulinski/Testing1-2-3.git
|
|
||
import java.util.concurrent.atomic.AtomicInteger; |
||
| import java.util.stream.Collectors; | ||
| import static java.util.stream.Collectors.toList; | ||
| public class Main { | ||
| public static List<String> number(List<String> lines) { | ||
| AtomicInteger i = new AtomicInteger(1); | ||
| return lines.stream().map(e -> i.getAndIncrement() + ": " + e).collect(Collectors.toList()); | ||
| } | ||
|
} |
best practice:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class LineNumbering {
static List<String> number(List<String> lines) {
if (lines.size() == 0) return lines;
return IntStream.range(0, lines.size())
.mapToObj(n -> String.format("%d: %s", n+1, lines.get(n)))
.collect(Collectors.toList());
}
}
