Java高效遍历List<Map>并比对已知数据的优化方案咨询
Hey there! Let's clean up that repetitive code and make it both more maintainable and efficient. Your current implementation gets the job done, but all those nested if-else blocks are a pain to update and can slow things down as you add more coins. Here are a few practical approaches to refactor this:
1. Use a Map to Eliminate Coin-Based If-Else Checks
The biggest win here is replacing all those coin-specific if-else blocks with a Map that maps coin symbols to their current prices. This turns linear checks into O(1) lookups, which is faster and way easier to extend.
First, initialize a static map (so you don't recreate it every time):
// Initialize once as a class member private static final Map<String, Double> COIN_PRICE_MAP = new HashMap<>(); static { COIN_PRICE_MAP.put("BTC", BTC); COIN_PRICE_MAP.put("BCH", BCH); COIN_PRICE_MAP.put("ETH", ETH); COIN_PRICE_MAP.put("ETC", ETC); COIN_PRICE_MAP.put("LTC", LTC); COIN_PRICE_MAP.put("XRP", XRP); }
2. Extract Reusable Logic into a Helper Method
Next, pull the criteria and price comparison logic into a separate method. This eliminates duplicate code and makes your main loop much cleaner.
private boolean shouldTriggerNotification(double currentCoinPrice, double targetPrice, String criteria) { switch (criteria) { case "above": return currentCoinPrice > targetPrice; case "below": return currentCoinPrice < targetPrice; default: // Handle unknown criteria (log a warning if needed) return false; } }
3. Simplify the Main Loop
Now rewrite your loop to use the map and helper method. We'll also optimize the data extraction to avoid unnecessary toString() and Double.parseDouble() calls (casting directly to Number is faster):
boolean sendNotification = false; // Use enhanced for-loop for cleaner code (same performance as index-based for ArrayList) for (Map<String, Object> data : result) { double priceToCheck = ((Number) data.get("value")).doubleValue(); String criteria = (String) data.get("criteria"); String coin = (String) data.get("coin"); // Get the current price from our map (null if coin isn't supported) Double currentCoinPrice = COIN_PRICE_MAP.get(coin); if (currentCoinPrice != null && shouldTriggerNotification(currentCoinPrice, priceToCheck, criteria)) { // Create your notification here sendNotification = true; // If you need to send immediately per match, handle it here and reset sendNotification if needed } }
4. Bonus: Use a POJO for Type Safety & Faster Access
If you're working with this List<Map> frequently, converting it to a list of POJOs (Plain Old Java Objects) will eliminate repeated type casting and parsing, boosting efficiency further.
First, create a simple class to hold your data:
public class CoinAlertData { private final double value; private final String criteria; private final String coin; public CoinAlertData(double value, String criteria, String coin) { this.value = value; this.criteria = criteria; this.coin = coin; } // Getters public double getValue() { return value; } public String getCriteria() { return criteria; } public String getCoin() { return coin; } }
Then convert your List<Map> once (before processing):
List<CoinAlertData> alertDataList = result.stream() .map(map -> new CoinAlertData( ((Number) map.get("value")).doubleValue(), (String) map.get("criteria"), (String) map.get("coin") )) .collect(Collectors.toList());
Now your loop becomes even cleaner and faster:
boolean sendNotification = false; for (CoinAlertData alertData : alertDataList) { Double currentCoinPrice = COIN_PRICE_MAP.get(alertData.getCoin()); if (currentCoinPrice != null && shouldTriggerNotification(currentCoinPrice, alertData.getValue(), alertData.getCriteria())) { // Create notification sendNotification = true; } }
Why This Works Better
- Efficiency: Map lookups are O(1) vs. linear if-else checks, and reducing repeated parsing/casting cuts down on overhead.
- Maintainability: Adding a new coin only requires a single line in the
COIN_PRICE_MAPinitialization—no more copying and pasting if-else blocks. - Readability: The helper method and POJO make the logic clear at a glance, so you (or other devs) can quickly understand what's happening.
内容的提问来源于stack exchange,提问作者Mitchell D

