我有一個陣列串列
[Type 1970, Type 1981, Type 1985, Type 1999]
[Type 1985, Type 1970, Type 1985, Type 1999]
[Type 1999, Type 1981, Type 1985, Type 1970]
[Type 1981, Type 1985, Type 1999, Type 1970]
[Type 1985, Type 1970, Type 1981, Type 1999]
我想拆分這些陣列,同時只提取特定的模型型別,例如“Type 1999”并提供計數。
這是我到目前為止想出的:
int counter = 0
for(int i = 0; i < listOfTypes.length; i ){
String[] typesSearch = listOfTypes[i]
if(typesSearch != null) {
if(typesSearch.equals("Type 1999")); {
counter ;
}
}
理想情況下,輸出將是一個只有特定元素的新陣列
{Type 1999, Type 1999, Type 1999, Type 1999} 等等
我想從這里我可以使用 length() 來計算這個新創建的陣列中的元素數
uj5u.com熱心網友回復:
我不知道你為什么想要那個;您當前的代碼運行良好且高效。
我想你可以這樣做:
int count = (int) Arrays.stream(listOfTypes)
.filter(x -> x.equals("Type 1999"))
.count();
如果您更喜歡這種風格,請盡情享受。性能明智和可讀性明智它真的沒有區別。然而,相對于僅以任何方式計數而言,僅使用Type 1999條目制作一個中間陣列是相當昂貴的。這也是更多的代碼。我不知道為什么你認為這是一個更好的解決方案。
uj5u.com熱心網友回復:
我猜你有二維陣列
String[][] listOfTypes = {
{"Type 1970", "Type 1981", "Type 1985", "Type 1999"},
{"Type 1985", "Type 1970", "Type 1985", "Type 1999"},
{"Type 1999", "Type 1981", "Type 1985", "Type 1970"},
{"Type 1981", "Type 1985", "Type 1999", "Type 1970"},
{"Type 1985", "Type 1970", "Type 1981", "Type 1999"}
};
并計算出現的次數 Type 1999
int counter = 0;
for (String[] typesSearch : listOfTypes) {
for (String str : typesSearch) {
if ("Type 1999".equals(str)) {
counter ;
}
}
}
或使用流
int counter = (int) Arrays.stream(listOfTypes)
.flatMap(typesSearch -> Arrays.stream(typesSearch))
.filter(str -> str.equals("Type 1999"))
.count();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351536.html
上一篇:如何使用變數和字串的混合標記Matplotlib圖?
下一篇:給出錯誤輸入時回圈?
