[精讚] [會員登入]
360

a function which takes a list of strings and returns each line prepended by the correct number

Write a function which takes a list of strings and returns e

分享此文連結 //n.sfs.tw/15357

分享連結 a function which takes a list of strings and returns each line prepended by the correct number@der amateur
(文章歡迎轉載,務必尊重版權註明連結來源)
最後編修
2021-08-22 16:16:20 By
 

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.List;

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());
    }
}

 

 

 

 

END

你可能感興趣的文章

a function that takes an array of integers and a target then added any two equals the target Write a function that takes an array of numbers (integers fo

a function which takes a list of strings and returns each line prepended by the correct number Write a function which takes a list of strings and returns e

find all elements in listA belonging to each element of listB and to sum according to listA A bookseller has lots of books classified in 26 categories l

to implement a difference function, which subtracts one list from another and returns the result. Description: Your goal in this kata is to implement a differ

JAVA Maximum Length Difference You are given two arrays a1 and a2 of strings. Each string i

隨機好文

JIRA instance migration phase2: install node.js and chinese fonts install node.js to export PDF though BigPicture plugin

win11 keep restart automatically after shutdown how to prevent win11 OS keep restart after manual or remote shutdown