2014-10-27 33 views
-2

我正在創建ObjectList的ArrayList,以便插入信息我在該類中使用了不同的構造函數,但是我有一個類型變量,每次構造函數調用時都會更新。這裏是我在做什麼在Java中從Map中找到每個類型的最高位

public class eProperty { 
    public String type = null; 
    public int marks; 
    public int code; 
    public String category 
    public String student_name = null; 
    public String employee_name = null; 
    public String o_name = null; 

    public eProperty(String type, String student_name, int marks) { 
     this.marks = marks; 
     this.type = type; 
     this.student_name = student_marks; 
    } 

    public eProperty(String type, String employee_name, int makrs, String category) { 
     this.marks = marks; 
     this.type = type; 
     this.employee_name = employee_name; 
     this.category = category; 
    } 
    public eProperty(String type, int code, int makrs, String o_name) { 
     this.marks = marks; 
     this.type = type; 
     this.mnc = code; 
     this.o_name = o_name; 
    } 
} 

我填充的ArrayList這樣,

ArrayList<eProperty> allData; 
eProperty data; 

if(type.equals("Student")) { 
    data = new eProperty(type, "John", 45) 
    allData.add(data) 
} 
if(type.equals("Employee")){ 
data = new eProperty(type, "Vicky", 86, "Developer") 
allData.add(data) 
} ... other cases also handled like this 

現在我想以檢索得分最高爲每種類型的,我堅持在這裏,任何幫助

感謝

+0

在你的arrayList上做一個循環,使變量(maxStu,max ...),檢查類型,比較,賦值...你卡在哪裏? – Kent 2014-10-27 16:39:41

+0

但我想避免循環和所有,沒有任何更清潔的方式,我試圖使用Map也不是很好 – user2323 2014-10-27 16:41:36

+1

如果您使用Java 8,您可以使用流。否則,你必須使用一個循環。 – 2014-10-27 16:43:02

回答

0

使用循環(對不起...)和PredicateApache Commons

public static int getHighestMarkByType(ArrayList<eProperty> allData, String type) { 

    Predicate predicate = new Predicate() { 
     public boolean evaluate(Object data) { 
      if ((eProperty) data).getType().equals(type)) { 
       return true; 
      } else { 
       return false; 
      } 
     } 
    }; 

    ArrayList<eProperty> filteredData = (ArrayList<eProperty>) CollectionUtils.select(allData,predicate); 

    int maxMarks = 0; 

    for (eProperty data : filteredData) { 
     if (data.getMarks() > maxMark) { 
      maxMarks = data.getMark(); 
     } 
    } 

    return maxMarks; 
} 
相關問題