<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ajitesh Tiwari</title>
    <description>The latest articles on DEV Community by Ajitesh Tiwari (@ajiteshtiwari).</description>
    <link>https://dev.to/ajiteshtiwari</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F62239%2F9d0588d6-7ba1-4824-aeda-8970c31fc4a1.jpeg</url>
      <title>DEV Community: Ajitesh Tiwari</title>
      <link>https://dev.to/ajiteshtiwari</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ajiteshtiwari"/>
    <language>en</language>
    <item>
      <title>How much I have paid to Uber?</title>
      <dc:creator>Ajitesh Tiwari</dc:creator>
      <pubDate>Tue, 05 Jun 2018 19:34:33 +0000</pubDate>
      <link>https://dev.to/ajiteshtiwari/how-much-i-have-paid-to-uber-2l7c</link>
      <guid>https://dev.to/ajiteshtiwari/how-much-i-have-paid-to-uber-2l7c</guid>
      <description>&lt;p&gt;Being a developer I feel thrilled to watch conferences on machine-learning, demonstrating life like chatbots or super awesome image analysis tools.&lt;/p&gt;

&lt;p&gt;But personally I have failed multiple times in making a start towards handling/analyzing data, which as many say is the base of ML. Learning about data-analysis can be tough to start. Most of the available tutorials took me so deep in complex math formulas that I was not able to follow after a few lectures.&lt;/p&gt;

&lt;p&gt;This weekend I decided to do something basic without any knowledge about python or other tools. Had to search solutions all along the way, but was a nice experience over-all.&lt;/p&gt;

&lt;p&gt;So, I decided to scrape my historical data from Uber's website and try to find some answers like -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How much I have paid to Uber in total?&lt;/li&gt;
&lt;li&gt;How much time I have spend on Uber rides or waiting for rides?&lt;/li&gt;
&lt;li&gt;How much I have saved by choosing ride-sharing as an option?&lt;/li&gt;
&lt;li&gt;How much I have paid per km for various Uber rides?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Although data may be obtained from Uber developer APIs. But for learning important concept of web-scraping I decided to take a longer path.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;And much more, depending on how much data you scrape and how much investigative you are :D&lt;br&gt;
So let's start&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1 - Scrape data from Uber's history
&lt;/h3&gt;

&lt;p&gt;We can get uber's history from this &lt;a href="https://riders.uber.com/trips"&gt;link&lt;/a&gt;. This is a paginated endpoint which has a list of rides. Most of the information is available on this page itself.&lt;/p&gt;

&lt;p&gt;To make things more simple we have a plugin available - &lt;a href="https://chrome.google.com/webstore/detail/uber-data-extractor/ckncaneeemafoonmpammikboiakeaggp"&gt;Uber data extractor&lt;/a&gt;. We just need to open this &lt;a href="https://riders.uber.com/trips"&gt;link&lt;/a&gt; and click on the plugin. Within some-time we will have an excel sheet in our downloads with most of the information we need.&lt;/p&gt;

&lt;p&gt;This plugin iterates through the paginated endpoint -&lt;code&gt;https://riders.uber.com/trips?page={page-number}&lt;/code&gt; and fetches data to save it in an excel sheet. After collecting information we have following columns - &lt;code&gt;trip_id, date, date_time, driver, car_type, city, price, payment_method, start_time, start_address, end_time, end_address.&lt;/code&gt;          &lt;/p&gt;

&lt;p&gt;But things are not finished yet. Two important parameters are still left to be captured - &lt;code&gt;distance and trip-time.&lt;/code&gt;&lt;br&gt;
This data is available on details page of each ride, which can be accessed from &lt;code&gt;https://riders.uber.com/trips/{trip-id}&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Thankfully we have trip-ids in the data collected from above chrome plugin, using which we can generate an array of links we need to visit.&lt;/p&gt;

&lt;p&gt;Now we can use selenium and chrome-web-driver to automate opening of links and printing of fields required. Since I am not so strong in python, please ignore if I have made few basic mistakes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time


option = webdriver.ChromeOptions()

browser = webdriver.Chrome(executable_path='/Users/atiwari4/Downloads/chromedriver', chrome_options=option)

