In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what is the functional way of Java8 to deal with data". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
A functional way of dealing with data
Java 8 not only adds functional support, it also extends the Collection class through a new functional way of handling data. In general, java needs a large number of loops and iterators to deal with large amounts of data.
For example, suppose you have a collection that stores customer (Customer) objects:
Collection customers
If you are only interested in customers from Belgium, you will have to iterate over all customer objects and save only what you need.
Collection belgians = new ArrayList (); for (Customer c: customers) {if (c.getCountry (). Equals ("Belgium") belgians.add (c);}
Not only does it take five lines of code, but it's not very abstract. What happens if you have 10 million people? Will you speed up by filtering all objects concurrently by two threads? Then you will have to use a lot of dangerous multithreaded code to rewrite all the code.
With Java 8, the same function can be achieved with only one line of code. With support for functional programming, Java 8 allows you to write only one function indicating which customers (objects) you are interested in and then use that function to filter the collection. The new Steams API for Java 8 supports you to do this:
Customers.stream () .filter (c-> c.getCountry () .equals ("Belgium"))
The above Java 8 version of the code is not only shorter, but also easier to understand. It has few platitudes (loops or iterators, etc.). The code calls the filter () method, which is obviously used to filter customers (objects). You no longer need to waste time reading the code in the loop to understand what it is doing to its data.
What if you want to execute this code concurrently? You only need to use another type of stream
Customers.parallelStream () .filter (c-> c.getCountry () .equals ("Belgium"))
What is even more exciting is that this functional style of code is also applicable to databases.
Use a functional approach on the database
Traditionally, programmers need to use special database query statements to access database data. For example, here is the JDBC code to find a customer from Belgium:
PreparedStatement s = con.prepareStatement ("SELECT *" + "FROM Customer C" + "WHERE C.Country =?"); s.setString (1, "Belgium"); ResultSet rs = s.executeQuery ()
Most of this code is a string, which prevents the compiler from finding errors and this hasty code can cause security problems. And this large amount of boilerplate code makes writing data access code very redundant. Some tools, such as jOOQ, can solve error checking and security problems by using special java libraries to provide a database query language. Or use object-relational mapping tools to avoid a lot of boring code, but they can only be used in general access queries, if you need complex queries, you still need to use a special database query language.
With Java 8, you can query the database functionally with the help of streaming API. For example, Jinq is an open source project that explores what kind of future database API can make functional programming possible. Here is a database query using Jinq:
Customers.where (c-> c.getCountry () .equals ("Belgium"))
This code is almost the same as code that uses streaming API. In fact, future versions of Jinq will allow you to write database queries directly using streaming API. When the code runs, Jinq is automatically translated into database query code, just like previous JDBC queries.
In this way, you can write efficient database queries even if you haven't learned some new database query languages. You can use the same style of code on the java collection. You don't need a special java compiler or virtual machine. All the code is compiled and run on the normal java 8 JDK. If there are errors in your code, the compiler will find them and report them to you, just like normal java code.
Jinq supports the same complex queries as SQL92. It supports Selection (selection), projection (projection), joins (join), and subquery. The algorithm of translating java code into database query is very flexible, as long as it is acceptable, it can be translated. For example, Jinq can translate the following database query, although it is complex.
Customers .where (c-> c.getCountry () .equals ("Belgium")) .where (c-> {if (c.getSalary ())
< 100000) return c.getSalary() < c.getDebt(); else return c.getSalary() < 2 * c.getDebt(); } ); 正如你看到的,java 8 的函数式编程非常适合数据库查询。而且查询紧凑,甚至复杂的查询也能够胜任。 内部运作 但这都是如何工作的呢?怎么能让普通的Java编译器将Java代码转换成数据库查询?Java 8 有什么特别之处使这个成为可能? 支持这些函数性风格的新的数据库PI的关键是一种叫做"象征性执行"的字节码分析手段。虽然你的代码是被一个普通的Java编译器编译的并运行在一个普通的Java虚拟机中,但 Jinq 能够在你被编译的Java代码运行时进行分析并从中构建数据库查询。使用 Java 8 Streams API 时,常会发现分析短小的函数时,象征性执行的工作效果***。 要了解这个象征性执行是如何工作的,最简单的方法是用一个例子。让我们检查一下下面的查询是如何被 Jinq 转换为SQL查询语言的: customers .where( c ->C.getCountry () .equals ("Belgium")
Initially, the variable customers is a collection, and its corresponding database query is:
SELECT * FROM Customers C
The where () method is then called and a function is passed to it. In the where () method, Jinq opens the function's .class file and gets the bytecode into which the function is compiled for analysis. In this example, instead of using the real bytecode, let's use some simple instructions to represent the bytecode of this function:
D = c.getCountry ()
E = "Belgium"
E = d.equals (e)
Return e
Here, we assume that the function has been compiled into these four instructions by the Java compiler. That's what Jinq sees when the where () method is called. How do you make Jinq understand this code?
Jinq analyzes by executing code. But Jinq does not run the code directly. It runs code "abstractly": instead of using real variables and real values, Jinq uses symbols to represent all values when the code is executed. This is why this analysis is called "symbolic execution".
Jinq executes each instruction and keeps track of all side effects or everything the code changes when the program is in state. Here is a chart showing all the side effects found when Jinq executes these four lines of code symbolically.
An example of symbolic execution
In the figure, you can see that after the * * instruction is run, Jinq finds two side effects: the variable d has changed and the method Customer.getCountry () is called. Because it is a symbolic execution, the variable d does not give a real value such as "USA" or "Denmark". It is assigned as a symbolic value of c.getCountry ().
After all these instructions have been symbolically executed, the Jinq pair is used as a side effect for simplification. Because the variables d and e are local variables, any changes to them will be discarded after the function exits, so these side effects are negligible. Jinq also knows that the Customer.getCountry () and String.equals () method does not modify any variables or display any output, so these method calls can also be ignored. From this, Jinq can conclude that executing this function has only one effect, and it returns c.getCountry (). Equals ("Belgium").
Once Jinq understands the function passed to it in the where () method, it can mix knowledge of database queries and take precedence over the customers collection to create a new database query.
Generate database query
This is how Jinq generates database queries from your code. The use of symbolic execution means that this approach is quite powerful for different code patterns output by different Java compilers. If the code encountered by Jinq has the side effect of not being converted into a database query, Jinq will keep your code unchanged. Because everything is written in normal Java code, Jinq can run that code directly, and your code will produce the desired results.
This simple translation example should let you know how to query translated works. You can be sure that these algorithms can correctly generate database queries from your code.
This is the end of the content of "what is the functional way in which Java8 handles data". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.