簡體   English   中英

當 n > list index-1 時,打印字符串列表中前 n 個元素的計數器和字符串,使用默認值

[英]Print counter and string for first n elements from list of strings, with default value, when n > list index-1

我目前正在嘗試使用 Java 8 中的流,通過重寫一些代碼,我想到了以下情況。

  • 我有一個具有動態大小的字符串列表。
  • 我想打印出列表的前五個字符串,或者-如果列表大小小於五個,則作為所有剩余條目的默認值。
  • 打印的消息需要包含當前字符串的計數器。

因此,例如以下列表:

List<String> strings = Arrays.asList("one", "two");

應該打印出來:

1: one
2: two
3: -
4: -
5: -

到目前為止,我想出了以下解決方案:

// Iterating over the existing entries
int i = 1;
for (String string : strings) {
    System.out.println(i++ + ": " + string);
}

// Printing the default lines for all missing ones
IntStream.rangeClosed(i, 5).forEach(n -> System.out.println(n + ": -"));

不知何故,它感覺不那么干凈,因為我以同樣的方式使用System.out::println兩次。 有沒有一種更簡潔的方法可以重寫它,將所有內容都集中在一個流中?

怎么樣

IntStream.range(0, 5)
    .mapToObj(i -> String.format("%d: %s", i + 1, i < strings.size() ? strings.get(i) : "-"))
    .forEach(System.out::println);

這是在一個“循環”中完成的最優雅的方式。

無論數組的長度如何,您的行數始終為 5。 我們也不能只流過元素,因為我們還需要索引。 所以strings.stream()將不起作用,正如您已經發現的那樣。

我們改用IntStream::range來提供五個整數的使用。 然后我們將每個整數映射到相應的元素,或者-如果它超出范圍。 最后,我們使用方法引用打印整個內容。


我個人更喜歡使用原始索引(0 到 4)而不是基於 1 的索引(1 到 5)。 所以range(0, 5)而不是range(1, 6)rangeClosed(1, 5)

這是另一種簡單的方法:

    List<String> strings = Arrays.asList("one", "two", "three");
    Iterator<String> it = strings.iterator();

    for (int i=1; i<=5; i++){
        if (it.hasNext()) {
            String str = it.next();
            System.out.println(i + ": " + str);
        }else {
            System.out.println(i + ": -");
        }
    }

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM