Looping in 2D-List JAVA - java

I'm trying to get the values for my function from the 2D List.
My 2D list value is defined as
List<List<String>> combined2d = new ArrayList<List<String>>();
After adding the values in to my List the structure is like below,
[[62744768, 62536400, 63689012, 63676486], [67888160, 67852422, 67299346, 68149470], [2017-09-06, 2017-09-05, 2017-09-17, 2017-09-15]]
I have a function with 3 parameters i.e,
FuncA(string param1,string param2,string param3)
{
//some operations
}
Now i want to pass the parameters of the FuncA by looping the 2D List Values.
For Loop 1
I have to get the 00,10,20 Index values from the List such as
62477,6780,2017-09-06
So that I will pass the parameters to my FuncA like
FuncA(62477,6780,2017-09-06)
For Loop 2
Like so for Loop 2 ,
FuncA(600,6785,2017-08-05)
For Loop 3
FuncA(12,646,2017-07-17)
Up-to N loops...
For a simple ArrayList I'm able to loop through like this
for(String value:Singlearraylist) {
FuncB(value);
}
As I'm new to java I couldn't able to find the solution for my problem here.
Appreciate your response
JAY

String[] strings = new String[combined2d.size()];
for (int i = 0; i < combined2d.get(0).size(); i++){
for (int j = 0; j < combined2d.size(); j++){
strings[j] = combined2d.get(j).get(i);
}
FuncA(strings[0] strings[1], strings[2]);
}
I think this will work fine for you.

If size of all the Lists are uneven, loop size should be minimum size of all given lists given in the 2-d list. Accordingly code can be written as forllows:
List<List<String>> combined2d = new ArrayList<List<String>>();
int minTemp = Math.min(combined2d.get(0).size(),combined2d.get(1).size());
int min = Math.min(minTemp,combined2d.get(2).size());
for(int i=0; i<min ; i+= 10){
FuncA(combined2d.get(0).get(i), combined2d.get(1).get(i), combined2d.get(2).get(i));
}

As #MadProgrammer suggested, create a class with data members param1 param2 param3with getters and setters and the list of this class's type, which you can use to iterate pass values to FuncA(...,...,...)
class Data{
String param1, param2, param3;
// constructors, getters and setters
}
List<Data> listData = new ArrayList<>();
for(Data temp : listData)FuncA(temp.getParam1(),temp.getParam2(),temp.getParam3());
And the way you create your list is the key here also as #MadProgrammer suggested in the comments.
This way, your code is a lot easier to read and debug.

Related

why is everything getting removed from my arraylist?

I'm trying to answer this question:
Program the method findIngredients. This method takes in a String called
foodInStock, and an ArrayList of Strings called ingredients. The method should return an
ArrayList of ingredients that were not found in foodInStock.
for example if:
foodInStock = “tomatopotatocornturkeycarrotstuffing”
ingredients = {“potato”, “corn”, “salt”, “chicken”, “turkey”}
returns {“salt”, “chicken”}
I tried writing some code but for some reason everything is getting removed when I use the above example on my program. Where did my program go wrong?
Here's my code:
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients){
ArrayList<String> ingredientsNotFound = new ArrayList<String>();
int i = 0;
for (; i < ingredients.size(); i++) {
for (int x = 0; x < foodInStock.length()-(ingredients.get(i).length())+1; x++) {
if (ingredients.get(i) == foodInStock.substring(x, (x + ingredients.get(i).length()))) {
ingredients.remove(i);
i = 0;
break;
}
}
}
ingredients = ingredientsNotFound;
return ingredientsNotFound;
}
I think there are two main things to cover here.
First, the way to build the final result. You are currently removing items from the original input; a better strategy is to add items to a new list (partially because it's simpler to think about and partially because you generally don't want to modify a list while iterating over it).
You also are, probably accidentally, overwriting your list with an empty list at the end.
Second, the way to determine whether or not the ingredient is in the string input. Rather than looping over the whole string and inspecting substrings, you can instead use the indexOf() method to see whether or not the string includes the current item.
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients) {
ArrayList<String> results = new ArrayList<>();
for (String ingredient : ingredients) {
if (foodInStock.indexOf(ingredient) == -1) {
results.add(ingredient);
}
}
return results;
}
Here we initialize a new list for the results. We then loop over every individual ingredient in the input list, and ask whether or not that ingredient is present in the string input. When it is not (indexOf() returns -1), we add it to the results list. At the end, the results contains every ingredient not found.

How can i remove an element from array in Java

Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?
You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list
First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!
To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.
There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}

Dynamically initialise array name

