Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem that list.foreach cannot use string concatenation in Java

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to solve the problem that string concatenation can not be used in list.foreach in Java. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

List.foreach cannot use string concatenation as shown in figure, and cannot use String for stitching.

Because Lambda is essentially an anonymous inner class, t must be of type final (although the final in the code can be omitted) and cannot be reassigned.

Can be used

Final StringBuilder str = new StringBuilder ("selected:")

Figure 2

String concatenation problem @ Test public void forEachTest () {String str = "Hello China!" cannot be used in the foreach loop. ; List list = Arrays.asList ("a", "b", "c", "d"); list.forEach (item- > {/ / editing error: Variable used in lambda expression should be final or effectively final str + = item;}); / / enhanced for// for (String item: list) {/ / str + = item can be used / /} System.out.println ("result: + str);}

The root cause of the failure of the compilation: the problem of using final for local variables in Lambda expressions.

Because the String type belongs to the reference data type, and the String string is immutable, String points to a different address value every time when concatenating the string, so the str variable cannot be regarded as a final type, which does not meet the requirements of Lambda expressions.

Solve

Use StringBuffer or StringBuilder:

@ Test public void forEachTest () {/ / String str = "Hello to China!" ; List list = Arrays.asList ("a", "b", "c", "d"); StringBuffer stringbuffer = new StringBuffer ("Hello to China!") ; list.forEach (item- > {stringbuffer .append (item);}); / / enhanced for// for (String item: list) {/ / str + = item;//} System.out.println ("result:" + sb);} principle   

StringBuffer is a reference data type. When you do append (), you just change the content, not the address value. This stringbuffer variable is treated as a variable of type final at compile time, so you can use it.

The problem of using final for local variables in Lambda expressions

To use local variables in lambda expressions, use final

The lambda expression itself is a written form of an anonymous inner class that can manipulate external variables

There are no restrictions on using instance variables or static variables (it can be thought of as referencing the first two through a local variable of type final this)

Using a local variable must be explicitly declared as a final or actual final type, that is, the variable has never been changed

@ Test public void finalTest () {String str = "Hello to China!" ; / / use this variable in Lambda, which cannot be modified. Java8 will add final / / str = "c" by default; List list = Arrays.asList ("a", "b", "c", "d"); List collect = list.stream (). Filter (item-> {return item.equals (str);}) .subscription (Collectors.toList ()) System.out.println ("result:" + collect); / / cannot change str, otherwise compilation fails in the Lambda expression / / str = "Hello to Shandong";}

If a local variable is to be accessed in an anonymous class or Lambda expression, the local variable must be final, and the compiler automatically adds a final modifier even if it is not decorated with a final type.

Under Java 8, even if local variables are not declared as final types, once they are used in Lambda expressions (anonymous classes), they are strongly typed with the final attribute, so str cannot be assigned again later.

Why can't Lambda expressions (anonymous classes) access local variables that are not final?

Because instance variables exist in the heap and local variables are allocated on the stack, Lambda expressions (anonymous classes) are executed in another thread. If you want to access a local variable directly in a thread, the local variable may have been destroyed when the thread executes, and a local variable of type final is actually a copy of the local variable in the Lambda expression (anonymous class).

When java compiles, anonymous inner classes are also treated as normal classes, but when the compiler generates its constructor, it not only passes the reference to the external class, but also copies the variable of the basic data type and passes the variable reference of the reference data type. Therefore, of course, the variables of the basic data types cannot be modified, otherwise they will be inconsistent with the external variables, and the transfer of the variables will become meaningless.

This is the end of this article on "how to solve the problem that list.foreach cannot use string concatenation in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report