Translate

Tuesday, June 1, 2021

Java 8 Map, Filter, and Collect Examples

 Source: https://dzone.com/articles/how-to-use-map-filter-collect-of-stream-in-java-8

How to use the Map and Filter functions in Java 8 to transform and filter elements of objects.

 · Java Zone · Tutorial

Hello, guys! Many of my readers emailed me, asking to write a post about the map and filter function of Java 8, because they found it difficult to use and understand. Even though I have previously blogged about both the map() and filter(), I am writing again to expand on the concept in layman's language to provide even better understanding for everyone.

The map() function is a method in the Stream class that represents a functional programming concept. In simple words, the map() is used to transform one object into other by applying a function.

That's why the Stream.map(Function mapper) takes a function as an argument. For example, by using the map() function, you can convert a list of String into a List of Integer by applying the Integer.valueOf() method to each String on the input list.

All you need is a mapping function to convert one object to the other. Then, the map() function will do the transformation for you. It is also an intermediate Stream operation, which means you can call other Stream methods, like a filter, or collect on this to create a chain of transformations.

The filter method, as its name suggests, filters elements based upon a condition you gave it. For example, if your list contains numbers and you only want numbers, you can use the filter method to only select a number that is fully divisible by two.

The filter method essentially selects elements based on a condition you provide. That's why the filter (Predicate condition) accepts a Predicate object, which provides a function that is applied to a condition. If the condition evaluates true, the object is selected. Otherwise, it will be ignored.

Similar to map, the filter is also an intermediate operation, which means you can call other Stream methods after calling the filter.

The filter() method is also lazy, meaning it will not be evaluated until you call a reduction method, like collect, and it will stop as soon as it reaches the target.  If you are not familiar with Stream behavior, I suggest you check out The Ultimate Java 8 Tutorial, which further explains Stream fundamentals in great detail.

1. How to Use Map and Filter in Java 8

You need a good example to understand any new concept. Since String and Integer are the most common data type in Java, I have chosen an example that is both simple and interesting.

I have a list of String: numbers e.g. {"1", "2", "3", "4", "5", "6"}. I want to process this list and need another List of Integer with just even numbers.

In order to find the even numbers, I first need to convert a List of String to a List of Integer. For that, I can use the map() method of java.util.Stream class. But, before that, we need a Stream as a map() as defined in the java.util.stream class.

This is not difficult at all, since you can get the stream from any collection, e.g. List or Set, by calling the stream() method, which is defined in the java.util.Collection interface.

The map(Function mapper) method takes a Function, technically speaking, an object of java.util.function.Function interface. This function is then applied to each element of Stream to convert it into the type you want.

Because we need to convert a String to an Integer, we can pass either the Integer.parseInt() or Integer.valueOf() method to the map() function.

