1

I have an ArrayList containing Objects, these objects have multiple values.

Now I would like to split up this list in to mulptiple lists depeding on an int value in the objects.

So if for example:

2 Objects have an int with value 1
3 Objects have an int with the value 3

So the arraylist has 5 objects, and I'd like to get:

2 Arraylists, 1 with the first objects en 1 with the second objects (more if there are more different int values)

Sorry if it is confusing..


First create a cache like this: Map<Integer, List<YourObjectType>>

Then cycle through each of your objects, and use your integer to access the above Map, if the value is null, create a new List and put it in the Map, then add your object to the List.

The end result would be a map with two entries, each containing a list of entries with the integer from your object being the discriminator.

Here's the code:

Map<Integer, List<YourObject>> cache = new HashMap<Integer, List<YourObject>>();
for (YourObject yo : yourObjectListArrayWhatever) {
  List<YourObject> list = cache.get(yo.getIntegerValue());
  if (list == null) {
    list = new ArrayList<YourObject>();
    cache.put(yo.getIntegerValue(), list);
  }
  list.add(yo);
} 
4

2 回答 2

7

首先创建一个这样的缓存:Map<Integer, List<YourObjectType>>

然后循环遍历您的每个对象,并使用您的整数来访问上面的Map,如果值为 null,则创建一个新对象List并将其放入Map,然后将您的对象添加到List.

最终结果将是一个包含两个条目的映射,每个条目都包含一个条目列表,其中来自您的对象的整数是鉴别器。

这是代码:

Map<Integer, List<YourObject>> cache = new HashMap<Integer, List<YourObject>>();
for (YourObject yo : yourObjectListArrayWhatever) {
  List<YourObject> list = cache.get(yo.getIntegerValue());
  if (list == null) {
    list = new ArrayList<YourObject>();
    cache.put(yo.getIntegerValue(), list);
  }
  list.add(yo);
} 
于 2013-03-21T12:27:31.963 回答
0

How do you store an int value in Object? I'm sure you have an implementation that is derived from Object and in that case you should use generecity at a lower point of the hierarchy.

Say you have a class Person with an int value and then subclasses Man extends Person and Woman extends Person and you populate this ArrayList with men and women, you would do so like so:

List<Person> pList = new ArrayList<Person>();

Now, in your Person class you should have a get-method for the int value. For example if the int value is the person's age:

public int getAge() { return age; }

Then, to finally answer your question I would go about like so:

List<Person> firstList = new ArrayList<Person>();
List<Person> secondList = new ArrayList<Person>();
for (Person person:pList) {
    if (person.getAge()==1) {
        firstList.add(person);
    }
    else if (person.getAge()==3) {
        secondList.add(person);
    }
}//for

I hope I answered your question adequately.

于 2013-03-21T12:37:41.190 回答