reza_khalafi
reza_khalafi

Reputation: 6544

How to arrange array of objects with same property value?

I have an person model with two property like this:

int id;
String name;

and some object with this data:

person0 = {1,"James"};
person1 = {2,"James"};
person2 = {3,"James"};
person3 = {4,"Barbara"};
person4 = {5,"Barbara"};
person5 = {6,"Ramses"}; 

and array contain objects:

firstArray = [person0, person1, person2, person3, person4, person5]; 

Therefore how can have this array:

secondArray = [
   [person0, person1, person2],
   [person3, person4],
   [person5]
]

Thank you.

Upvotes: 4

Views: 51

Answers (2)

reza_khalafi
reza_khalafi

Reputation: 6544

Try this code in Java Android:

ArrayList<ArrayList<Person>> secondArr = new ArrayList<>();
        ArrayList<Course> tempArr = new ArrayList<>();
        for (int i = 0; i < firstArr.size(); i++) {
            if ((i + 1) >= firstArr.size()) {
                tempArr.add(firstArr.get(i));
                secondArr.add(tempArr);
            } else {
                if (firstArr.get(i).name .equals(  firstArr.get(i + 1).name) ) {
                    tempArr.add(firstArr.get(i));
                } else {
                    tempArr.add(firstArr.get(i));
                    secondArr.add(tempArr);
                    tempArr = new ArrayList<>();
                }
            }
        }

Finally secondArr prepared.

And if list not sorted we can use code like this:

for (int i = 0; i <firstArr.size() ; i++) {
  boolean isAdd = false;

  for (int j = 0; j < secondArr.size() ; j++) {
    if (secondArr.get(j).get(0).getName().equals(firstArr.get(i).getName())){
      secondArr.get(j).add(firstArr.get(i));
      isAdd =true;
      break;
    }
  }
  if (!isAdd){

    ArrayList<Person> arrayList = new ArrayList<>();
    arrayList.add(firstArr.get(i));
    secondArr.add(arrayList);

  }
}

Upvotes: 1

bvdb
bvdb

Reputation: 24730

If language does not matter.

map = new Map();    
for (persona of personas) {
  name = persona.name;
  arrayForName = map.get(name);
  if (arrayForName == null) {
    arrayForName = [];
    map.put(name, arrayForName);
  }
  arrayForName.put(persona)
}

The idea is to have a map (which is a collection key->value). The value of the map should in turn be an array.

To add elements efficiently, you iterate only once through the data, and add arrays each time a new key is discovered (i.e. the name).

In Java it would be something like:

Map<String, List<Persona>> map = new HashMap<>();    
for (Persona persona : personas) {
  String name = persona.getName();
  List<Persona> listForName = map.get(name);
  if (listForName == null) {
    listForName = new ArrayList<Persona>();
    map.put(name, listForName);
  }
  listForName.add(persona)
}

Upvotes: 1

Related Questions