browser.get("https://riders.uber.com/trips")
time.sleep(60)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above code tries to take you to &lt;a href="https://riders.uber.com/trips"&gt;https://riders.uber.com/trips&lt;/a&gt; link, which in turn asks for authentication. We need to login into uber's account in order to process next steps.&lt;br&gt;
Thus, I have added &lt;code&gt;time.sleep(60)&lt;/code&gt;. It provides us with a buffer of 60 secs to help us complete the login process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for a in arr:
    row = []
    browser.get(a)
    time.sleep(3)
    distance = browser.find_elements_by_xpath("/html/body/div[2]/div/div[2]/div/div/div[2]/div[3]/div/div[1]/div[2]/div[2]/div/div[2]/h5")
    trip_time = browser.find_elements_by_xpath("/html/body/div[2]/div/div[2]/div/div/div[2]/div[3]/div/div[1]/div[2]/div[2]/div/div[3]/h5")
    row.append(a)
    distancex = [x.text for x in distance]
    row.append(distancex)
    trip_timex = [x.text for x in trip_time]
    row.append(trip_timex)
    print row
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here &lt;code&gt;arr&lt;/code&gt; is array of ride detail page links.&lt;/p&gt;

&lt;p&gt;Using XPath we pick the required elements from the page and print them on console. Above code may take time depending on number of trips you have completed. For more info on web-scraping using selenium, refer this &lt;a href="https://medium.com/the-andela-way/introduction-to-web-scraping-using-selenium-7ec377a8cf72"&gt;article&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Now my data-sheet looks something like &lt;a href="https://medium.com/the-andela-way/introduction-to-web-scraping-using-selenium-7ec377a8cf72"&gt;this&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2 - Analyze data using Google Colaboratory
&lt;/h3&gt;

&lt;p&gt;Google &lt;a href="https://colab.research.google.com/"&gt;colabs&lt;/a&gt; is a cloud environment which can be used to run live code.&lt;/p&gt;

&lt;p&gt;We can import sheets in colabs using various methods. Since we have our sheet already uploaded on google-sheets, we can directly access it from there.&lt;/p&gt;

&lt;p&gt;First we need to authenticate our google account with colabs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;!pip install --upgrade -q gspread
!pip install -U matplotlib

from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we are authenticated this is how we import the sheet from google-sheets&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Open our new sheet and read some data.
worksheet = gc.open('Uber').sheet1

# get_all_values gives a list of rows.
rows = worksheet.get_all_values()
print(rows)

# Convert to a DataFrame and render.
import pandas as pd
df = pd.DataFrame.from_records(rows)
df.head()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;df stands for &lt;a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html"&gt;DataFrame&lt;/a&gt; which is provided by Pandas. According to there documentation it is -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;head(n=5)&lt;/code&gt; function returns top n (default 5) rows of the data-frame.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--e0gJYjfp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/174doh6gqd4dybmgnc92.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--e0gJYjfp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/174doh6gqd4dybmgnc92.png" alt="uber-sheet"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The first row in our sheet is wrong and should me made header for the sheet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we need to define a column which has unique values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df['trip_id'].is_unique
df = df.set_index('trip_id')
df.head()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vaysMfaB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/wx4gup99dbg0et4yah73.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vaysMfaB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/wx4gup99dbg0et4yah73.png" alt="uber-sheet"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The schema looks better now. But what about data. We need to clean it, before we start looking for answers. For example, the price column is something like &lt;code&gt;₹89.53&lt;/code&gt;. We need to remove first 3 characters from that column.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df['price'] = df['price'].str.slice(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we need to remove comma from price column in order to convert its datatype to number. Also we need the data-type of date column to be of date-time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df['price'] = df['price'].str.replace(',','')
df['price'] = pd.to_numeric(df['price'])
df['date'] = pd.to_datetime(df['date'], format='%m/%d/%y')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we will have a lot of columns as NaN. Those are especially the cancelled rides, and we need to get rid of those.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import numpy as np
df['end_time'].replace('', np.nan, inplace=True)
df['end_time'].replace('Dropoff time unknown', np.nan, inplace=True)
df['start_time'].replace('', np.nan, inplace=True)

