[英]Is there a way to compare two Strings with each other using java streams?
[英]How to parse strings using streams or other better way?
我有一個 HashMap,我想將其中的數據轉換為 Response 對象。 是否可以實現下面的代碼,以更好、優化和更清晰的方式解析字符串? 可能正在使用流?
class Converter{
public static void main(String[] args) {
Map<String, Long> map = new HashMap<String, Long>();
map.put("111", 80) // first
map.put("1A9-ppp", 190) // second
map.put("98U-6765", 900) // third
map.put("999-aa-local", 95) // fourth
List<FinalProduct> products = new ArrayList<>();
for(String key : map.keySet()){
FinalProduct response = new FinalProduct();
String[] str = key.split("\\-");
response.id = str[0] //id is always present in key i.e 111, 1A9, 98U,999
if(str.length == 2) {
if(str.matches("-?\\d+(\\.\\d+)?");){ // check if is numeric
response.code = str[1]; // 6765
}
else{
response.city = str[1]; //ppp
}
}
if(str.length == 3){
response.client = str[1]; //aa
response.type = str[2]; // local
}
response.qty = map.get[key];
products.add(response);
}
}
}
class FinalProduct{
String id;
String city;
Long code;
String client;
String type;
Long qty;
// getters and setters
我看不到任何重大改進。 有幾點要點:
正則表達式不需要測試符號。 您已經在-
字符上進行了拆分,因此不可能在數字字段中使用減號。
考試
if(str.length == 3){
可能
else if(str.length == 3){
代碼中有很多樣式錯誤,我發現了一些編譯錯誤。 在要求我們提供代碼幫助之前,您應該已經對它們進行了糾正。
最后,流將無法完成此任務。 他們當然不會提高效率。
為了使您的代碼可重用,我建議創建一個FinalProduct
構造函數作為
FinalProduct(String key, Long value) {
String[] str = key.split("-");
this.id = str[0];
if (str.length == 2) {
if (str[1].matches("-?\\d+(\\.\\d+)?")) {
this.code = Long.parseLong(str[1]);
} else {
this.city = str[1];
}
} else if (str.length == 3) { // ELSE IF !!
this.client = str[1];
this.type = str[2];
}
this.qty = value;
}
然后你可以將它用作
List<FinalProduct> products = map.entrySet().stream()
.map(e -> new FinalProduct(e.getKey(), e.getValue()))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.