如何将字段作为参数传递给方法呢?或者有更好的实现办法还请看看!
论文问答
1
背景:我有数据对象itemData,需求呢就是根据pw字段或者toa字段或者pa字段来统计,选出出现次数最多的那一组数据返回。
```java
public class ItemData{
public String type = "ini";
public double pw;
public int toa;
public double pa;
public boolean pwValid = true;
public int channel1;
public double fre1;
public int channel2;
public double fre2;
public int toaCnt;
}
-
// 接口定义 interface Selector{ int getProperty(ItemData itemData); } // 方法参数中传递接口参数 protected List<ItemData> findMostProperty(List<ItemData> list,Selector selector){ Map<Integer,Integer> propertyMap = new HashMap<>(); Map<Integer,List<ItemData>> propertyMapList = new HashMap<>(); for (ItemData itemData : list) { int propertyCache = selector.getProperty(itemData); propertyMap.put(propertyCache,propertyMap.getOrDefault(propertyCache,0)+1); List<ItemData> listCache = propertyMapList.getOrDefault(propertyCache,new ArrayList<>()); listCache.add(itemData); propertyMapList.put(propertyCache,listCache); } int maxFreCount = Collections.max(propertyMap.values()); int maxPropertyKey = 0; for (Integer key : propertyMap.keySet()) { if(propertyMap.get(key) == maxFreCount){ maxPropertyKey = key; break; } } Main.log("dual selector: Map:" + propertyMap); return propertyMapList.get(maxPropertyKey); } // 调用的时候使用lambda表达式 List<ItemData> mostProperty = dataFilterDual.findMostProperty(list, (itemData) -> (itemData.toa));
发表回复