I have mList2 with values. There are values with the same id. How can I get a List or ArrayList in which objects with the same id are grouped and add it to mLists?
mList = ArrayList<DataPost>()
mLists = ArrayList<ArrayList<DataPost>>()
var f= mList2[0].ids_post
for ((b,o) in mList2.withIndex()){
if (o.ids_post.equals(f)){
mList.add(o)
}else{
mLists.addAll(listOf(mList))
mList.clear()
mList.add(o)
f = o.ids_post
}
}
The program below should meet your requirements.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String args[]) {
// Sample items
String arrId[] = { "India", "England", "France", "China", "India", "France", "India", "England", "Germany" };
List<String> mList2 = Arrays.asList(arrId);
// Output list
List<List<String>> output = new ArrayList<List<String>>();
// List to track items that have been already grouped
List<String> itemsAlreadyGrouped = new ArrayList<String>();
// Loop through all items in the sample list
for (int i = 0; i < mList2.size(); i++) {
// Temporary list to hold identical items
List<String> groupList = new ArrayList<String>();
// Reset the flag for each iteration
boolean groupCandidateFound = false;
// If the item at the current index is not found in the
// list to track items that have been already grouped
if (!itemsAlreadyGrouped.contains(mList2.get(i))) {
for (int j = 0; j < mList2.size(); j++) {
// If the item at the current index of
// the inner loop is the same as the
// item at the current index of the
// outer loop, add it to the temporary
// list and mark the flag true
if (mList2.get(i).equals(mList2.get(j))) {
groupList.add(mList2.get(i));
groupCandidateFound = true;
}
}
// If the flag is true
if (groupCandidateFound) {
itemsAlreadyGrouped.add(mList2.get(i));
}
}
if (groupList.size() > 0) {
output.add(groupList);
}
}
//Let's test the logic
for (List<String> group : output) {
System.out.println(group);
}
}
}
Output for the given sample of items:
[India, India, India]
[England, England]
[France, France]
[China]
[Germany]