I am trying to create an array of objects with a MAX_N 6 object into this array, then create another array within an else statement to fit the rest of the array objects.
I would like to name the new array
sbag1
sbag2
etc
here is my code:
public static ShoppingBag[] packIntoBags(GroceryItem[] goods) {
ShoppingBag newBag = new ShoppingBag();
GroceryItem tmpObject = null;
int index = 0;
String bag = "newBag";
String bagNum = bag + index;
for (int i = 0; i < MAXNBAG; i++)
if (newBag.numItems() < MAX_NUM_ITEMS) {
for (int k = 0; i < MAX_NUM_ITEMS; i++) {
tmpObject = goods[i];
newBag.addToBag(tmpObject);
}
}
else {
ShoppingBag newBag1 = new ShoppingBag();
}
}
You will not be able to dynamically create new variables in java.
When I look at the signature of your method you don't need to return multiple variables, only an array of ShoppingBags.
You should create a variable of type List<ShoppingBag>:
List<ShoppingBag> shoppingsBags=new ArrayList<>();
each time you need a new ShoppingBag:
bag=new ShoppingBag();
shoppingBags.add(bag);
at the end convert this list to an array:
return shoppingBags.toArray(new ShoppingBag[0]);
Java is a statically compiled language. In general, it is not possible, or to be precise: not helpful to use "dynamic" names for variables.
What you could do instead: use a Map, or even more simple: an array of arrays to hold your data.

Replace strings populated in an ArrayList<String> with other values

I am currently working on a project where I need to check an arraylist for a certain string and if that condition is met, replace it with the new string.
I will only show the relevant code but basically what happened before is a long string is read in, split into groups of three, then those strings populate an array. I need to find and replace those values in the array, and then print them out. Here is the method that populates the arraylist:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> DNAsplit = new ArrayList<String>();
for (int i = 0; i < text.length(); i += 3)
{
DNAsplit.add(text.substring(i, Math.min(i + 3, text.length())));
}
return DNAsplit;
}
How would I search this arraylist for multiple strings (Here's an example aminoAcids = aminoAcids.replaceAll ("TAT", "Y");) and then print the new values out.
Any help is greatly appreciated.
In Java 8
list.replaceAll(s-> s.replace("TAT", "Y"));
There is no such "replace all" method on a list. You need to apply the replacement element-wise; the only difference vs doing this on a single string is that you need to get the value out of the list, and set the new value back into the list:
ListIterator<String> it = DNAsplit.listIterator();
while (it.hasNext()) {
// Get from the list.
String current = it.next();
// Apply the transformation.
String newValue = current.replace("TAT", "Y");
// Set back into the list.
it.set(newValue);
}
And if you want to print the new values out:
System.out.println(DNAsplit);
Why dont you create a hashmap that has a key-value and use it during the load time to populate this list instead of revising it later ?
Map<String,String> dnaMap = new HashMap<String,String>() ;
dnaMap.push("X","XXX");
.
.
.
dnaMap.push("Z","ZZZ");
And use it like below :
//Use the hash map to lookup the temp key
temp= text.substring(i, Math.min(i + 3, text.length()));
DNAsplit.add(dnaMap.get(temp));

Sorting a list of maps within before this while loop runs out(Java)

A database call is made and result is a bunch of rows of two string columns of type A and B. e.g. (x_a, y_b), (x_a, y1_b), (x2_a,y_b)
The idea is to come up with a list of maps like {(x_a,{y_b,y1_b}), (x2_a,{y_b})} where the objects of type A are not repeated and to do this while pulling the results from a database.
Here's what I tried:
int i =0;
List<String> type2 = new ArrayList<String>();
Map<String,List<String>> type1_type2 = new HashMap<String,List<String>>();
List<Map> list_type1_type2 = new ArrayList<Map>();
String [] type1Array = new String[100];
String [] type2Array = new String[100];
int trackStart = 0;
while (res.next()){
String type1 = res.getString(1);
String type2 = res.getString(2);
type1Array[i]=type1;
type2Array[i] = type2;
if(i>0 && !type1Array[i].equals(type2Array[i-1])){
int trackStop = i;
for(int j = trackStart; j<trackStop;j++){
type2.add(type2Array[j]);
}
type1_type2.put(type1Array[i-1], type2);
list_type1_type2.add(type1_type2);
//debugging stuff
String x = list_type1_type2.toString();
System.out.println(x);
System.out.println(" printing because "+ type1Array[i]+" is not equal to " + type1Array[i-1]);
type2 = new ArrayList<String>();
type1_type2 = new HashMap<String,List<String>>();
trackStart=i;
}
i++;
}
This method does not work when the last type1 values of the result object are the same.
Is there a way to do this in the same spirit (within the while(res.next)) without first storing the results of the database call in separate arrays or adding an extra for loop outside the while loop to "patch it up"?
The simple way to do this is to use a Guava / Google Collections SetMultiMap. This is essentially a mapping from a key (your 'A' objects) to a set of values (your 'B' objects).
[I'm not going to try to code it for you. Your current code is too horrible to read ... unless you were paying me :-) ]
However, a better idea would be to get the database to do the collation. If you can do that, you will reduce the amount of (redundant) data that gets send across the database connection ... assuming that you are using JDBC.
If you don't want duplicates like {x_a:[y_b, y_b]} then use a set as the value of your map:
Map<String,Set<String>> type1_type2;
I don't know what the other various list and arrays are for. You can probably just get by with the type1_type2 map. Process each (x, y) in pseudo-code:
Set s = type1_type2.get(x)
if s == null:
s = new Set()
type1_type2.put(x, s)
s.add(y)

Categories

Resources