我想獲取以2003(2003001和2003002) 開頭的數字并將它們放入另一個串列中。
public static void main(String[] args) {
String [] num = {"2012001", "2003001", "2003002"};
List<String> list = new ArrayList<String>();
for(String actualList : num) {
list.add(actualList);
}
}
uj5u.com熱心網友回復:
您可以使用 startsWith() 方法:
String[] num = {"2012001", "2003001", "2003002"};
List<String> list = new ArrayList<>();
for (String number : num) {
if (number.startsWith("2003")) {
list.add(number);
}
}
uj5u.com熱心網友回復:
除了@Adixe 迭代解決方案之外,您還可以通過流式處理陣列、過濾以開頭2003的元素并使用終端操作收集剩余元素來簡潔地實作這一點collect(Collectors.toList())。
String[] num = {"2012001", "2003001", "2003002"};
List<String> listNums = Arrays.stream(num)
.filter(s -> s.startsWith("2003"))
.collect(Collectors.toList());
uj5u.com熱心網友回復:
正如@Ole VV在評論中指出的那樣,您的陣列中的字串似乎由year like2012和day of the year like組成001。
如果是這樣,將這些資料轉換成匹配會LocalDate比使用它像普通字串一樣操作更方便。
要將這些行字串決議為LocalDate您需要DateTimeFormatter使用靜態方法創建一個ofPattern()。
與示例資料對應的字串模式如下:
yyyyDDD
y- 代表年份;
D- 一年中的一天。
有關更多資訊, 請參閱
因此,要過濾出具有特定年份的日期,首先我們需要LocalDate.parse()通過將字串和格式化程式作為引數傳遞來決議每個字串,然后通過應用從每個日期中提取年份:getYear()
String [] num = {"2012001", "2003001", "2003002"};
int targetYear = 2003;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyDDD");
List<LocalDate> dates = Arrays.stream(num)
.map(date -> LocalDate.parse(date, formatter))
.filter(date -> date.getYear() == targetYear)
.collect(Collectors.toList());
System.out.println(dates);
輸出:
[2003-01-01, 2003-01-02]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/486408.html
