Group ArrayList of integers in sequence
Hi,
I have an ArrayList of integer values. These values are sorted in ascending order. Some of the values in the List may be in sequence and some may not. So the values in the List can look like this:
661, 662, 670, 683, 684, 708, 709, 710, 711.
I want to be able to "group" the numbers into separate arrays where :
array1 = {661, 662}
array2 = {670}
array3 = {683, 684}
array4 = {708, 709, 710, 711}
Here is a what I have tried so far but I still am nowhere near it I think. Any help is appreciated!
import java.lang.*;
import java.util.*;
publicclass GroupNumbers
{
publicstaticvoid main(String args[])
{
List numbers =new ArrayList();
numbers.add(661);
numbers.add(662);
numbers.add(670);
numbers.add(683);
numbers.add(684);
numbers.add(708);
numbers.add(709);
numbers.add(710);
numbers.add(711);
int size = numbers.size();
List[] lstNumbers =new ArrayList[size];
for(int k=0;k<size;k++)
lstNumbers[k] =new ArrayList();
int count = 1;
int currentNumber = 0;
int nextNumber = 0;
for(int i=0;i<size;i++)
{
currentNumber = Integer.parseInt(numbers.get(i).toString());
try{
nextNumber = Integer.parseInt(numbers.get(i+count).toString());
}
catch(Exception e){}
System.out.println("Current Number : " + currentNumber);
System.out.println("Add current channel to list");
System.out.println("Next Number : " + nextNumber);
System.out.println("Count : " + count);
lstNumbers[i].add(nextNumber);
if((nextNumber - currentNumber) == count)
{
System.out.println("Add " + nextNumber +" to list");
lstNumbers[i].add(nextNumber);
count++;
}
else
{
System.out.println("Create new list....break to out for loop");
count = 1;
}
}
for(int b=0;b<size;b++)
System.out.println("List size : " + b +" -> " + lstNumbers[b].size());
}
}
You can make a 2 dimensional data structure (e.g. array of an array or collection of a collection or combinations thereof). Or you can create another array or collection that stores the indexes of the 'main' array where the groups break/start anew.- Saish
I have created an array of ArrayLists that are to hold the contents of the grouped numbers.
int size = numbers.size();
List[] lstNumbers = new ArrayList[size];
for(int k=0;k<size;k++)
lstNumbers[k] = new ArrayList();
However, the problem I am having has to do with main for loop. Specifically with comparing the current number against the remaining contents of the list.>
In your loop, you are presumably iterating over the main list (not the one holding the indexes). That loop has a counter. We'll call that the main list index.
You then have your other list. What you want to do is keep a separate int variable, let's call this the position list index. It will start at zero. Grab the contents from the position list, that is the first main list index you will stop at. Once you encounter the stop, increment position list index. Fetch the next value. Repeat.
- Saish
> currentNumber = Integer.parseInt(numbers.get(i).toString());
Painful. Recall numbers is a list of Integers -- you don't have to convert them to strings and then parse the strings! Since you used autoboxing earlier (numbers.add(661)) I'm assuming you are using Java >= 1.5. Try this:
import java.util.*;
public class Grouper {
public static void main(String... args) {
List<Integer> data = new ArrayList<Integer>(Arrays.asList(661, 662, 670, 683, 684, 708, 709, 710, 711));
List<List><Integer>> result = group(data);
System.out.println(result);
}
static List<List><Integer>> group(List<Integer> data) {
List<List><Integer>> result = new ArrayList<List><Integer>>();
int lastInt = 0;
List<Integer> lastGroup = null;
for(int n : data) {
if (lastGroup == null || lastInt + 1 != n)
result.add(lastGroup = new ArrayList<Integer>());
lastGroup.add(lastInt = n);
}
return result;
}
}
Argh! The forum formatting code is mangling generics! It writes List<List><Integer>> where I wrote List lt List lt Integer gt gt
Message was edited by:
DrLaszloJamf
> Argh! The forum formatting code is mangling generics!> ...A couple of spaces will fix it:List< List<Integer> > result = new ArrayList< List<Integer> >();
Thanks DrLaszloJamf. Works a treat. Dukes awarded.
> Thanks DrLaszloJamf. Works a treat. Dukes awarded.Woohoo! I'm going shopping. Where's the rewards program page?
you could use arraylist of arraylist i.e., multi-dimensional arraylists :)
> you could use arraylist of arraylist i.e., multi-dimensional arraylists :)I'd rather keep the duke dollars in my wallet.
sure, no problem. they are all yours.i dont need any :)i just wanted to present another solution. that is all :)--Who needs gates in this free world... -- Anonymous
> i just wanted to present another solution. that is all :)Wasn't my reply #4, done with a list of lists? Are you suggesting something different?
ArrayList of ArrayList is similar to Lists of Lists, right? :)so, sure, yes in logicwise. but with a different data structure.
that is why dukes are yours. :)
> ArrayList of ArrayList is similar to Lists of Lists,
> right? :)
> so, sure, yes in logicwise. but with a different data
> structure.
No.List is an Interface, ArrayList is an implementation of List. Therefore an ArrayList of ArrayLists is a List of Lists.
As a general practice you should program against List instead of ArrayList.
sure, but what is wrong with using ArrayList instead of List?
I used the type List< List<Integer> > for the return type, for the sake of generality, but of course List is an interface. What I constructed was in fact a ArrayList< ArrayList<Integer> >. I could have just as easily constructed it as a LinkedList< LinkedList<Integer> >, right?
i agree, once i tried to use ArrayList of ArrayList and it was a mess.this codes looks neater. maybe, this is a better way to go but dont know about performance.
> sure, but what is wrong with using ArrayList instead> of List?Did you read what I posted?A List is an Interface. Programming against an interface will allow you to freely change the implementation.
zadoka at 2007-7-21 16:52:22 >

> i agree, once i tried to use ArrayList of ArrayList
> and it was a mess.
> this codes looks neater. maybe, this is a better way
> to go but dont know about performance.
I don't think you are getting the point.
1. Do you understand that List is an interface and ArrayList is not?
2. Do you understand what advantages there might be to having a method return a List as opposed to an ArrayList?(Even if the List is actually an ArrayList?)
3. Do you understand if you did create a List of Lists you would have to pick an implementation like Vector, LinkedList, or ArrayList?
zadoka at 2007-7-21 16:52:22 >

yes, i did. what could you possibly change in this case?
>> I don't think you are getting the point.
>
> 1. Do you understand that List is an interface and
> ArrayList is not?
> 2. Do you understand what advantages there might be
> to having a method return a List as opposed to an
> ArrayList?(Even if the List is actually an
> ArrayList?)
> 3. Do you understand if you did create a List of
> Lists you would have to pick an implementation like
> Vector, LinkedList, or ArrayList?
have you tried both and see any performance difference?
> have you tried both and see any performance> difference?You still aren't getting it. List is an interface that ArrayList implements. Do you understand what an Interface is?
zadoka at 2007-7-21 16:52:22 >

hi Zadok,-
just try the following cases and see it for yourself:
(would you mind stop saying "you are not getting it", we are not in playground like 4-5 years old kids, ok?)
one case with your "favorite" List of List (as interface). And, then, another case with directly (WITHOUT INTERFACE) using ArrayList of ArrayList.
Do these and get back to me, ok?
thanks
Those of us who do get it don't have to do that test. It will come out the same because it's the same implementation being run in both cases.
if you see big difference, please report it to Sun.is that clear? are you getting it?
ok, folks, no hard feelings here.if you dont wanna try it, that is of course ok.thanks
see you may have two things implemented but the performance might be different. this is my last post to this thread.thanks
> hi Zadok,-
> just try the following cases and see it for
> yourself:
> would you mind stop saying "you are not getting it",
> we are not in playground like 4-5 years old kids,
> ok?)
>
> one case with your "favorite" List of List (as
> interface). And, then, another case with directly
> (WITHOUT INTERFACE) using ArrayList of ArrayList.
>
> Do these and get back to me, ok?
> thanks
you are still not getting it (btw I am 4 and this is my playground)
A list is an interface; you can't create a List. You have to create an implementation of it. (ArrayList, Vector, LinkedList, etc.).You can't compare List's performance to ArrayList. That make no sense because List has no performance because it does nothing. An Interface is a contract not an implementation!
zadoka at 2007-7-21 16:52:22 >

>btw I am 4 and this is my playgroundYou type pretty well for a four-year-old. =)
> >btw I am 4 and this is my playground> > You type pretty well for a four-year-old. =)Well, I started at -7. With Filestream as my tutor, I have noticed a steady improvement.
zadoka at 2007-7-21 16:52:27 >

One time, I was driving home in the early evening and drivers coming the other way kept flashing their highbeams at me. I assumed they were trying to tell me my highbeams were on, which I knew was not true. So I was flashing my highbeams back at them and getting more and more pissed off. I was almost all the way home when I realized they were telling me to turn my headlights on. Of course, they should have been blinking their headlights, not flashing their highbeams, but it was still pretty embarassing how long it took me to get the message. I guess this guy is just going to have to drive into a tree before he realizes that we're talking about good object-oriented design, not performance.
it would be a waste not to respond to this nice and cool story.Dont you look at your front panel which shows whether your headlights are on or off. See, this makes a huge difference in this story.
sorry but when you make stories, pay attention to details.... like in (java) programming too.... :) [just to make this post related to this forum]
btw, flashing high-beams is much eaiser than turning off/on (blinking) your high beams.
and this comes from a person who does not have a driver's license....
i like smart and story-telling wise people :)
i think i will get tons of cruel and arrogant responses after these posts.
Are you still here? I did say it was early evening: it was still light enough that I could see the other cars and my dashboard without difficulty. And this was in Germany, where people actually learn how to drive before being issued licenses, including little details like this. It was other Americans who kept flashing me.
Did you read far enough to see the part about design vs. performance? Just curious.
i am not as smart as you are.