Home > Back-end >  Lambda expressions foreach how to acquire the traverse index
Lambda expressions foreach how to acquire the traverse index

Time:11-23

Public static void main (String args []) {
List List=Java. Util. Arrays. AsList (" a ", "b", "c");
List. The forEach (s - & gt; {
//how to obtain traversal to which one now, such as the index
System. The out. Println (s);
});
}

CodePudding user response:

His first cap

CodePudding user response:

for (int i=0; I & lt; List. The size (); I++) {
System.out.println(i);
}

CodePudding user response:

Want to use lambda expressions

CodePudding user response:

Public static void main (String args []) {
List List=Java. Util. Arrays. AsList (" a ", "b", "c");
Int id=0;
List. The forEach (s - & gt; {
//how to obtain traversal to which one now, such as the index
Id=list. IndexOf (s);
System. The out. Println (id);
System. The out. Println (s);
});
}

CodePudding user response:

The
reference 4 floor qq_38455201 reply:
public static void main (String args []) {
List List=Java. Util. Arrays. AsList (" a ", "b", "c");
Int id=0;
List. The forEach (s - & gt; {
//how to obtain traversal to which one now, such as the index
Id=list. IndexOf (s);
System. The out. Println (id);
System. The out. Println (s);
});
}

If there is a repeating element?

CodePudding user response:

Lambda forEach is converted into the iterator traversal, you can only make an index outside himself, then index++

CodePudding user response:

 
List List=Java. Util. Arrays. AsList (" a ", "b", "c");
Stream. Iterate (0, I - & gt; I + 1). The limit (the list. The size ()). The forEach (I - & gt; {
System. The out. Println (String. The valueOf (I) + list. Get (I));
});

CodePudding user response:

Stream. Iterate (0, I - & gt; I + 1). The limit (the list. The size ()). The forEach (I - & gt; {
System. Out.println (I)
}

CodePudding user response:

The Local variable I is defined in an enclosing scope must be final or effectively final

CodePudding user response:

refer to 6th floor wildyy response:
lambda forEach is converted into the iterator traversal, you can only make an index outside himself, then index++


The Local variable I is defined in an enclosing scope must be final or effectively final

CodePudding user response:

For ((index, value) in the list!!!!! . WithIndex ()) {
}

CodePudding user response:

Plus the steram together not sweet with filter conditions inside the
  • Related