[精讚] [會員登入]
381

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

你可能感興趣的文章

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

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

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

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

隨機好文

steps to pass-through usb smart card reader for virtualbox how to pass through usb-smart-card-reader from ubuntu host to virtualbox vm

repairing esxi guest system after power failure if centos7 guest system reboot failed after power failure

dealing with virtualbox installation on ubuntu 22.04LTS trouble shooting on virtualbox installation