This question already has answers here:
Why is this java Stream operated upon twice?
(4 answers)
Copy a stream to avoid "stream has already been operated upon or closed"
(10 answers)
Closed 5 years ago.
Can Anyone help me why this case is giving the exception?
IntStream i = IntStream.of(6,5,7,1, 2, 3, 3);
IntStream d = i.map(n -> n+1 );
d.forEach(System.out::print);
System.out.println();
System.out.println("Origional Streams" );
i.forEach(System.out::print);
Here is Output.
7682344
Origional Streams
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
at java.util.stream.IntPipeline$Head.forEach(IntPipeline.java:557)
look that
d = i.map(n -> n + 1);
means that the stream d is taking the reference of the stream i,
now forEach is a terminal operation, consuming the stream of i, affecting the ref on d too.
Related
This question already has an answer here:
Golang updating maps and variables in an object
(1 answer)
Closed 3 years ago.
Currently trying to learn Go.
I have the following function, but it only works when the team doesn't exist in the map already and it creates a new record in the map. It will not update the values if the team already has a struct in the map.
func AddLoss(teamMap map[string]TeamRow, teamName string) {
if val, ok := teamMap[teamName]; ok {
val.Wins++
val.GamesPlayed++
} else {
newTeamRow := TeamRow{Losses: 1}
teamMap[teamName] = newTeamRow
}
}
I have updated the function to just replace the existing record with a brand new struct with the values I want, but that seems odd that I can't update the values in a map.
Can someone explain this to me, or point me in the right direction?
You have a map of string to the value of TeamRow so when you get the val out of the map it returns the value of the team, not a pointer to the team. If you make the map a string to the pointer of TeamRow then when you get the val out it will point to the memory that is stored in the map so values will persist beyond the scope of your AddLoss function. To do this simply add a * to the map declaration - teamMap map[string]*TeamRow though when you populate it you will then also need to store pointers in the map.
This question already has answers here:
Explain Type Assertions in Go
(3 answers)
Accessing Nested Map of Type map[string]interface{} in Golang
(2 answers)
Typed, nested map of map[string]interface{} returns "type interface {} does not support indexing"
(1 answer)
get value form nested map type map[string]interface{}
(2 answers)
how to access nested Json key values in Golang
(3 answers)
Closed 4 years ago.
I have something like this:
x1 := someFunctionWithAnInterfaceReturnValue()
and the underlying type is something like this:
x2 := map[string] string{"hello": "world"}
How would I access value in x1?
Essentially I want the equivalent of this for x1:
var value string = x2["hello"]
Use a type assertion:
x1 := someFunctionWithAnInterfaceReturnValue()
x2, ok := x1.(map[string]string)
if !ok {
// handle unexpected type
}
var value string = x2["hello"]
This question already has answers here:
Efficiently mutate a vector while also iterating over the same vector
(2 answers)
Is there an elegant solution to modifying a structure while iterating?
(1 answer)
How to idiomatically iterate one half of an array and modify the structure of the other?
(1 answer)
How can I iterate a vector once and insert/remove/modify multiple elements along the way?
(1 answer)
How can I modify a collection while also iterating over it?
(2 answers)
Closed 4 years ago.
I have a struct GameLog that holds a Vec<Steps>. Steps holds a Vec<FieldData> and FieldData consists only of basic data types.
I create instances of these types using serde_json. After the deserialisation is done, I need to iterate over all the steps in the GameData and add to it the past version of the fields that are changed in the next turn it doesn't already contain.
I have a working Java implementation I'm trying to port to Rust, but I just can't figure this out, probably because I don't know enough about Rust's insides.
The current code looks like this:
let data = load_data("Path/to/json");
let mut gamelog: Vec<Vec<FieldData>> = Vec::with_capacity(data.steps.len() + 1);
gamelog.push(Vec::with_capacity(data.init.fields.len()));
gamelog[0] = data.init.fields;
for i in 1..(data.steps.len() - 1) {
gamelog.push(Vec::with_capacity(data.steps[i - 1].fields.len()));
gamelog[i] = data.steps[i - 1].fields.clone();
for future_field in &data.steps[i + 1].fields {
let mut inside = false;
for current_field in &data.steps[i].fields {
if current_field.x == future_field.x && current_field.y == future_field.y {
inside = true;
}
}
if !inside {
for j in i..0 {
let mut insideb = false;
for past_field in &data.steps[j].fields {
if future_field.x == past_field.x && future_field.y == past_field.y {
gamelog[i].push(past_field.clone());
insideb = true;
break;
}
}
if insideb {
break;
}
}
}
}
}
However, this only works by creating copies of the vectors and fields and creates a new Vec.
When I try to manipulate the Vec directly, I most often get a "can't move out of borrow" error on the for .. in data.steps[?].fields lines
What would a proper (and possibly much more idiomatic) way of directly manipulating the Vecs in the struct?
This question already has answers here:
What's the difference between pointer and value in struct?
(2 answers)
When to use a pointer to a nested struct for JSON? [duplicate]
Is it common to have struct members be pointers?
(1 answer)
Why should I use a pointer ( performance)?
(3 answers)
Closed 8 months ago.
I have read some of the stack overflow question related to "why pointer and why not pointer", but I could not understand much.
So, want to understand based on my example below
I have a list of users and I am finding a hard time to understand which approach is better and faster for the purpose of nesting array struct of users inside another struct.
For an example -
type loc struct {
Type string
Point []float64
}
type User struct {
ID string
Name string
Location loc
... // 30 more fields
}
Case A - Using pointer for nested array struct
type Games struct {
ID string
Owner []*User
Player []*User
}
// and storing it as
G:= Games{
ID: "1",
Owner: []*User{
&User {
ID: "2",
Name: "User A",
},
},
}
Case B - Should I use above approach or below approach to
type Games struct {
ID string
Owner []User
Player []User
}
// storing it as
G := Games {
ID: "1",
Owner: []User{
{
ID: "2",
Name: "User A",
},
},
}
Considering the situation, I do not have to change data for Owner or Player after creating value for Games above and Player can sometimes remain Nil, should I use only User or it's better to use *User
I have following confusion based on above 2 cases
Performance - which one is better & why?
Garbage Collection - which one is better & why?
Any Memory effects?
Any other effects!
Please help me out understanding based on the above example, which method would you have chosen above and why?
use option B
but if you want avoid allocation during iterations or change the content, you need to do it like this:
for i:=range G.Games{
G.Games[i]....
}
this way a copy will be created in every iteration
for _,game:=range G.Games{
game....
}
this looks like premature optimization.
write in the most simple/readable way and if is not fast enough, take a look at this in order to find the bottleneck
This question already has answers here:
Multidimensional arrays in Swift
(7 answers)
Closed 8 years ago.
I'm trying to push array type object to special index inside array in new Swift lang by Apple. It should look like this = [ [...], [...], ...], as I've read in the docs - NSMutableArray type is assigned to variable automatically if it's var, but even in playground it throws me errors:
var arr = [];
arr[0] = []; // Error: cannot assign to result of this expression
arr.insert([], atIndex:0) // Error: 'NSArray' does not have member named 'insert'
var array2d: [[Int]] = [[1,2,3,4],[5,6,7,8]]