简体   繁体   中英

Adding numbers to first element of arrayLists

Suppose you have an arrayList of arrayLists:

[[a,b,6],[a,b,7],[s,d,3]]

I want to add a number as an index starting from 0 in first place of every arrayList as long as the two first elements remains the same. When it doesn't, counting must start again from 0. So I expect as a result:

[[0,a,b,6],[1,a,b,7],[0,s,d,3]]

Any help is appreciated. Thanks

You can iterate and remember the first two elements each step:

List<List<Object>> listOfLists = ...
Object first = listOfList.get(0).get(0);
Object second = listOfList.get(0).get(1);
int count = 0;

for (List<Object> list : listOfList) {
    Object currFirst = list.get(0);
    Object currSecond = list.get(1);
    if (!currFirst.equals(first) || currSecond.equals(second)) {
        first = currFirst;
        second = currSecond;
        count = 0;
    }
    list.add (0, count);
    ++count;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM