I am doing homework. I would like to build a base case for a recursion where ordering given numbers (list2) in ascending order. Purpose of writing this codes is that when all numbers are in ascending order then should stop calling a method called ascending(list2, list1); and all values in list2 should be shipped to list1. For instance, list2 = 6,5,4,3,2,1 then list2 becomes empty and list1 should be 1,2,3,4,5,6. I am trying to compare result with previous one and if matches then stop. But I can't find the base case to stop it. In addition, Both ascending() and fixedPoint() are void method. Anybody has idea? lol Took me 3 days...
When I run my code then
6,5,4,3,2,1
5,6,4,3,2,1
4,5,6,3,2,1
3,4,5,6,2,1
2,3,4,5,6,1
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
1,2,3,4,5,6
infinite.............
public class Flipper
{
public static void main(String[] args)
{
Flipper aFlipper = new Flipper();
List<Integer> content = Arrays.asList(6,5,4,3,2,1);
ArrayList<Integer> l1 = new ArrayList<Integer>(content);
ArrayList<Integer> l2 = new ArrayList<Integer>(); // empty list
aFlipper.fixedPoint(l2,l1);
System.out.println("fix l1 is "+l1);
System.out.println("fix l2 is "+l2);
}
public void fixedPoint(ArrayList<Integer> list1, ArrayList<Integer> list2)
{
// data is in list2
ArrayList<Integer> temp1 = new ArrayList<Integer>(); // empty list
if (temp1.equals(list2))
{
System.out.println("found!!!");
}
else
{
ascending(list2, list1); // data, null
temp1 = list1; // store processed value
System.out.println("st list1 is "+list1);
System.out.println("st list2 is "+list2);
}
fixedPoint(list2, list1); // null, processed data
}
Second try after receiving advice.
else {
temp1 = list2;
System.out.println("temp1: "+temp1);
// temp1 printed out the value assigned
// store only previous value
ascending(list2, list1); // data, null
temp2 = list1;
// store previous value
System.out.println("temp1: "+temp1);
// after invoking ascending() temp1
becomes empty lol So not able to compare in if statement....
Can anybody correct it?
System.out.println("temp2: "+temp2);
}
fixedPoint(list2, list1); // previous, proceeded data
After brain storming with dasblinkenlight, Julien S, Nikolas, ZouZou and vels4j a solution found. I appreciate your contribution of thought! :-)
public void fixedPoint(ArrayList<Integer> list1,
ArrayList<Integer> list2)
{
List<Integer> content = Arrays.asList(1);
ArrayList<Integer> temp1 = new ArrayList<Integer>(content);
fixedPoint(list2, list1, temp1);
}
// Since it is recursive method I needed to create another parameter
// to store temporary values.
public void fixedPoint(ArrayList<Integer> list1,
ArrayList<Integer> list2,
ArrayList<Integer> temp)
{
ArrayList<Integer> temp1 = new ArrayList<Integer>();
temp1 = temp;
if (temp1.equals(list2))
{
return;
}
else
{
temp1.clear();
for(int i = 0; i < list2.size(); i++)
// To store temp value of list2,
// I used add method. Because ArrayList is an object type so if I assign
// list2 to temp1 then it will assign memory address rather
// than values. Thus I will lose the values after invoking ascending() as
// all elements of list2 will shipped to list1. So List2 becomes empty.
{
temp1.add(list2.get(i));
}
ascending(list2, list1);
fixedPoint(list2, list1, temp1);
}
}
Purpose of writing this codes is that when all numbers are in ascending order then should stop calling a method called ascending(list2, list1)
Then you should add a loop that checks for the elements of list1 to be in ascending order, like this:
public void fixedPoint(ArrayList<Integer> list1, ArrayList<Integer> list2)
{
boolean isAscending = true;
for (int i = 1 ; (isAscending) && (i < list2.size()) ; i++) {
isAscending = list2.get(i-1) < list2.get(i);
}
if (isAscending) {
... // Insert code to copy the data from list2 to list1.
... // Note that a simple assignment is not going to work here!
System.out.println("found!!!");
return;
}
// It's not in ascending order - continue recursing down.
ascending(list2, list1);
ArrayList<Integer> temp1 = new ArrayList<Integer>(list1); // store processed value
fixedPoint(list2, list1);
// temp1 makes the old value of list1 available for comparison
System.out.println("st list1 is "+list1);
System.out.println("st list1 was "+temp1);
System.out.println("st list2 is "+list2);
}
There is no return in fixedPoint when the case is found. Therefore the line fixedPoint(list2, list1);
will be processed regardless of the fixed point.
I am not able to test since ascending method is not provided, however I think that
if (CollectionUtils.isEqualsCollection(list1,list2)
{
System.out.println("found!!!");
return;
}
would do the job.
You will require Apache-commons Collections to perform the equality on lists with isEqualsCollection.
Your problem probably arises from the usage of temp1.equals(list2). What you want to use is Arrays.equals(temp1, list2).
An explanation for this is given here by Peter Lawrey.
Edit
Yeah, I should probably read better.
I just checked and it appears ArrayList inherits .equals() from List which is defined differently than array.equals() and "should" work.
Related
I've searched through many questions on this site with somewhat similar underlying concepts, however after many hours of attempting to solve this problem myself and reviewing I am still lost. If there is another question that answers this I will be more than happy to give it a look over.
Ultimately I want to create a recursive method such that it takes two lists and returns a Set of String lists:
//Example of such a function definition
private static Set<List<String>> myRecursiveMethod(List<String> listOne,
List<String> listTwo) {
}
When I say "Set of String lists" I mean specifically the following:
(Note:"AD" == "DA")
// if the two following lists are INPUTTED into myRecursiveMethod();
// listOne = ["A","B"]
// listTwo = ["C","D"]
// the following set is OUTPUTTED: [["AC","BD"],["AD","BC"]]
Such that if there were three elements in both listOne and listTwo, there would be SIX elements in the set. i.e:
// listOne = ["A","B","C"]
// listTwo = ["D","E","F"]
// OUTPUTTED: [["AD","BE","CF"],["AD","BF","CE"],["BD","AE","CF"],
// ["BD","AF","CE"],["CD","AE","BF"],["CD","AF","BE"]]
I tried writing this using a double enhanced FOR loop so I could understand the logic. My FOR loop approach is terrible and only works for the HARD-CODED limit of list.size() == 2.
// Create Lists and append elements
List<String> listOne = new ArrayList<String>();
listOne.add("A");
listOne.add("B");
List<String> listTwo = new ArrayList<String>();
listTwo.add("C");
listTwo.add("D");
// List One = ["A","B"]
// List Two = ["C","D"]
// Create new List
List<List<String>> newList = new ArrayList<List<String>>();
Integer counter = 0;
for (String s : listOne) {
counter++;
for (String p : listTwo) {
// A HARD-CODED bad implementation of this method
if (counter < 3) {
List<String> newListTwo = new ArrayList<String>();
newListTwo.add(s.concat(p));
newList.add(newListTwo);
} else if (!(counter % 2 == 0)) {
newList.get(1).add(s.concat(p));
} else {
newList.get(0).add(s.concat(p));
}
}
}
System.out.println(newList); // = [["AC","BD"],["AD","BC"]]
Also you can note that I defined List<List<String>> Rather than Set<List<String>>. This was due to my badly coded attempted which relies on the list.get() method.
So my current recursive method is as follows:
private static Set<List<String>> myRecursiveMethod(List<String> listOne,
List<String> listTwo)
{
//Base Case:
if (listOne.isEmpty){
return new HashSet<List<String>>;
}
//Recursive Case:
else {
String listOneFirst = listOne.get(0);
String listTwoFirst = listTwo.get(0);
List<String> sampleList = new ArrayList<String>();
sampleList.add(listOneFirst+listTwoFirst);
Set<List<String>> newSet = new HashSet<List<String>>(myRecursiveMethod())
newSet.add(sampleList);
return newSet;
}
}
This method only acts like this currently:
INPUT:
List One = ["A","B"]
List Two = ["C","D"]
OUTPUT:
[["AC"]["BD"]]
DESIRED OUTPUT:
[["AC","BD"],["AD","BC"]]
EDIT:
After reviewing responses my W.I.P code for the class:
private static Set<List<String>> myRecursiveMethod(List<String> listOne,
List<String> listTwo) {
//Backup Case (user enters an empty list)
if (listOne.isEmpty()){
return new HashSet<List<String>>();
}
// Base Case:
if (listOne.size() == 1) {
List<String> mergedStrings = new ArrayList<>();
for (String s : listTwo) {
mergedStrings.add(listOne.get(0).concat(s));
}
Set<List<String>> builtHashSet = new HashSet<List<String>();
builtHashSet.add(mergedStrings);
return builtHashSet;
}
// Recursive Case:
else {
// Ensure original list values arn't changed.
List<String> newListOne = new ArrayList<String>(listOne);
List<String> newListTwo = new ArrayList<String>(listTwo);
//first two elements...I don't think this is correct
String listOneFirst = newListOne.get(0);
String listTwoFirst = newListTwo.get(0);
List<String> sampleList = new ArrayList<String>();
sampleList.add(listOneFirst + listTwoFirst);
//used for making recursive case smaller
newListOne.remove(0);
// Calls recursion
Set<List<String>> newSet = new HashSet<List<String>>(
myRecursiveMethod(newListOne, newListTwo));
newSet.add(sampleList);
return newSet;
}
}
I think the problem is here:
if (listOne.isEmpty){
return new HashSet<List<String>>;
}
You are correct, at some point your recursion has to end, and you have to start building the desired output. But the desired output is not a Set with an empty list. It is a Set containing some lists with some content. Thus: don't wait until listOne is empty. Instead:
if (listOne.size() == 1) {
List<String> mergedStrings = new ArrayList<>();
mergedStrings = ... merge the ONE listOne entry with all listTwo entries
Set<List<String>> rv = new HashSet<>();
rv.add(mergedStrings);
return rv;
}
In other words: you use recursion to reduce the length of the first list by one. And when only one element is left in that list, it is time to merge in the second list.
Now lets look into how to "use" that (calling the method rec for brevity); putting down some pseudo code to show the steps we need:
rec([a, b], [c,d]) -->
rec([a], [c,d]) X rec([b], [c, d]) -->
<[ac, ad]> X <[bc, bd]> -->
<[ac, ad], [bc, bd]>
"X" meaning "joining" two results from recursive calls; should be as easy as:
Set<List<String>> rec1 = rec(...);
return rec1.addAll(rec2 ...
I am planning to write a Java Function that takes two linked lists. Both have the same size. I want to return a new list that contains the maximum of the data found in the corresponding nodes of the two lists passed to my function.
However I am stuck in filling the new list. I came up with this:
function max2List (LinkedList list1 , LinkedList list2) {
LinkedList <int> list3 = new LinkedList<int> ();
for (ListNode p = list1.first ; p!=null; p=p.next) {
for (ListNode p = list2.first ; p!=null; p=p.next) {
if (list1.p.data > list2.p.data ) {
//return list3 here with big value
else if (list1.p.data < list2.p.data ) {
//return list3 here with big value
I don't know how to continue. I want list3 to contain the maximum values from the two lists.
Firstly, what you have written is not valid Java. Generics cannot use primitive types, such as the use of <int> in your example. It needs to be a class e.g. <Integer>. function is also not a keyword.
For brevity, the following code assumes both lists are of equal size:
public static List<Integer> max2List (List<Integer> list1, List<Integer> list2)
{
List<Integer> maxValues = new LinkedList<>();
for (int i = 0; i < list1.size(); ++i)
{
// If item in list1 is larger, add it
if (list1.get(i).compareTo(list2.get(i)) > 0)
{
maxValues.add(list1.get(i));
}
else // else add the item from list2
{
maxValues.add(list2.get(i));
}
}
return maxValues;
}
def compare_lists(node_1, node_2):
while True:
if not node_1 and not node_2:
return 1
if (not node_1) ^ (not node_2):
return 0
if node_1.data != node_2.data:
return 0
node_1 = node_1.next
node_2 = node_2.next
What's the best way to compare the String elements of two List<List<String>>...
At the end, I want to know if they contain the same elements (true) or not (false)
This two lists I want to compare:
ObservableList<List<String>> fnlData = FXCollections.observableList(new LinkedList<>());;
List<List<String>> fnlDataTMP = new LinkedList<>();
I searched for already answered questions in the forum, but nothing helped me ..
Try fnlData.equals(fnlDataTMP) if both list are in order
or if order does not matter, try creating hash set and then compare using equals
new HashSet(fnlData).equals(new HashSet(fnlDataTMP))
I don't think there is a way that let's you achieve that out of the box.
You can do something like the functional java List.join method to quickly generate 2 Lists and compare these:
List<String> joinedFnlData = jf.data.List.join(fnlData);
List<String> joinedFnlDataTMP = jf.data.List.join(fnlDataTMP);
CollectionUtils.isEqualCollection(joinedFnlData, joinedFnlDataTMP);
Things to note:
This is probably not the cheapest operation - so it should not be invoked too often in a time critical scenario (e.g. UI thread)
It does not do a "real" equals - for that you would have to do a nested loop like in the above answer. This checks that both joined lists have the same elements with the same cardinality: e.g. if fnlData has 2 lists with "1" and "2" as the only elements and fnlDataTMP has 1 list with "1", "2" as the elements, this would mark both as equal. Depending on your scenario this might be irrelevant - if this is relevant I don't see a way around nested loops.
If by same elements you mean that the two lists are exacly the same but in a different order, then i suggest you sort the to lists and then compare them.
boolean isEqual(List<String> list1, List<String> list2) {
if (list1.size() != list2.size()) return false;
Collections.sort(list1);
Collections.sort(list2);
int i = 0;
for (String element : list1) {
if (!element.equals(list2.get(i))) return false;
i++;
}
return true;
}
I didn't test it yet!
For a Collections (Lists) to be equal, both need to be a proper subset of each other. Thus list1.containsAll(list2) and list2.containsAll(list1).
For a List within a List, you will have to loop, but that's essentially what any built-in library has to do anyway.
looks like you need a double iteration
boolean checkEqual(List<List<String>> l1,List<List<String>> l2){
if(l1.size() != l2.size()){
return false;
}
if(l1.hashCode() != l2.hashCode()){
return false;
}
for(int i=0; i<l1.size(); i++) {
List<String> curr = l1.get(i);
List<String> comp = l2.get(i);
if(curr.size() != comp.size()){
return false;
}
if(curr.hashCode() != comp.hashCode()){
return false;
}
for(int j=0; j<curr.size(); j++) {
if(!curr.get(j).equals(comp.get(j))){
return false;
}
}
}
return true;
}
You can improve the solution checking first difference of hashCode
if(l1.hashCode() != l2.hashCode()){
return false;
}
if hashCode are equal, then check eventually deep difference
I came up with a solution that doesn't need to have two inner loops by using Collections.sort(List list), which sorts a List in place, and List.containsAll(java.util.Collection), which compares two Lists for their elements.
Sample Code:
//Creating two lists for comparison and their inner lists
List<List<String>> list1 = new LinkedList<>();
List<List<String>> list2 = new LinkedList<>();
LinkedList<String> l11 = new LinkedList<>();
l11.add("a");
l11.add("b");
l11.add("c");
LinkedList<String> l12 = new LinkedList<>();
l12.add("d");
l12.add("e");
l12.add("f");
LinkedList<String> l21 = new LinkedList<>();
l21.add("b");
l21.add("c");
l21.add(new String("a"));
LinkedList<String> l22 = new LinkedList<>();
l22.add("d");
l22.add("e");
l22.add("f");
list1.add(l11);
list1.add(l12);
list2.add(l22);
list2.add(l21);
for (List<String> list : list1){
Collections.sort(list);
}
for (List<String> list : list2){
Collections.sort(list);
}
System.out.println(list1.containsAll(list2) && list2.containsAll(list1)); //prints true
If you don't want to change the order of the elements in the inner Lists you can create copies of the outer Lists and perform the operations on them.
Note: This only works for sortable collections.
Store one of the list in a HashMap and then iterate through the other list and check if the Map already contains that KEY. Ofcourse you have to ensure that KEY types match.
Hi and thanks for reading! I'm currently studying Generics in Java and this is what I'm trying to accomplish:
I need to delete duplicate elements from an ArrayList. Currently, the ArrayList contains integers. I want to first print the original list, and then print the resulting list after removing the duplicates. This is what I have so far. Any help is appreciated!
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(1);
list1.add(1);
list1.add(2);
list1.add(2);
list1.add(2);
list1.add(3);
list1.add(3);
list1.add(3);
removeDuplicates(list1);
System.out.println("Original List with Duplicates: \n" + list1);
System.out.println();
//System.out.println("After removing duplicates: \n" + list2);
}
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
for(int i = 0; i < list2.size(); i++){
//logic to remove duplicates
}
return list2;
}
You could add the elements to the Set collection. If you want to preserve order you should use LinkedHashSet
Step One
Convert your list to a set.
Set<Integer> aSet = new HashSet<Integer>(list);
Step Two
Convert your set back to a list.
list = new ArrayList<Integer>(new HashSet<Integer>(list));
Why it Works
Sets can only contain unique elements.
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
list1.add(1);
list1.add(1);
list1.add(1);
list1.add(2);
list1.add(2);
list1.add(2);
list1.add(3);
list1.add(3);
list1.add(3);
System.out.println("Original List with Duplicates: \n" + list1);
System.out.println();
list2 = removeDuplicates(list1);
System.out.println("After removing duplicates: \n" + list2);
}
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
ArrayList<E> usedList = new ArrayList<E>();
ArrayList<E> newList = new ArrayList<E>();
for(int i = 0; i < list2.size(); i++){
E object = list2.get(i);
if(! usedList.contains(object))
{
usedList.add(object);
newList.add(object);
}
}
return newList;
}
Output (as expected):
Original List with Duplicates:
[1, 1, 1, 2, 2, 2, 3, 3, 3]
After removing duplicates:
[1, 2, 3]
If you're working with other types (not java standard like int), then you have to override the equals method, because it's used in the ArrayList contains method.
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
LinkedHashSet<E> dataSet = new LinkedHashSet<E>(list2.size());
dataSet.addAll(list2);
ArrayList<E> uniqueLists = new ArrayList<E>(dataSet.size());
uniqueLists.addAll(dataSet);
return uniqueLists;
}
Convert the ArrayList to Set, maybe HashSet and then back to an ArrayList that you could sort if you want the numbers in order (the ordering in Sets are not usually not guaranteed).
HashSet hs<Integer> = new HashSet(list1);
ArrayList<Integer> uniqueList = Collections.sort(new ArrayList<Integer>(hs));
There's also various SortedSet, among them TreeSet.
Also, you can use a less error-prone for loop construction:
for (int i : uniqueList) {
System.out.println(i);
}
All the other answers so far create a new list. If you want to modify the list in place, you can iterate through the list while using an auxiliary Set to keep track of all elements already seen. The following works for any List (not just ArrayList) that allows elements to be removed:
public static <E> List<E> removeDuplicates(List<E> list){
ListIterator<E> iter = list.listIterator();
Set<E> seen = new HashSet<>();
while (iter.hasNext()) {
if (!seen.add(iter.next())) {
// element not added--must have already been seen, so remove element
iter.remove();
}
}
return list;
}
An alternative is to dump the entire list into a Set, clear the list, and then add all the element of the set back into the list. Depending on the Set implementation, this may or may not preserve order.
public static <E> List<E> removeDuplicates(List<E> list){
Set<E> unique = new LinkedHashSet<>(list);
list.clear();
list.addAll(unique);
return list;
}
EDIT: If (as per your comment) you wish to completely remove elements that are not unique to start with, you can modify the first approach:
public static <E> List<E> removeNonUnique(List<E> list){
Set<E> seen = new HashSet<>(); // all values seen
Set<E> dups = new HashSet<>(); // all values seen more than once
for (E elt : list) {
if (!seen.add(elt)) {
// element not added--must have already been seen, so add to dups
dups.add(elt);
}
}
// clean out the list
list.removeAll(dups);
return list;
}
Note that since we're not modifying the list during the loop, we don't need to have an explicit iterator.
I am fairly new to Java and I have stumbled across a problem I cannot figure out for the life of me. First let me explain what I am trying to do then I will show you the code I have so far.
I have a webservice that returns an array of arrays(which include company and lines of business strings). I wish to transform this into a string list, which I did in the first line of code below. Then I wish to Iterate through the list and every I come across a different value for company, I want to create a new ArrayList and add the associated line of business to the new list. Example output of webservice: 80,80,64,64 (this is presorted so the same companies will always be grouped together) the associated lobs would be 1,2,3,4 respectively. What I want: arraylist[0]: 1,2 arrayList[1]: 3,4
What I have so far:
List coList = Arrays.asList(coArray);
//create list of lists
List<List<String>> listOfLists = new ArrayList<List<String>>();
String cmp = "";
for (int i=0;i<coList.size();i++){//loop over coList and find diff in companies
String currentCo = ((__LOBList)coList.get(i)).getCompany();
String currentLob = ((__LOBList)coList.get(i)).getLobNum();
if(i<coArray.length-1){
String nextCo = ((__LOBList)coList.get(i+1)).getCompany();
if((currentCo.equals(nextCo))){
//do nothing companies are equal
}else{
log("NOT EQUAL"); //insert logic to create a new array??
ArrayList<String> newList = new ArrayList<String>();
// for(int j=0;j<coList.size();j++){
newList.add( ((__LOBList)coList.get(i)).getLobNum());
// }
for(int k=0; k<listOfLists.size();k++){//loop over all lists
for(int l=0;l<listOfLists.get(k).size();l++){ //get first list and loop through
}
listOfLists.add(newList);
}
}
}
}
My problem here is that it is not adding the elements to the new string array. It does correctly loop through coList and I put a log where the companies are not equal so I do know where I need to create a new arrayList but I cannot get it to work for the life of me, please help!
Yes you can do this but it's really annoying to write in Java. Note: This is a brain dead simple in a functional programming language like Clojure or Haskell. It's simply a function called group-by. In java, here's how I'd do this:
Initialize a List of Lists.
Create a last pointer that is a List. This holds the last list you've added to.
Iterate the raw data and populate into the last as long as "nothing's changed". If something has changed, create a new last.
I'll show you how:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
ArrayList<String> rawInput = new ArrayList<String>();
rawInput.add("80");
rawInput.add("80");
rawInput.add("60");
rawInput.add("60");
new Sandbox().groupBy(rawInput);
}
public void groupBy(List<String> rawInput) {
List<List<String>> output = new ArrayList<>();
List<String> last = null;
for (String field : rawInput) {
if (last == null || !last.get(0).equals(field)) {
last = new ArrayList<String>();
last.add(field);
output.add(last);
} else {
last.add(field);
}
}
for (List<String> strings : output) {
System.out.println(strings);
}
}
}
This outputs:
[80, 80]
[60, 60]
Of course, you can do what the other guys are suggesting but this changes your data type. They're suggesting "the right tool for the job", but they're not mentioning guava's Multimap. This will make your life way easier if you decide to change your data type to a map.
Here's an example of how to use it from this article:
public class MutliMapTest {
public static void main(String... args) {
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("Fruits", "Bannana");
myMultimap.put("Fruits", "Apple");
myMultimap.put("Fruits", "Pear");
myMultimap.put("Vegetables", "Carrot");
// Getting the size
int size = myMultimap.size();
System.out.println(size); // 4
// Getting values
Collection<string> fruits = myMultimap.get("Fruits");
System.out.println(fruits); // [Bannana, Apple, Pear]
Collection<string> vegetables = myMultimap.get("Vegetables");
System.out.println(vegetables); // [Carrot]
// Iterating over entire Mutlimap
for(String value : myMultimap.values()) {
System.out.println(value);
}
// Removing a single value
myMultimap.remove("Fruits","Pear");
System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]
// Remove all values for a key
myMultimap.removeAll("Fruits");
System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
}
}
It sounds to me like a better choice would be a Map of Lists. Let the company ID be the key in the Map and append each new item for that company ID to the List that's the value.
Use the right tool for the job. Arrays are too low level.
Create a Map<String, List<Bussiness>>
Each time you retrieve a company name, first check if the key is already in the map. If it is, retrieve the list and add the Bussiness object to it. If it is not, insert the new value when a empty List and insert the value being evaluated.
try to use foreach instead of for
just like
foreach(List firstGroup in listOfLists)
foreach(String s in firstGroup)
............
Thanks for the input everyone!
I ended up going with a list of lists:
import java.util.*;
import search.LOBList;
public class arraySearch {
/**
* #param args
*/
public static void main(String[] args) {
LOBList test = new LOBList();
test.setCompany("80");
test.setLOB("106");
LOBList test1 = new LOBList();
test1.setCompany("80");
test1.setLOB("601");
LOBList test2 = new LOBList();
test2.setCompany("80");
test2.setLOB("602");
LOBList test3 = new LOBList();
test3.setCompany("90");
test3.setLOB("102");
LOBList test4 = new LOBList();
test4.setCompany("90");
test4.setLOB("102");
LOBList test5 = new LOBList();
test5.setCompany("100");
test5.setLOB("102");
LOBList BREAK = new LOBList();
BREAK.setCompany("BREAK");
BREAK.setLOB("BREAK");
BREAK.setcompany_lob("BREAK");
// create arraylist
ArrayList<LOBList> arlst=new ArrayList<LOBList>();
// populate the list
arlst.add(0,test);
arlst.add(1,test1);
arlst.add(2,test2);
arlst.add(3,test3);
arlst.add(4,test4);
arlst.add(5,test5);
//declare variables
int idx = 0;
String nextVal = "";
//loops through list returned from service, inserts 'BREAK' between different groups of companies
for(idx=0;idx<arlst.size();idx++){
String current = arlst.get(idx).getCompany();
if(idx != arlst.size()-1){
String next = arlst.get(idx+1).getCompany();
nextVal = next;
if(!(current.equals(next))){
arlst.add(idx+1,BREAK);
idx++;
}
}
}
//add last break at end of arrayList
arlst.add(arlst.size(),BREAK);
for(int i=0;i<arlst.size();i++){
System.out.println("co:" + arlst.get(i).getCompany());
}
//master array list
ArrayList<ArrayList<LOBList>> mymasterList=new ArrayList<ArrayList<LOBList>>();
mymasterList = searchListCreateNewLists(arlst);
//print log, prints all elements in all arrays
for(int i=0;i<mymasterList.size();i++){
for(int j=0;j<mymasterList.get(i).size();j++){
System.out.println("search method: " + mymasterList.get(i).get(j).getCompany());
}
System.out.println("end of current list");
}
}
//method to loop over company array, finds break, creates new array list for each company group,
//adds this to a list of lists(masterList)
public static ArrayList<ArrayList<LOBList>> searchListCreateNewLists(ArrayList<LOBList> list){
ArrayList<ArrayList<LOBList>> masterList=new ArrayList<ArrayList<LOBList>>();
int end = 0;
int start = 0;
int index = 0;
for(int i=0;i<list.size();i++){
if(list.get(i).getCompany().equals("BREAK")){
end = i;//end is current index
masterList.add(new ArrayList<LOBList>());
for(int j = start;j<end;j++){
masterList.get(index).add(list.get(j));
}
index++;
start = i+1;
}
}
return masterList;
}
}
The output is:
search method: 80
search method: 80
search method: 80
end of current list
search method: 90
search method: 90
end of current list
search method: 100
end of current list
So all company LOBList objects with Company: 80, are grouped together in a list, as are 90 and 100.
To iterate through the list you can use
ListIterator litr = coList.listIterator();
while(litr.hasNext()){
}