[精讚] [會員登入]
239

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

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

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

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

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

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

JIRA instance migration phase3: upgrading jira trying to upgrade jira from 7.6.1 to 8.x