我有一个ArrayList>>,它保存某些键值条目。类似:-
ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String,String>>();
HashMap<String,String> map = new HashMap<String,String>();
map.put("NewId", newId);
map.put("Title", title);
map.put("Description", description);
mList.add(map);
MyList myList = new MyList(mList);
itemsAdapter = new LazyAdapter(myContext, myList);
newList.setAdapter(itemsAdapter);
对于多个条目,"NewId"可以是相似的。
此外,我有一个颜色阵列:-
String[] colors = new String[]{"#1F1A17", "#62934D", "#F9B03F", "#7959BC", "#74B8DE", "#E65641", "#7CC8BB", "#D7CE5D", "#D6BE95", "#B694D1"};
我想要一个新的组,将所有具有相同"NewId"的条目放在一起,并为它们分配第一种颜色,其他具有下一个类似"NewId"的条目分配第二种颜色,以此类推,直到具有前10个相同"NewId"的条目被分配各自的颜色。
例如:-分组之前
NewId Title Description
101 title1 des1
102 title2 des2
103 title3 des3
101 title4 des4
102 title5 des5
103 title6 des6
分组后,
NewId Title Description
101 title1 des1 ------> color1
101 title4 des4 ------> color1
102 title2 des2 ------> color2
102 title5 des5 ------> color2
103 title3 des3 ------> color3
103 title6 des6 ------> color3
我已经做了什么:-
public class MyList {
private ArrayList<HashMap<String, String>> list = new ArrayList<>();
public MyList(ArrayList<HashMap<String, String>> mylist)
{
this.list = mylist;
}
public boolean add(HashMap<String, String> map) {
return list.add(map);
}
public void setColor(String newId, String color) {
for (HashMap<String, String> m : list)
if (m.containsKey(newId))
m.put("color", color);
}
public String getGroupKey(String key, int i) {
ArrayList<String> uniqeList = getUniqKeyList(key);
Collections.sort(uniqeList);
return uniqeList.get(i);
}
public ArrayList<String> getUniqKeyList(String key){
ArrayList<String> l = new ArrayList<>();
for (HashMap<String, String> m : list)
if(!l.contains(m.get(key)))
l.add(m.get(key));
return l;
}
}
public static void main(String[] args) throws Exception {
MyList myList = new MyList();
HashMap<String,String> map = new HashMap<String,String>();
map.put("NewId", newId);
map.put("Title", title);
map.put("Description", description);
myList.add(map);
String[] colors = new String[]{"#1F1A17", "#62934D","#B694D1"};
int i=0;
while (true) {
if(i == colors.length)
break;
String s = myList.getGroupKey("NewId", i);
if(s == null)
break;
else
myList.setColor(s, colors[i++]);
}
}
itemsAdapter = new LazyAdapter(myContext, myList);
但我得到一个错误:-
04-24 04:57:49.993: E/AndroidRuntime(1882): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 4, size is 4
04-24 04:57:49.993: E/AndroidRuntime(1882): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
04-24 04:57:49.993: E/AndroidRuntime(1882): at java.util.ArrayList.get(ArrayList.java:304)
04-24 04:57:49.993: E/AndroidRuntime(1882): at Utility.MyList.getGroupKey(MyList.java:58)
try...
while (true) {
if(i >= colors.length)
break;
String s = myList.getGroupKey("NewId", i);
if(s == null)
break;
else
myList.setColor(s, colors[i++]);
}