【问题标题】:Replacing the places of the values using split and replace method使用拆分和替换方法替换值的位置
【发布时间】:2021-12-23 01:44:15
【问题描述】:

这是我的方法,它返回字符串值列表,如下所示:10x2021

这是我发送给我的方法的值。

 List<HistoryItem> historyItems = Arrays.asList
                (
                        new HistoryItem(364, "10x2021", Long.valueOf("009"))

                );



public static List<String> foo(List<HistoryItem> historyItems) {
    List<HistoryItem> collect = historyItems.stream().filter(item -> item.getCreditStatus().equals(Long.valueOf("009")) || item.getCreditStatus().equals(Long.valueOf("0010")))
            .collect(Collectors.toList());
    List<String> reportingPeriods = new ArrayList<>();
    for (HistoryItem historyItem : historyItems) {
        reportingPeriods.add(historyItem.getReportingPeriod());
    }

    return reportingPeriods;
}

我想要做的是我希望输出看起来像 2021-10 , 2021-9, not 10x2021 。我不能完全按照我的意愿使用字符串的方法。如何解决这个问题?

【问题讨论】:

  • 您能否将其简化为具体问题。你想把 10x2021 变成 2021-10 吗?这可以通过正则表达式或 String.split 来完成
  • 是的。我想转一下,最后加个逗号。

标签: java string methods split output


【解决方案1】:

这应该会为您解决问题:

List<String> reportingPeriods = historyItems.stream().map(hI -> { 
String[] splitted = hI.getReportingPeriod().split("x");
return splitted [1] + "-" + splitted [0]; }).collect(Collectors.toList());

【讨论】:

  • 我们忘记了一些东西,你能告诉我们如何在末尾加上逗号吗? @阿里·本·扎鲁克
  • 你的意思是像 2021-9, 2021-9, 2021-9 之类的东西?
  • 是的,我愿意。 2021-10 , 2021-9, 2021-8 像这样。
  • 您可以使用 String.join(",", reportingPeriods) 或使用 .collect(Collectors.joining(",")) 立即收集到加入的字符串,而不是收集到列表中收集到的字符串
  • String commaSeparatedPeriods = historyItems.stream().map(hI -> { String[] splitted = hI.getReportingPeriod().split("x"); return splitted [1] + "-" + 拆分 [0]; }).collect(Collectors.joining(","));
猜你喜欢
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
  • 2015-10-23
  • 2021-09-12
  • 1970-01-01
  • 2016-06-13
  • 2013-01-23
  • 1970-01-01
相关资源
最近更新 更多