I have chosen the valueOf() method because of performance and caching. (By the way, it's not just me. Even Joshua Bloch has advised preferring static factory methods like valueOf() over constructor in Effective Java.) 

Image title

The map() will then return a Stream of Integer that contains both even and odd numbers. To select just even numbers, we can use the filter() method.

It takes a predicate object which is technically a function to convert an object to boolean. We pass an object and it will return true or false. The filter, then uses that information to include the object in the result stream.

To include only even numbers, we call filter( number -> number%2==0), which means each number will be divided by two, and if there is no remainder, it will be selected. This is the same logic we have used while solving coding problems to check if a given number is even or odd in Java. 

We are almost done. But, so far, we only have the Stream of even integers — not the List of even Integers and that's why we need to use them. 

Since we need a List, I called collect(Collectors.toList()), which will accumulate all even numbers into a List and return.

Now, you may be thinking: how does it know to return List of Integer? Well, we need to get that information by Type inference, because we have already specified that information by storing the result into a List<Integer>.

If you want to know more about type inference in a lambda expression, The Complete Java MasterClass is a good place to start.

2. Java 8 Map + Filter + Collect Example


2. Java 8 Map + Filter + Collect Example

Here is the Java program to implement what I covered in the above section. You can run this program in IDE or from the command line and see the result.

You can also experiment with using more map() functions or more filter() calls to make the composition longer and more sophisticated. You can even play with the collect() method to collect the result in a list, set, map or any other collection.


You can see that the original list contains numbers from 1 to 6, and the filtered list only contains even numbers, i.e. 2, 4, and 6.

The most important code in this example is the following four lines of Stream processing code:

Java 8 filter + map + collect + Stream example

This code is starting with a map, then a filter, and finally a collect. You may be wondering whether the order will matter or not. Well, it does.

Since our filter condition requires an int variable we first need to convert Stream of String to Stream of Integer. That's why we called the map() function first.

Once we have the Stream of Integer, we can apply maths to find the even numbers. We passed that condition to filter method. If we needed to filter on String, e.g. select all string which has length > 2, then we would have called filter before map.

That's all about how to use map and filter in Java 8. We have seen an interesting example of how we can use the map to transform an object to another and how to use filter to select an object based upon condition. We have also learned how to compose operations on stream to write code that is both clear and concise.


Tuesday, May 25, 2021

Learn R: How to Extract Rows and Columns From Data Frame

 Source: https://dzone.com/articles/learn-r-how-extract-rows

This article represents command set in R programming language, which could be used to extract rows and columns from a given data frame.

 · Big Data Zone · Tutorial

This article represents a command set in the R programming language, which can be used to extract rows and columns from a given data frame. When working on data analytics or data science projects, these commands come in handy in data cleaning activities. This article is meant for beginners/rookies getting started with R who want examples of extracting information from a data frame. Please feel free to comment/suggest if I missed mentioning one or more important points.

The following are the key points described later in this article:

  • Commands to extract rows and columns.
  • Command to extract a column as a data frame.
  • Command to extract an element.

Suppose you have a data frame, df, which is represented as follows. Below we've created a data frame consisting of three vectors that include information such as height, weight, and age.

Commands to Extract Rows and Columns

The following represents different commands which could be used to extract one or more rows with one or more columns. Note that the output is extracted as a data frame. This could be checked using the class command.

Command to Extract a Column as a Data Frame

The following represents a command which can be used to extract a column as a data frame. If you use a command such as df[,1], the output will be a numeric vector (in this case). To get the output as a data frame, you would need to use something like below.

Command to Extract an Element

The following represents a command which could be used to extract an element in a particular row and column. It is as simple as writing a row and a column number, such as the following:

# Element at 2nd row, third column

df[2,3]

Tuesday, May 18, 2021

Private Blockchains: Hyperledger vs. Quorum vs. Corda

 Source: https://dzone.com/articles/hyperledger-vs-quorum-vs-corda-which-is-correct-fo

May. 07, 21 · Security Zone · Opinion

Hyperledger, Quorum, and Corda all are private, permissioned blockchains, meaning that network participation is restricted and not anyone can be part of the blockchain.

In our primitive blogs, we learned about the basics of Blockchain Technology, what are public and private blockchains. We understood the details of public blockchains like Bitcoin, Ethereum as well as private blockchains Hyperledger Fabric and Hyperledger Fabric 2, the private blockchains of the Hyperledger family. While each blockchain has its own features and advantages, not everything can be applied and implemented for a particular project or business. Every business has its own set of requirements, the challenges or problems vary from business to business and a lot of other factors like budget, infrastructure, resources, time, etc., have to be taken into account while choosing the right technology for a business project.

In the case of Blockchain, a business, depending upon its nature and functionality may require to choose either a public, a private or a hybrid blockchain. While one of our previous blogs explained the difference between Bitcoin and Ethereum, the public blockchains; this blog will shed more light on the difference between Hyperledger vs. Quorum vs. Corda, the private blockchains. Check below for Hyperledger vs. Quorum vs. Corda activity protocols over the years.

Hyperledger vs. Quorum vs. Corda

Node Permissioning

Hyperledger, Quorum, and Corda all are private, permissioned blockchains, meaning that participation in the network is restricted and not anyone can be part of the blockchain. A governing entity (typically a set of participants) allows the entry of participants in the blockchain and also decides the permissions of the other nodes/peers.

So in Hyperledger, the governing peers allow and provide permission to other nodes for any sort of transaction. This type of access control can be done on a node, channel, or even consortium level. Read more about Hyperledger node permissions in this article.

Corda has file-based configurations to access nodes and their permissions. Contrary to other blockchains, in Corda, data is shared only on a need-to-know basis instead of global broadcasts. Learn how nodes interact with others in Corda in this article.

Whereas in Quorum, node permissioning is specified in smart contracts. In technical words, a json file containing a permission flag is maintained for it. Read more about node permissioning in Quorum.

Consensus Algorithm

In the case of Hyperledger, rather than the sequential execution of transactions, multiple transactions can be executed simultaneously which enhances the performance of the system. For transactions to be executed and affirmed, Hyperledger follows the KAFKA and the RAFT algorithms to arrive at a consensus.

Corda was designed to especially serve banks and financial institutions and overcome challenges faced by this particular field. Hence, Corda coined the “Notaries” concept wherein the notaries validate the transactions and add blocks to the chain. Go through this documentation to know about Corda Notaries.

Quorum uses a protocol called the QuorumChain to reach consensus. A simple voting process that confirms transactions using the majority coupled with BFT and RAFT algorithms is used by this blockchain.

Smart Contract Logic

Hyperledger uses the Chaincode as its business logic. Chaincode can be written in any standard programming language like Node.js, Go, and Java.

As said above, Corda was developed for banks and financial institutes which emphasizes the need for a legal agreement between participants. Thus, Corda implements smart contracts coupled with Ricardian contracts to obtain validity and security. For Corda, the smart contract can be written using Java or Kotlin programming languages.

Quorum supports both public and private contracts which are written in Solidity programming language.

Currency/Tokens

Hyperledger facilitates the creation of native currencies as well as digital tokens using the FabToken management system.

Corda offers an SDK that allows the development of native tokens, issuance, and trading of the tokens.

The JPM coin is the digital currency of the Quorum Blockchain.

Conclusion

Enterprise blockchains are hugely popular and are much in demand for their scalable and adaptable characteristics. Hyperledger, Corda, and Quorum all offer privacy, robust mechanisms, scalability, and enhance blockchain performance. While Corda and Quorum have simple architecture, Hyperledger is more modular. Hence, it is up to organizations to decide which blockchain is more suitable and can be altered to their business needs.

Sunday, April 25, 2021

Simplified Blockchain Part 2: Ethereum Example With Java Client

 Source: Simplified Blockchain Part 2: Ethereum Example With Java Client - DZone Security

Simplified Blockchain Part 2: Ethereum Example With Java Client

Simple example explaining how powerful blockchain is.

by  CORE ·
 Jun. 01, 20 · Security Zone · Tutorial

In the previous article, we got acquainted with the theoretical foundations of the blockchain. In this article, we implement the functionality of the passport office.

Before You Start

In order to generate and deploy smart contract, you need to install next tools:

  • Solc — Solidity compiler: Solc download link
  • Ganache-cli —Testing Ethereum network, to install execute: npm install -g ganache-cli
  • Web3j — Tool to generate java client. to install execute next command in windows power shell:

Simplified Blockchain Part One: Theory

Source: Simplified Blockchain Part One: Theory - DZone Security

 · Security Zone · Presentation

Blockchain in Two Words

You can interpret blockchain as a distributed database, each node of which is launched on the client side. All nodes synchronize (validate and confirm) all transactions among themselves. Every deployed smart contract (code and variables) stays there forever with its unique id. Initially, blockchain was created as a way to store information about sending/receiving money between clients. New blockchain systems are significantly different — they let users deploy and execute functions + variables, also known as smart contracts. Smart contracts turned these databases into real, stateful servers.

Classical Server vs Blockchain Network

To simplify your understanding of blockchain, check out the figure and table below:

Traditional server vs Blockchain network


Classic Java EE server Blockchain network
Is it decentralized?No. Can be clustered (but still not decentralized)Yes it's decentralized and all nodes synchronize the same state.
Is it possible to redeploy artifacts? Each component (java class eg jar/war/ear) can be redeployedEvery new component (smart contract) is persisted forever with it's unique hash. Every new deploy create new version of the component
What I need to do to hack the application? Put troyan inside deployed component/crack database/social engineering (bride server administrator) In the best case you need to replace (half + 1 node)
Can persiste a lot of data? Yes, often servers tons of hdd/ram memory Each node has to replicate all the data. Big size nodes became useless quickly. Rather looks like text/transaction storage
Is it possible to brut force security once you have source code? Depends on security implementation. Often it's possible.No chance. To brutforce regular Ethereum account private key  - billion years

Key Advantages of Blockchain

Code can be trusted:

1. Each transaction executed on blockchain being verified by (half + 1) node. To falsify it, you need to falsify more than half of the nodes. This is practically impossible.

2. Each contract (also known as a class in Java) has its unique hash and can't be redeployed. An executed contract is the right contract you execute.

3. All transactions (a.k.a. blocks) in blockchain have a specific hash that is compatible with the next and previous transactions. Quite similar to GIT. So no transaction can be injected somewhere in the middle.  

So if we deploy the same code twice, we can see unique transaction hash and unique contract address.

Unique contract address

Two deploy of the same code result

Access is invulnerablePrivate key by number

Each contract is being executed by account (built in feature). Ethereum account key has 256 bit complexity. Brute force of such key takes more than a billions years.

When Blockchain Is Useful

Because of this, two advantages blockchain platforms can be used as trusted, incorruptible third-party player eg:

  • Casino: blockchain protects casino by holding a bet and protect player from game falsification. 
  • Signing  juridical contact: blockchain helps to sign contract by both sides in one single action and store that contract without any possible change. So you do not need the presence of a lawyer/realtor as evidence of the authenticity of the contract. 
  • Government systems: blockchain systems protected from any falsification (even bribed internal employees) and stays completely invaluable to attacks even if application been stolen. 

Implementing Passport Office System on Blockchain

In Sweden, their national passport service is based on blockchain systems. Let's create the same simplified service using Ethereum in the next article.