Java ForEach in ArrayList with Locate [duplicate] - java

This question already has answers here:
Java, How do I get current index/key in "for each" loop [duplicate]
(6 answers)
Closed 8 years ago.
Overview:
I'm using for-each loops and I'm curious if I need to replace them with regular for loops, or if there is a way to do a locate in an ArrayList which will give me the equivalent of keeping track of the index which is used in normal for loops.
Simplified Version of the Problem:
I'm using for-each with an ArrayList of objects. These objects are used to calculate different values at different times, so I need to iterate through the items and do the calculates a couple different times. I wish to track these results in a structure, which I can easily do, if I can locate items in an ArrayList (without having to iterate through everything in a separate loop). If there is, then I can use that to build what I need. If not, I'll replace the for-each with for loops and get the functionality I need.

You can use a regular for-loop but sometimes it just isn't a good idea, for example if you're dealing with linked lists where element retrieval is O(n) in the index. Why not just keep track of index?
int index = 0;
for (Element e : list) {
...
index++;
}
I find this cleaner than a plain for-loop, and it will remain efficient even if you change from ArrayList to another type of list which is not random-access.

The for-each loop is meant to be an easy way to operate on every element in a collection or array. If you want to iterate and keep track of indicies, you'll want a normal for loop.
However, some Collections (Lists for example) have an indexOf() method which you can use to get the index. That would kill your performance though.
You can also use a counter:
int i = 0;
for (Object o : list) {
// Code
i++;
}

Related

Remove all the strings in an array list containing certain characters

