How to join a String list to numbered string in Java and Kotlin

127 Views Asked by At

I have a String list like below.

[
    "Java",
    "Kotlin", 
    "Python"
]

Is there any way (in both Java and Kotlin) to get the final output as below using String.join() or any other simple way instead of using a loop and adding numbers manually?

"1. Java\n2. Kotlin\n3. Python"
1

There are 1 best solutions below

1
Sweeper On

In Java, if you don't want to write explicitly loops, there isn't much else to use other than streams. Since we can't keep track of an index if we loop over the strings, we have to stream over the indices of the list instead:

var list = List.of("Java", "Kotlin", "Python");
var result = IntStream.range(0, list.size())
    .mapToObj(i -> String.format("%d. %s", i + 1, list.get(i)))
    .collect(Collectors.joining("\n"));

I think that's not really a lot shorter than if you had done it with a loop.

var list = List.of("Java", "Kotlin", "Python");
ArrayList<String> resultList = new ArrayList<>();
for (int i = 0; i < list.size(); i++)
    resultList.add(String.format("%d. %s", i + 1, list.get(i)));
var result = String.join("\n", resultList);

In Kotlin on the other hand, there is mapIndexed which is designed for exactly this kind of situation:

val list = listOf("Java", "Kotlin", "Python")
val result = list.mapIndexed { i, s -> "${i + 1}. $s" }.joinToString(separator = "\n")