df.dropna(subset=['end_time'], inplace=True)
df.dropna(subset=['start_time'], inplace=True)
df.dropna(subset=['price'], inplace=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally the question of decade :D&lt;/p&gt;

&lt;h1&gt;
  
  
  How much I have paid to Uber?
&lt;/h1&gt;

&lt;p&gt;Just type this to get your answer -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df['price'].sum()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Turns out that I have paid &lt;strong&gt;Rs. 26852.03&lt;/strong&gt; to Uber(involving Uber Eats). We can also segregate various uber services and see what have we paid for them individually.&lt;/p&gt;

&lt;p&gt;To know exact number of uber services availed with count we need to run following code -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print pd.value_counts(df['car_type'].values, sort=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the result - &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w7nOZAkO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/475dvvfkghr3hp4kvpk0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w7nOZAkO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/475dvvfkghr3hp4kvpk0.png" alt="uber"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can also plot graphs in colabs using &lt;code&gt;matplotlib&lt;/code&gt; library. Here is an example of a time vs price graph.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9BAUQNDh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/7fcqb1voto4oudkmal71.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9BAUQNDh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/7fcqb1voto4oudkmal71.png" alt="graph"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;A thousand more answers can be retrieved from this dataset. Feel free to try new combinations and comment in the section below. &lt;/p&gt;

&lt;p&gt;Click &lt;a href="https://colab.research.google.com/drive/1NsCpZGsbdXlk-azg7AgMe7gaoy6g7_Gz"&gt;here&lt;/a&gt; for colabs sheet with many more inferences.&lt;/p&gt;

</description>
      <category>dataanalysis</category>
      <category>webscraping</category>
      <category>python</category>
      <category>googlecolabs</category>
    </item>
    <item>
      <title>Go functional with Java</title>
      <dc:creator>Ajitesh Tiwari</dc:creator>
      <pubDate>Thu, 05 Apr 2018 07:46:21 +0000</pubDate>
      <link>https://dev.to/ajiteshtiwari/go-functional-with-java-45ac</link>
      <guid>https://dev.to/ajiteshtiwari/go-functional-with-java-45ac</guid>
      <description>&lt;p&gt;Java has been the &lt;a href="https://stackify.com/popular-programming-languages-2018/" rel="noopener noreferrer"&gt;most popular language&lt;/a&gt; since it's launch, because it's creators have made sure that the language doesn't miss on anything and sustains it originality with the emerging changes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Functional Programming
&lt;/h3&gt;

&lt;p&gt;Functional programming is a programming concept that is inspired from lambda calculus. In this concept each computation is considered as a function. Although these functions should not be allowed to change state/data outside their scope.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F3%2F3b%2FFunction_machine2.svg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F3%2F3b%2FFunction_machine2.svg" alt="Function"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  Why?
&lt;/h4&gt;

&lt;p&gt;Software development is an iterative process, which involves not only writing code but also understanding code written by others. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You may find it challenging and vice-versa :D&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It can take a lot of time just to figure out the state of a particular object, if it is been changed by functions that use it as an argument. Hence making it difficult to predict the behavior of a program.&lt;/p&gt;

&lt;p&gt;Consider it like a third-party API without documentation. You are not sure of what behavior to expect when calling a particular function.&lt;/p&gt;

&lt;p&gt;It is not same with concept of functional programming. By not allowing changing state and mutable data it avoids &lt;strong&gt;&lt;a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)" rel="noopener noreferrer"&gt;side-effects&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;h4&gt;
  
  
  How?
&lt;/h4&gt;

&lt;p&gt;&lt;em&gt;All this theory is fine, but how do I use it as a Java developer?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Most of you must be thinking about this question. The answer is a new member of java family &lt;strong&gt;Lambda&lt;/strong&gt;.&lt;/p&gt;
&lt;h4&gt;
  
  
  Lambda
&lt;/h4&gt;

&lt;p&gt;Lambda is a function which acts like an object. Can be passed anywhere. Can be executed whenever needed. Can be defined in a single line. Can be created without a class. And much more. It helps to remove a lot of boilerplate code previously required by Java.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Syntax - (Parameter Declaration) -&amp;gt; {Lambda Body}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Examples -
Without parameters - () -&amp;gt; System.out.println("Hello lambda")
With one parameter - s -&amp;gt; System.out.println(s)
With two parameters - (x, y) -&amp;gt; x + y
With multiple line body - (x, y) -&amp;gt; {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Cool right? but how Java knows which lambda gets mapped to which function?&lt;/em&gt; &lt;/p&gt;

&lt;h4&gt;
  
  
  Digging Deep
&lt;/h4&gt;

&lt;p&gt;Since interfaces are the backbone of lambdas. Java has introduced a new concept known as  &lt;strong&gt;Functional Interface&lt;/strong&gt; against which a lambda is defined.&lt;/p&gt;

&lt;h4&gt;
  
  
  Functional Interface
&lt;/h4&gt;

&lt;p&gt;They are similar to normal interfaces in java with one major difference. They follow &lt;strong&gt;SAM rule&lt;/strong&gt;. According to SAM rule an interface is allowed only single abstract method (SAM). &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This check can be enforced at compile time using &lt;em&gt;@FunctionalInterface&lt;/em&gt; annotation.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;For each lambda we need to create a new functional interface? &lt;br&gt;
That's in-convenient. Right?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Looks like Java has already taken care of this issue as well.&lt;br&gt;
Package &lt;em&gt;java.util.function&lt;/em&gt; contains almost 50 functional interfaces. It is highly unlikely that you may need something out of their scope.&lt;/p&gt;
&lt;h2&gt;
  
  
  Family of functional-interfaces
&lt;/h2&gt;

&lt;p&gt;Mastering all the interfaces may seem like a lot. Rather if we just understand their families, we can point to the right interface easily.&lt;/p&gt;

&lt;p&gt;There are 4 families of functional-interfaces - &lt;/p&gt;
&lt;h3&gt;
  
  
  Consumer - Consume and Discard
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@FunctionalInterface
public interface Consumer&amp;lt;T&amp;gt; {
    void accept(T t);

    default Consumer&amp;lt;T&amp;gt; andThen(Consumer&amp;lt;? super T&amp;gt; after) {
        Objects.requireNonNull(after);
        return (T t) -&amp;gt; { accept(t); after.accept(t); };
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;It accepts an object, performs some action and returns no output. So mean :D&lt;/p&gt;
&lt;h5&gt;
  
  
  Example -
&lt;/h5&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Consumer&amp;lt;String&amp;gt; stringConsumer = string -&amp;gt; System.out.println(string);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Since lambda function and println() both accept same arguments, this can also be written using &lt;strong&gt;Method reference&lt;/strong&gt;, like this -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Consumer&amp;lt;String&amp;gt; stringConsumer = System.out::println;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Function - Map or Transform or Compute
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@FunctionalInterface
public interface Function&amp;lt;T, R&amp;gt; {
    R apply(T t);

    default &amp;lt;V&amp;gt; Function&amp;lt;V, R&amp;gt; compose(Function&amp;lt;? super V, ? extends T&amp;gt; before) {
        Objects.requireNonNull(before);
        return (V v) -&amp;gt; apply(before.apply(v));
    }

    default &amp;lt;V&amp;gt; Function&amp;lt;T, V&amp;gt; andThen(Function&amp;lt;? super R, ? extends V&amp;gt; after) {
        Objects.requireNonNull(after);
        return (T t) -&amp;gt; after.apply(apply(t));
    }

    static &amp;lt;T&amp;gt; Function&amp;lt;T, T&amp;gt; identity() {
        return t -&amp;gt; t;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It accepts one object, performs some action on it and returns another object.&lt;/p&gt;

&lt;h5&gt;
  
  
  Example -
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Function&amp;lt;String, String&amp;gt; stringStringFunction = String::toUpperCase;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Predicate - Test or Filter
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@FunctionalInterface
public interface Predicate&amp;lt;T&amp;gt; {
    boolean test(T t);

    default Predicate&amp;lt;T&amp;gt; and(Predicate&amp;lt;? super T&amp;gt; other) {
        Objects.requireNonNull(other);
        return (t) -&amp;gt; test(t) &amp;amp;&amp;amp; other.test(t);
    }

    default Predicate&amp;lt;T&amp;gt; negate() {
        return (t) -&amp;gt; !test(t);
    }

    default Predicate&amp;lt;T&amp;gt; or(Predicate&amp;lt;? super T&amp;gt; other) {
        Objects.requireNonNull(other);
        return (t) -&amp;gt; test(t) || other.test(t);
    }

    static &amp;lt;T&amp;gt; Predicate&amp;lt;T&amp;gt; isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -&amp;gt; targetRef.equals(object);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It accepts one object, and returns a boolean. Usually defines rules.&lt;/p&gt;

&lt;h5&gt;
  
  
  Example -
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Predicate&amp;lt;String&amp;gt; stringPredicate = String::isEmpty;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Supplier - Create
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@FunctionalInterface
public interface Supplier&amp;lt;T&amp;gt; {
    T get();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It accepts nothing, but returns an object. So generous :D&lt;/p&gt;

&lt;h5&gt;
  
  
  Example -
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Supplier&amp;lt;String&amp;gt; stringSupplier = () -&amp;gt; "Hello, World";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Real world
&lt;/h2&gt;

&lt;p&gt;Now it's time to apply our knowledge to some real world challenge. Let's pick up a basic programming challenge from HackerRank - &lt;a href="https://www.hackerrank.com/challenges/camelcase/problem" rel="noopener noreferrer"&gt;camelCase&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Problem - Count number of words in a camelCase string.

Example - saveChangesInTheEditor
Result - 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So our motive is not only to solve this problem, but to solve it using the &lt;strong&gt;functional&lt;/strong&gt; way.&lt;/p&gt;

&lt;p&gt;The solution is straight forward, count the number of upper-case letter in the string and the result is count + 1.&lt;/p&gt;

&lt;p&gt;To do this in functional way we need - &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stream of individual characters in the string, and&lt;/li&gt;
&lt;li&gt;A predicate which helps filter the upper-case characters.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Solution -

/* Stream - s.chars()
Predicate - Character::isUpperCase */

static long camelcase(String s) {
    return s.chars().filter(Character::isUpperCase).count() + 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Hurrray !
&lt;/h2&gt;

&lt;p&gt;A single line and the problem is solved.&lt;/p&gt;

&lt;p&gt;This approach helps developers easily understand the behavior of the snippet. The above line can easily be understood to filter upper-case chars from a string and return value of (count of chars + 1), without any side-effects. Which is what we wanted. &lt;/p&gt;

&lt;p&gt;Although becoming functional is not limited to the above example. It is something which is developed with experience, because it is about how we approach a problem. &lt;/p&gt;

&lt;p&gt;Java developers may have to put in some extra effort to learn this approach, because our minds are trained to create more code than required. :D &lt;/p&gt;

</description>
      <category>functional</category>
      <category>java</category>
      <category>lambda</category>
      <category>functionalinterface</category>
    </item>
    <item>
      <title>Java 9 Flow API</title>
      <dc:creator>Ajitesh Tiwari</dc:creator>
      <pubDate>Fri, 23 Mar 2018 04:45:36 +0000</pubDate>
      <link>https://dev.to/ajiteshtiwari/java-9-flow-api-4e38</link>
      <guid>https://dev.to/ajiteshtiwari/java-9-flow-api-4e38</guid>
      <description>&lt;h1&gt;
  
  
  Java 9 Flow API
&lt;/h1&gt;

&lt;p&gt;Flow API is Java's official support for &lt;a href="http://www.reactive-streams.org/"&gt;Reactive Streams Specification&lt;/a&gt;. It is a combination of both Iterator(Pull) and Observer(Push) patterns.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Flow API is an inter operation specification and not an end-user API like &lt;a href="https://github.com/ReactiveX/RxJava"&gt;RxJava&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you are a developer(even an outdated one :D), you must have surely heard about reactive-streams, non blocking IO, asynchronous calls, etc. &lt;/p&gt;

&lt;h4&gt;
  
  
  So why Reactive?
&lt;/h4&gt;

&lt;p&gt;Consider it as a secretary in a office - &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If they &lt;strong&gt;makes you wait&lt;/strong&gt; for meeting their boss - that's normal way.&lt;/li&gt;
&lt;li&gt;If they asks you to &lt;strong&gt;go do something else&lt;/strong&gt; and they contact you when their boss is free for meeting - that's the reactive way.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;People generally tend to think any reactive programming as improvement in speed, but it is not true. Considering both scenarios above you have to spend equal time for meeting her boss (so no improvement in speed), but you can be more productive in the second approach.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reactive programming increases scalability and stability but not speed.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Flow API
&lt;/h3&gt;

&lt;p&gt;Flow API consists of 4 basic interfaces - &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Subscriber - The Subscriber subscribes to the Publisher for the callbacks.&lt;/li&gt;
&lt;/ul&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Publisher - The publisher publishes the stream of data items to the registered subscribers.&lt;/li&gt;
&lt;/ul&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Subscription - Link between publisher and subscriber.&lt;/li&gt;
&lt;/ul&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Processor - The processor sits between the Publisher and Subscriber, and transforms one stream to another.&lt;/li&gt;
&lt;/ul&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h4&gt;
  
  
  Now it's time for some hands-on with our new Flow API
&lt;/h4&gt;

&lt;p&gt;Let's create a basic subscriber which &lt;strong&gt;asks for one data object, prints it and asks for one more.&lt;/strong&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now let's quickly use a publisher implementation provided by Java (&lt;strong&gt;SubmissionPublisher&lt;/strong&gt;) to complete our session.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;And here is our sweet output - &lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/Ok2j8YLq9PeQoM2wMg/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/Ok2j8YLq9PeQoM2wMg/giphy.gif" alt="Output.gif https://media.giphy.com/media/Ok2j8YLq9PeQoM2wMg/giphy.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here you can easily see how the submit(T item) function of publisher invokes onNext(T item) function of subscriber. &lt;/p&gt;

&lt;p&gt;But it wouldn't have been possible without request(long n) function of the subscription.&lt;/p&gt;

&lt;p&gt;The delay of 1 sec helps us see the reactive magic happening. Although it's no magic, just some code written by really smart people.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;a href="https://github.com/Ajitesh-Tiwari/Java-Flow-API"&gt;Source Code&lt;/a&gt;
&lt;/h4&gt;

</description>
      <category>java</category>
      <category>reactive</category>
      <category>flowapi</category>
    </item>
  </channel>
</rss>