so i have an array list that contains strings such as:
ArrayList<String> list = new ArrayList<>();
list.add("bookshelf");
list.add("bookstore");
list.add("library");
list.add("pencil");
Now i wanna search and remove all the strings in the arraylist that contain the word "book" in them. As far as i understand list.remove("book"); will only search for the particular string "book" and not the strings that contain the word "book". How can i solve this?
You can use removeIf like this:
list.removeIf(s -> s.contains("book"));
Note: this answers applies to Java version 7 and below (of course that it will work for higher versions as well but YCF_L's answer is simpler to implement in versions 8 and above).
The requirement is to iterate the list, check every element, and if it answers a certain condition: remove it.
Since this is the case we fall into a risky scenario where we modify the list while iterating it which is problematic because when we remove an element in the list its size changes.
In order to work around this problem we can iterate the list by index from the last element and back until the first one, this way, removing an element at index n will not effect accessing any element at index < n.
I'll leave the implementation details to you in order not to "spoon feed" and destroy your exercise :)

wanted to limit the looping while using ForEach

Say I got 100 records from DB, I want to loop 10 times and perform some action.
and loop again and perform some action.. it continues until the last record is read.
The problem what i am seeing is
for (int number: numbers) {
add(number);
//after adding 10 items I want to complete a function and continue the loop
}
But here in Java, if use the above loop we can see it will iterate the complete list and comes out.
I know in older versions, we can iterate by counter like
for(int i=0; i<10;i++)
some thing like this.
My question is if forEach loop doesnot provide this flexibility, then why Sun Java introduced to a looping mechanism where it will iterate completely.
Trying to understand the logic of this design.
You can use a forEach or for-in with a nested conditional.
for(number: numbers){
if(number != (multOfTen)){
myFunction(number);
add(number);
}else{
add(number);
}
}
you will need to replace multOfTen w/ an expression that includes only multiples of ten.
One way to do this is to use regEx to check that the last digit is zero (so long as your using integers.)
As the name suggests, forEach will iterate over the whole collection. This is the same for JavaScript and several other languages. However you can abort / skip the iteration with a condition (which depends on the language implementation details).
There are difference between for and forEach loop. There are reason why java has these 2. forEach is enhance for loop. Both have their usage based on requirements.
for
This we can use for general purpose. This is totally based on indexes. If you want to play with data at particular index or want to perform some actions based on index of element, you should use for.
forEach
this is used with only collections and arrays. This iterate over whole collections at once. Means you can't have index of element while iterating it. This is used when you manipulate each data in list regardless whats its index. For example to print all element in a given list, instead of writing classical for loop
for (int i =0; i < list.length(); i++){
System.out.println(list(i));
}
we use forEach loop
list.forEach(e -> {
System.out.println(e);
});
this is more readable, easy to use and crisp.
because sometimes the question or the implementation you're doing using java doesn't need the index of the array "simply".
so instead of writing the whole for(int i=0;i<arr.length;i++) thing you can just use foreach and instead of arr[i] you use a simple variable name.
This is actually possible using the same Stream api but it's beyond the scope of forEach. What you want to do isn't possible by limiting yourself to forEach. The purpose of forEach is to execute some action without bias on all elements of an Iterable or Stream. What you can do is break down your objects into groups of 10 and then for each grouping of 10, do what you want which is add all to the underlying collection and then perform some other action which is what you want as well.
List<Integer> values = IntStream.range(0, 100)
.boxed()
.collect(Collectors.toList());
int batch = 10;
List<List<Integer>> groupsOfTen = IntStream.range(0, values.size() / batch + 1)
.map(index -> index * batch)
.mapToObj(index -> values.subList(index,
Math.min(index + batch, values.size())))
.collect(Collectors.toList());
groupsOfTen.forEach(myListOfTen -> myListOfTen.forEach(individual -> {
}));

What is the meaning of ":"? [duplicate]

This question already has answers here:
How does the Java 'for each' loop work?
(29 answers)
Closed 5 years ago.
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like
for(String x : model)
Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?
It means the loop will iterate through each object of the list
String x declares a String named x
model is the list of String you want to iterate through
: is the operator making the compiler doing this operation.
You can read the for like this : For each String in model, use x as variable and do the following operations.
you can then use x to do the operations you want on each elements of the list
In this context, : literally means in.
This is the syntax of the enhanced for loop. It marely means that you're iterating over all the elements in model, where in each iteration the String x is assigned with the current element so you can use in the loop's body.
Similar to mathematical notation that represents elements in a set.
Read left to right; For all string's x that are elements in model, do .

Why did the first for loop fail in Java? [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 7 years ago.
I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.
for(int num:a)
num=1;
But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~
for(int num=0;num<a.length;num++)
a[num]=1;
for(int n:a)
System.out.println(n);
Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.
These loops are different. Both in functionality and operations.
The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.
The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.
To put this in other terms:
The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.
The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.
Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.
Or...you could use Java 8's Stream API and come up with something like this:
IntStream.iterate(1, (x) -> 1).limit(100).toArray()

Android (Method for finding Array repeated numbers) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android (method for checking an arrays for repeated numbers?)
I've just asked a question and got a few answers and i was very happy to, but there were very complicated answers, I'm quite new to android so can some one maybe give me some example code or some think explained not the complicated. I've tried there code and tried to make sense of it but i cant.
here is the question....
could any one help me. i am making an app, and in the java, numbers are send to a int array and i need to check if any of the numbers in the array repeated and if there are to call a method or something like that. Is there a method to check this or something similar? or would i have to do it using loops and if statements, which i have tried but is getting a bit long and confusing. Any advice would be great, thanks.
int test[] = {0,0,0,0,0,0,0}; (The Array)
(A method to check if any of the arrays numbers are repeated)
First don't make double topic.
Second you are searching for a Java answer not related to Android.
I think that maybe it's better if you first learn java (or other language like).
I would store the items in a Set if you do not want them to repeat. If add returns false then you have a repeating number
Set uniqueItems = new HashSet();
for(int i=0;i<test.length;i++)
if(!uniqueItems.add(test[a]))
System.out.println("The item is already in the set");
First, sort the array. Then search through the array comparing each node to the node on either of it's sides. Or you could store the data in a Set which cannot have duplicates.
Arrays.asList(test).contains(valueYouWantCheck).
If you want to find out for each and every value in test array, Yes I think you need to loop the array.

Categories

Resources