Hey guys sorry i'm a noob at java but im trying to make something and i need a multidimensional array list. It must be implemented into the following code:
public static void OpenFile() {
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
int retrival = chooser.showOpenDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.equals("")) {
continue;
} else if (sCurrentLine.startsWith("Question")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [0] in array ArrayList
} else if (sCurrentLine.startsWith("Answer")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [1] in array ArrayList
} else if (sCurrentLine.startsWith("Category")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [2] in array ArrayList
} else if (sCurrentLine.startsWith("Essay")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [3] in array ArrayList
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
All the [1] index's of the strings i split need to go into a multidimesional array in this order: question, answer, category, essay.
So i am currently using a normal multidimensional array but you cant change the values of it easily. What i want my multidimensional arraylist to look like is this:
MultiDimensional ArrayList
[0]: questions(it may be over 100 of them.)
[1] answers(it may be over 100 of them.)
[2] category(it may be over 100 of them.)
[3] essay(it may be over 100 of them.)
Seems like an assignment with List of List.
Here is the psuedo code. Try to implement rest.
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
First thing you have to do is take 4 fresh ArrayLists
ArrayList<String> qtns= new ArrayList<String>>();
ArrayList<String> answrs= new ArrayList<String>>();
--
--
Add all of them to main list
array.add(qtns);
--
--
Then now filling them like
else if (sCurrentLine.startsWith("Question")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [0] in array ArrayList
array.get(0).add(sCurrentLine.split(":")[1]);//get first list(which is qtns list) and add to it.
} else if (sCurrentLine.startsWith("Answer")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [1] in array ArrayList
array.get(1).add(sCurrentLine.split(":")[1]);//get second list(which is answers list) and add to it.
}
-- -
---
So that in the end you'll have a list of list which contains the data.
array is an array of four elements (or will be, after you set it up--see below). Each of the elements is a reference to another ArrayList, i.e. an ArrayList<String>. To modify the inner ArrayList, first you need to get the reference to it, which you do with the get method:
array.get(0)
for the [0] list, or array.get(1) for the [1] list, and so on. The result will be an ArrayList<String>. Now you can perform methods on that; to add a String to the end of the ArrayList<String>:
array.get(0).add("String to add");
etc.
Actually, now that I look at it, you'll need to set up the four elements of array first. Each element will be set to a new ArrayList<String>:
for (int i = 0; i < 4; i++)
array.add(new ArrayList<String>());
Do this at the top of the method.
This is a really bad design. You should create a custom class, with the separate types of rows as fields (maybe call it Question), and then use a List<Question> to store the individual question objects. This will make it clearer, and safer, to work with in the future.
You can have a HashMap with key as (Questions,Answers..) and ArrayList as value
HashMap <String,ArrayList<String>> array = new HashMap<String,ArrayList<String>>();
if(array.containsKey("Question")){
array.get("Question").add(sCurrentLine.split(":")[1]);
}else{
ArrayList<String> questions = new ArrayList<String>();
questions.add(sCurrentLine.split(":")[1]);
array.put("Question",questions );
}
Modification In your Code
public static void OpenFile() {
HashMap <String,ArrayList<String>> array = new HashMap<String,ArrayList<String>>();
int retrival = chooser.showOpenDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.equals("")) {
continue;
} else if (sCurrentLine.startsWith("Question")) {
System.out.println(sCurrentLine.split(":")[1]);
if(array.containsKey("Question")){
array.get("Question").add(sCurrentLine.split(":")[1]);
}else{
ArrayList<String> questions = new ArrayList<String>();
questions.add(sCurrentLine.split(":")[1]);
array.put("Question",questions );
}
//add to [0] in array ArrayList
} else if (sCurrentLine.startsWith("Answer")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [1] in array ArrayList
//Do the same as above if condition with Answer as Key
} else if (sCurrentLine.startsWith("Category")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [2] in array ArrayList
} else if (sCurrentLine.startsWith("Essay")) {
System.out.println(sCurrentLine.split(":")[1]);
//add to [3] in array ArrayList
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Once you created a 2D array, you also need to create 4 1D arrays.
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
// 1D array for "Question"
array.add(new ArrayList<String>());
// 1D array for "Answer"
array.add(new ArrayList<String>());
// 1D array for "Category"
array.add(new ArrayList<String>());
// 1D array for "Essay"
array.add(new ArrayList<String>());
Let's say if you need to add one item to the question array, then you should do:
array.get(i).add(...);
where i = 0. The range of i is from 0 to 3, which corresponds to the 4 enumerations.
You should use another data structure to achieve that, Use a Map<String,List<String>> where the possible keys are Question,Answers,Category,Essay
Then in your code you can remove all unnecessary if-else
Example with your code:
public static void openFile() {
Map<String,List<String>> map = new HashMap<>();
// here you put the keys, you can do it when you read the file based in your input too dynamically
map.put("Question",new ArrayList<>());
map.put("Answers",new ArrayList<>());
map.put("Category",new ArrayList<>());
map.put("Essay",new ArrayList<>());
int retrival = chooser.showOpenDialog(null);
String[]array = null;
if (retrival == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(
chooser.getSelectedFile()))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.equals("")) {
continue;
}
array = sCurrentLine.split(":");
if(map.containsKey(array[0])){
map.get(array[0]).add(array[1]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You can see this way is much more cleaner and readable.
Related
Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));
public class JavaApplication13 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
BufferedReader br;
String strLine;
ArrayList<String> arr =new ArrayList<>();
HashMap<Integer,ArrayList<String>> hm = new HashMap<>();
try {
br = new BufferedReader( new FileReader("words.txt"));
while( (strLine = br.readLine()) != null){
arr.add(strLine);
}
} catch (FileNotFoundException e) {
System.err.println("Unable to find the file: fileName");
} catch (IOException e) {
System.err.println("Unable to read the file: fileName");
}
ArrayList<Integer> lengths = new ArrayList<>(); //List to keep lengths information
System.out.println("Total Words: "+arr.size()); //Total waords read from file
int i=0;
while(i<arr.size()) //this loop will itrate our all the words of text file that are now stored in words.txt
{
boolean already=false;
String s = arr.get(i);
//following for loop will check if that length is already in lengths list.
for(int x=0;x<lengths.size();x++)
{
if(s.length()==lengths.get(x))
already=true;
}
//already = true means file is that we have an arrayist of the current string length in our map
if(already==true)
{
hm.get(s.length()).add(s); //adding that string according to its length in hm(hashmap)
}
else
{
hm.put(s.length(),new ArrayList<>()); //create a new element in hm and the adding the new length string
hm.get(s.length()).add(s);
lengths.add(s.length());
}
i++;
}
//Now Print the whole map
for(int q=0;q<hm.size();q++)
{
System.out.println(hm.get(q));
}
}
}
is this approach is right?
Explanation:
load all the words to an ArrayList.
then iterate through each index and check the length of word add it to an ArrayList of strings containing that length where these ArrayList are mapped in a hashmap with length of words it is containing.
Firstly, your code is working only for the files which contain one word by line as you're processing whole lines as words. To make your code more universal you have to process each line by splitting it to words:
String[] words = strLine.split("\\s+")
Secondly, you don't need any temporary data structures. You can add your words to the map right after you read the line from file. arr and lengths lists are actually useless here as they do not contain any logic except temporary storing. You're using lengths list just to store the lengths which has already been added to the hm map. The same can be reached by invoking hm.containsKey(s.length()).
And an additional comment on your code:
for(int x=0;x<lengths.size();x++) {
if(s.length()==lengths.get(x))
already=true;
}
when you have a loop like this when you only need to find if some condition is true for any element you don't need to proceed looping when the condition is already found. You should use a break keyword inside your if statement to terminate the loop block, e.g.
for(int x=0;x<lengths.size();x++) {
if(s.length()==lengths.get(x))
already=true;
break; // this will terminate the loop after setting the flag to true
}
But as I already mentioned you don't need it at all. That is just for educational purposes.
Your approach is long, confusing, hard to debug and from what I see it's not good performance-wise (check out the contains method). Check this:
String[] words = {"a", "ab", "ad", "abc", "af", "b", "dsadsa", "c", "ghh", "po"};
Map<Integer, List<String>> groupByLength =
Arrays.stream(words).collect(Collectors.groupingBy(String::length));
System.out.println(groupByLength);
This is just an example, but you get the point. I have an array of words, and then I use streams and Java8 magic to group them in a map by length (exactly what you're trying to do). You get the stream, then collect it to a map, grouping by length of the words, so it's gonna put every 1 letter word in a list under key 1 etc.
You can use the same approach, but you have your words in a list so remember to not use Arrays.stream() but just .stream() on your list.
So I gathered tokens from multiple lines of a text file and put those tokens into an array called tokens. With this code.
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if ((line = scanner.nextLine()).charAt(0) != '#') {
tokens = line.split(",");
}
}
(Its all in a try catch block)
I need to put all of those String tokens into a single array, how would I do this.
My new array is stringTokens [] = new String [countLines *4].
The while loop redefines the elements in tokens with each iteration, how do I save those old elements in stringTokens and add the new elements tokens will get into stringTokens as well.
You can use an ArrayList<String> for that, and when you need it as array, you can convert it to one:
ArrayList<String> list = new ArrayList<>();
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if ((line = scanner.nextLine()).charAt(0) != '#') {
for(String s : line.split(",")) {
list.add(s);
}
}
}
stringTokens = list.toArray(new String[0]);
You should look into using ArrayLists. They are essentially mutable arrays, with no specified size (the array "grows"* as you add elements.) and adding each token to your list of strings.
ArrayList<String> stringTokens = new ArrayList<String>();
...
for(String s : line.split(",")) {
stringTokens.add(s);
}
*Capacity doubles when needed.
I want to read a CSV file in Java and sort it using a particular column. My CSV file looks like this:
ABC,DEF,11,GHI....
JKL,MNO,10,PQR....
STU,VWX,12,XYZ....
Considering I want to sort it using the third column, my output should look like:
JKL,MNO,10,PQR....
ABC,DEF,11,GHI....
STU,VWX,12,XYZ....
After some research on what data structure to use to hold the data of CSV, people here suggested to use Map data structure with Integer and List as key and value pairs in this question:
Map<Integer, List<String>>
where the value, List<String> = {[ABC,DEF,11,GHI....], [JKL,MNO,10,PQR....],[STU,VWX,12,XYZ....]...}
And the key will be an auto-incremented integer starting from 0.
So could anyone please suggest a way to sort this Map using an element in the 'List' in Java? Also if you think this choice of data structure is bad, please feel free to suggest an easier data structure to do this.
Thank you.
I would use an ArrayList of ArrayList of String:
ArrayList<ArrayList<String>>
Each entry is one line, which is a list of strings.
You initialize the list by:
List<ArrayList<String>> csvLines = new ArrayList<ArrayList<String>>();
To get the nth line:
List<String> line = csvLines.get(n);
To sort you write a custom Comparator. In the Constructor of that comparator you can pass the field position used to sort.
The compare method then gets the String value on stored position and converts it to a primitive ava type depending on the position. E.g you know that at position 2 in the csv there is an Integer, then convert the String to an int. This is neccessary for corretcly sorting. You may also pass an ArrayList of Class to the constructor such that it knows which field is what type.
Then use String.compareTo() or Integer.compare(), depending on column position etc.
Edit example of working code:
List<ArrayList<String>> csvLines = new ArrayList<ArrayList<String>>();
Comparator<ArrayList<String>> comp = new Comparator<ArrayList<String>>() {
public int compare(ArrayList<String> csvLine1, ArrayList<String> csvLine2) {
// TODO here convert to Integer depending on field.
// example is for numeric field 2
return Integer.valueOf(csvLine1.get(2)).compareTo(Integer.valueOf(csvLine2.get(2)));
}
};
Collections.sort(csvLines, comp);
In Java 8 you can do
SortedMap<Integer, List<String>> collect = Files.lines(Paths.get(filename))
.collect(Collectors.groupingBy(
l -> Integer.valueOf(l.split(",", 4)[2]),
TreeMap::new, Collectors.toList()));
Note: comparing numbers as Strings is a bad idea as "100" < "2" might not be what you expect.
I would use a sorted multi-map. If you don't have one handy you can do this.
SortedMap<Integer, List<String>> linesByKey = new TreeMap<>();
public void addLine(String line) {
Integer key = Integer.valueOf(line.split(",", 4));
List<String> lines = linesByKey.get(key);
if (lines == null)
linesByKey.put(key, lines = new ArrayList<>());
lines.add(line);
}
This will produce a collection of lines, sorted by the number where lines with duplicate numbers have a preserved order. e.g. if all the lines have the same number, the order is unchanged.
You can also use a list of lists:
List<List<String>> Llp = new ArrayList<List<String>>();
Then you need to call sort that extends a custom comparator that compares the third item in the list:
Collections.sort(Llp, new Comparator<LinkedList<String>>() {
#Override
public int compare(LinkedList<String> o1, LinkedList<String> o2) {
try {
return o1.get(2).compareTo(o2.get(2));
} catch (IndexOutOfBoundsException e) {
return 0;
}
}
In the below code I have sorted the CSV file based on the second column.
public static void main(String[] args) throws IOException {
String csvFile = "file_1.csv";
String line = "";
String cvsSplitBy = ",";
List<List<String>> llp = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
llp.add(Arrays.asList(line.split(cvsSplitBy)));
}
llp.sort(new Comparator<List<String>>() {
#Override
public int compare(List<String> o1, List<String> o2) {
return o1.get(1).compareTo(o2.get(1));
}
});
System.out.println(llp);
} catch (IOException e) {
e.printStackTrace();
}
}
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()){
}