Java 过滤器和拆分阵列列表
在我的程序中,我有一个Java 过滤器和拆分阵列列表,java,arraylist,Java,Arraylist,在我的程序中,我有一个事件数组列表。以下是我的代码摘录: ArrayList<Event> events; public class Event { // with getter and setter - don't write it down to keeps this short protected int day, month, year; } public static void main(String args[]) { events = new
事件数组列表
。以下是我的代码摘录:
ArrayList<Event> events;
public class Event
{
// with getter and setter - don't write it down to keeps this short
protected int day, month, year;
}
public static void main(String args[])
{
events = new ArrayList<Event>();
// fill list with items
HashMap<String, ArrayList<Event>> map = orderEvents(3, 2014);
// some more code
}
private HashMap<String, ArrayList<Event>> orderEvents(int month, int year)
{
// should return all events from the given month and year in a HashMap
// HashMap has this format: key = day | value = events of this day
}
ArrayList事件;
公开课活动
{
//有了getter和setter,不要把它写下来以保持简短
保护整数日、月、年;
}
公共静态void main(字符串参数[])
{
事件=新的ArrayList();
//用项目填充列表
HashMap=orderEvents(2014年3月);
//还有代码吗
}
私有HashMap orderEvents(整数月、整数年)
{
//应在HashMap中返回给定月份和年份的所有事件
//HashMap的格式为:key=day | value=当天的事件
}
当然,现在我可以循环浏览整个列表并处理大量的if条件
,但我认为我没有最有效的解决方案,对于其他人来说,这将很难阅读。是否有一些方法可以用来过滤ArrayList或按其中对象的值拆分它们?以下是我的解决方案
public static class ListExtractor<K, V> {
List<V> list = new ArrayList<>();
public ListExtractor(List<V> list) {
this.list = list;
}
public Map<K, List<V>> extract(Extractor<K, V> extractor) {
Map<K, List<V>> res = new HashMap<K, List<V>>();
for (V v : list) {
K key = extractor.getKey(v);
if (!res.containsKey(key))
res.put(key, new ArrayList<V>());
res.get(key).add(v);
}
return res;
}
}
public static interface Extractor<K, V> {
public K getKey(V v);
}
这是输出
--> 1-3-2014, 1-3-2014,
--> 2-3-2014, 2-3-2014, 2-3-2014,
--> 26-2-2014, 26-2-2014, 26-2-2014,
--> 27-2-2014,
--> 28-2-2014, 28-2-2014,
你能说得更具体些吗?你想要实现什么?你需要这些if条件做什么?你是否试图根据事件类中的某个变量将ArrayList分解为几个ArrayList?是的,这是我的考虑哇,太好了。谢谢你的密码。这是一个非常完美的模板解决方案。
--> 1-3-2014, 1-3-2014,
--> 2-3-2014, 2-3-2014, 2-3-2014,
--> 26-2-2014, 26-2-2014, 26-2-2014,
--> 27-2-2014,
--> 28-2-2014, 28-2-2014,