2018-10-29

Java Sound API Example

The Sound API is a low-level API for creating, modifying, and controlling the input and output of sound media, including both audio and MIDI (Musical Instrument Digital Interface) data. The JavaSound API provides explicit control over the capabilities normally required for sound input and output, in a framework that promotes extensibility and flexibility.

The public JavaSound API consists of two main packages:

  • javax.sound.sampled (interfaces and classes for sampled audio)
  • javax.sound.midi (interfaces and classes for MIDI).
  • javax.sound.sampled.spi
  • javax.sound.midi.spi

Java 12 features

JDK 12

This release will be the Reference Implementation of version 12 of the Java SE Platform, as specified by JSR 386 in the Java Community Process.

Status

The development repositories are open for bug fixes, small enhancements, and JEPs as proposed and tracked via the JEP Process.

Schedule

2018/12/13Rampdown Phase One (fork from main line)
2019/01/17Rampdown Phase Two
2019/02/07Release-Candidate Phase
2019/03/19General Availability

Features

JEPs targeted to JDK 12, so far
325: Switch Expressions (Preview)
326: Raw String Literals (Preview)
340: One AArch64 Port, Not Two
341: Default CDS Archives

Java 11 features

JDK 11 is the open-source reference implementation of version 11 of the Java SE 11 Platform as specified by by JSR 384 in the Java Community Process.
JDK 11 reached General Availability on 25 September 2018. Production-ready binaries under the GPL are available from Oracle; binaries from other vendors will follow shortly.
The features and schedule of this release were proposed and tracked via the JEP Process, as amended by the JEP 2.0 proposal. The release was produced using the JDK Release Process (JEP 3).

Features

181: Nest-Based Access Control
309: Dynamic Class-File Constants
315: Improve Aarch64 Intrinsics
318: Epsilon: A No-Op Garbage Collector
320: Remove the Java EE and CORBA Modules
321: HTTP Client (Standard)
323: Local-Variable Syntax for Lambda Parameters
324: Key Agreement with Curve25519 and Curve448
327: Unicode 10
328: Flight Recorder
329: ChaCha20 and Poly1305 Cryptographic Algorithms
330: Launch Single-File Source-Code Programs
331: Low-Overhead Heap Profiling
332: Transport Layer Security (TLS) 1.3
333: ZGC: A Scalable Low-Latency Garbage Collector
   (Experimental)

335: Deprecate the Nashorn JavaScript Engine
336: Deprecate the Pack200 Tools and API

PUBG mobile not responding after match end.


2018-10-28

Java String strip() method Example

String strip() method


String strip() method added in jdk 11.

String strip() 

Returns a string whose value is this string, with all leading and trailing white space removed.
If this String object represents an empty string, or if all code points in this string are white space, then an empty string is returned.

Otherwise, returns a substring of this string beginning with the first code point that is not a white space up to and including the last code point that is not a white space.

This method may be used to strip white space from the beginning and end of a string.

strip method remove the extra space from both side.

Java Program Example:

class StripMethodExample{
public static void main(String args[]){
//with var variable
var test = "     hello!   ";
System.out.println(test.strip());

//with String class
String test1 = "     hello!   ";
System.out.println(test1.strip());
}
}

Output:

hello!
hello!


Java 11 : repeat method example

repeat method accept a integer parameter and repeat variable that many time.

var test = " hello ";
System.out.println(test.repear(3));

Output:
hello   hello   hello

Java 10 : Garbage Collector

The GC interface would be defined by the existing class CollectedHeap which every garbage collector needs to implement. The CollectedHeap class would drive most aspects of interaction between the garbage collector and the rest of HotSpot (there a few utility classes needed prior to a CollectedHeap being instantiated). More specifically, a garbage collector implementation will have to provide:
  • The heap, a subclass of CollectedHeap
  • The barrier set, a subclass of BarrierSet, which implements the various barriers for the runtime
  • An implementation of CollectorPolicy
  • An implementation of GCInterpreterSupport, which implements the various barriers for a GC for the interpreter (using assembler instructions)
  • An implementation of GCC1Support, which implements the various barriers for a GC for the C1 compiler
  • An implementation of GCC2Support, which implements the various barriers for a GC for the C2 compiler
  • Initialization of eventual GC specific arguments
  • Setup of a MemoryService, the related memory pools, memory managers, etc.
The code for implementation details that are shared between multiple garbage collectors should exist in a helper class. This way it can easily be used by the different GC implementations. For example, there could be a helper class that implements the various barriers for card table support, and any GC that requires card table post-barriers would call the corresponding methods of that helper class. This way the interface provides flexibility to implement completely new barriers, and at the same time allows for reuse of existing code in a mix-and-match style.

Java 10 : 'var' variable example

'var' keyword - "var" variable introduced in Java 10 to declared any type of datatype.

Example:

var message= "hello";
var size = 10;
var array = new String[]{"1","2","3"};

for(var i=0;i<10;i++){
}


var in collection:

var map = getMap();

public Map<String,String> getMap(){
Map<String,String> m=new HashMap<>();
m.put("1","1");
return m;
}

Java 9 : JShell example

In your command prompt, type jshell and press enter.
You will see a message and then a jshell> prompt:


Use Ctrl + A to reach the beginning of the line and Ctrl + E to reach the end of the line.

1)
/help intro
or
/help
help you in interacting with JShell

2)
/imports java.lang.Object
This imports the Object class

3)
Let's declare an Employee class.
class Employee{
private String empId;
public String getEmpId() {
return empId;
}
public void setEmpId ( String empId ) {
this.empId = empId;
}
}

4)
/open 
loading the code from within a file.
/open Test.java
It will load the Test class definition and create an Test object.


Java 9 : Unified logging for JVM

Java 9 implemented JEP 158: Unified JVM Logging, which requested to introduce a common logging system for all the components of the JVM. The main components of JVM include the following:

  • Class loader
  • Runtime data area
       Stack area
       Method area
       Heap area
       PC registers
       Native method stack


  • Execution engine

          Interpreter
          The JIT compiler
          Garbage collection
          Native method interface JNI
          Native method library

Java 9 : HTTP POST request example

1. Create an instance of HttpClient using its HttpClient.Builder builder:

HttpClient client = HttpClient.newBuilder().build();

2. Create the required data to be passed into the request body:
Map<String, String> requestBody =
Map.of("key1", "value1", "key2", "value2");

3. Create a HttpRequest object with the request method as POST and by providing
the request body data as String. We make use of Jackson's ObjectMapper to
convert the request body, Map<String, String>, into a plain JSON String and then
make use of HttpRequest.BodyProcessor to process the String request body:

ObjectMapper mapper = new ObjectMapper();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://httpbin.org/post")).POST(
HttpRequest.BodyProcessor.fromString(
mapper.writeValueAsString(requestBody)))
.version(HttpClient.Version.HTTP_1_1).build();

4. The request is sent and the response is obtained by using the send(HttpRequest,
HttpRequest.BodyHandler) method:

HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandler.asString());

5. We then print the response status code and the response body sent by the server:

System.out.println("Status code: " + response.statusCode());
System.out.println("Response Body: " + response.body());

Java 9 : HTTP GET request example

Using the JDK 9 HTTP Client API to make a GET request to the URL

Package

  • jdk.incubator.http.HttpClient
  • jdk.incubator.http.HttpRequest
  • java.net.URI
  1. HttpClient client = HttpClient.newBuilder().build();
  2. HttpRequest request = HttpRequest.newBuilder(new URI("http://java.com")).GET().version(HttpClient.Version.HTTP_1_1).build();
  3. HttpResponse<String> response = client.send(request,HttpResponse.BodyHandler.asString());
  4. System.out.println("Status code: " + response.statusCode());
  5. System.out.println("Response Body: " + response.body());


Print the status code and the response body.


2018-10-26

Producing and consuming JSON or XML in Java REST Services with Jersey

Maven dependencies


<dependencies>
  <dependency>
 <groupId>com.sun.jersey</groupId>
 <artifactId>jersey-bundle</artifactId>
 <version>1.19.3</version>
 </dependency>
 <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.17.1</version>
</dependency>
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.9.10</version>
 </dependency>
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-core-asl</artifactId>
 <version>1.9.10</version>
 </dependency>
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-xc</artifactId>
 <version>1.9.10</version>
 </dependency>
 <dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-jaxrs</artifactId>
 <version>1.9.10</version>
 </dependency>
 <dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>javax.servlet-api</artifactId>
 <version>3.1.0</version>
 <scope>provided</scope>
 </dependency>
    <dependency>
    <groupId>oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
    </dependency>
  </dependencies>


Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>st</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>Web</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>st</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>


JSON and XML POJO class


@XmlRootElement 
public class User {
private String name;
private String time;
private String price;
private String location;

//getter and setter
}



2018-10-21

Java - Stream Operations and Pipelines

java.util.stream 

This package allows you to have a declarative presentation
of the procedures that can be subsequently applied to the data, also in parallel; these
procedures are presented as streams, which are objects of the Stream interface. For
better transition from the traditional collections to streams, two default methods
(stream() and parallelStream()) were added to the java.util.Collection interface along
with the addition of new factory methods of stream generation to the Stream interface.

This approach takes advantage of the power of composition, discussed in one of the
previous chapters. Together with other design principles--encapsulation, interface,
and polymorphism--it facilitates a highly extensible and flexible design, while
lambda expressions allow you to implement it in a concise and succinct manner.
Today, when the machine learning requirements of massive data processing and the
fine-tuning of operations have become ubiquitous, these new features reinforce
the position of Java among the few modern programming languages of choice.

Java 9 : functional programming

Functional programming--the ability to treat a certain piece of functionality as an
object and to pass it as a parameter or the return value of a method--is a feature
present in many programming languages. It avoids the changing of an object state
and mutable data. The result of a function depends only on the input data, no matter
how many times it is called. This style makes the outcome more predictable, which
is the most attractive aspect of functional programming.

Its introduction to Java also allows you to improve parallel programming capabilities
in Java 8 by shifting the responsibility of parallelism from the client code to the
library. Before this, in order to process elements of Java collections, the client code
had to acquire an iterator from the collection and organize the processing of the
collection.


java 9 : Modular Programming

Modular programming enables one to organize code into independent, cohesive
modules, which can be combined together to achieve the desired functionality. This
allows in creating code that is:

More cohesive because the modules are built with a specific purpose, so the
code that resides there tends to cater to that specific purpose.
Encapsulated because modules can interact with only those APIs that have been
made available by the other modules.
Reliable because the discoverability is based on the modules and not on the
individual types. This means that if a module is not present, then the dependent
module cannot be executed until it is discoverable by the dependent module.
This helps in preventing runtime errors.
Loosely coupled. If you use service interfaces, then the module interface and
the service interface implementation can be loosely coupled.


So, the thought process in designing and organizing the code will now involve
identifying the modules, code, and configuration files, which go into the module and
the packages in which the code is organized within the module. After that, we have
to decide the public APIs of the module, thereby making them available for use by
dependent modules.

Reliable configuration: Developers have long suffered from the brittle, errorprone classpath mechanism for configuring program components. The classpath
cannot express relationships between components, so if a necessary component
is missing, then that will not be discovered until an attempt is made to use it.
The classpath also allows classes in the same package to be loaded from
different components, leading to unpredictable behavior and difficult-todiagnose errors. The proposed specification will allow a component to declare
that it depends upon other components as other components depend upon it.

Strong encapsulation: The access-control mechanism of the Java programming
language and the JVM provides no way for a component to prevent other
components from accessing its internal packages. The proposed specification
will allow a component to declare its packages that are accessible by other
components and those that are not.

The JSR further goes to list the advantages that result from addressing the preceding
issues, as follows:

A scalable platform: The ever-increasing size of the Java SE platform has
made it increasingly difficult to use in small devices, despite the fact that many
such devices are capable of running an SE-class JVM. The compact profiles
introduced in Java SE 8 (JSR 337) help in this regard, but they are not nearly
flexible enough. The proposed specification will allow the Java SE platform and
its implementations to be decomposed into a set of components that can be
assembled by developers into custom configurations that contain only the
functionality actually required by an application.

Greater platform integrity: Casual use of APIs that are internal to Java SE
platform implementations is both a security risk and a maintenance burden. The
strong encapsulation provided by the proposed specification will allow
components that implement the Java SE platform to prevent access to their
internal APIs.

Improved performance: Many ahead-of-time, whole-program optimization
techniques can be more effective when it is known that a class can refer only to
classes in a few other specific components rather than to any class loaded at
runtime. Performance is especially enhanced when the components of an
application can be optimized in conjunction with the components that
implement the Java SE platform.

Java 9 : HTML5 in Javadocs - HTML5 tags in the Javadoc comments

Generate javadocs to HTML content using java command

HTML5 provides better browser compatibility. It is also more mobile-friendly than
its predecessor, HTML4. But to take advantage of HTML5, one has to specify the html5 parameter during Javadoc generation. Otherwise, only HTM4-style comments
will continue to be supported.

Here is an example of the HTML5 tags used for Javadoc comments:
/**
<h2>Returns the weight of the car.</h2>
<article>
<h3>If life would be often that easy</h3>
<p>
Do you include unit of measurement into the method name or not?
</p>
<p>
The new signature demonstrates extensible design of an interface.
</p>
</article>
<aside>
<p> A few other examples could be found
<a href="http://www.nicksamoylov.com/cat/programming/">here</a>.
</p>
</aside>
* @param weightUnit - an element of the enum Car.WeightUnit
* @return the weight of the car in the specified units of weight
*/
int getMaxWeight(WeigthUnit weightUnit);

If you are using IntelliJ IDEA, go to Tools | Generate JavaDoc... and set the -html5
value in the Other command line arguments field and click on OK. Without an IDE,
use the following command:

javadoc [options] [packagenames] [sourcefiles] [@files]

The resulting Javadoc will look like this:



Java 9 : jmod

JMOD is a new format for packaging your modules. This format allows including
native code, configuration files, and other data that do not fit into JAR files. The
JDK modules have been packaged as JMOD files.
The jmod command-line tool allows create, list, describe, and hash JMOD files:
create:


  • This is used to create a new jmod file
  • list: This is used to list the contents of a jmod file
  • describe: This is used to describe module details
  • hash: This is used to record hashes of tied modules

Java 9 : jlink

This tool is used to select modules and create a smaller runtime image with the selected modules.

$> jlink --module-path mods/:$JAVA_HOME/jmods/ --add-modules com.packt --output img

Looking at the contents of the img folder, we should find that it has the bin, conf, include, and lib directories.

Java 9 : jdeps

This tool analyses your code base specified by the path to the .class file, directory, or  JAR, lists the package-wise dependency of your application, and also lists the JDK module in which the package exists. This helps in identifying the JDK modules that the application depends on and is the first step in migrating to modular applications.

We can run the tool on our HelloWorldXml example written earlier and see what jdeps provides:

$> jdeps mods/com.packt/
com.packt -> java.base
com.packt -> java.xml.bind
com.packt -> java.io                                  java.base
com.packt -> java.lang                              java.base
com.packt -> javax.xml.bind                     java.xml.bind
com.packt -> javax.xml.bind.annotation   java.xml.bind

2018-10-19

Java 9 : jdeprscan

This tool is used for scanning the usage of deprecated APIs in a given JAR file,
classpath, or source directory. Suppose we have a simple class that makes use of the
deprecated method, addItem, of the  java.awt.List class, as follows:

import java.awt.List;
public class Test{
public static void main(String[] args){
List list = new List();
list.addItem("Hello");
}
}

Compile the preceding class and then use jdeprscan, as follows:

C:Program FilesJavajdk-9bin>jdeprscan.exe -cp . Test

You will notice that this tool prints out class Test uses method java/awt/List addItem (Ljava/lang/String;) deprecated, which is exactly what we expected.

Java 9 : more concurrency updates

In this update, a new class, java.util.cuncurrent.Flow, has been introduced, which has java.util.concurrent nested interfaces supporting the implementation of a publish-subscribe framework. The publish-subscribe framework enables developers to build components that
can asynchronously consume a live stream of data by setting up publishers that produce the data and subscribers that consume the data via subscription, which manages them. The four new interfaces are as follows:

  • java.util.concurrent.Flow.Publisher
  • java.util.concurrent.Flow.Subscriber
  • java.util.concurrent.Flow.Subscription (which acts as both and Subscriber).
  • java.util.concurrent.Flow.Processor

Java 9 : multi-release JAR files

As of now, JAR files can contain classes that can only run on the Java version they
were compiled for. To leverage the new features of the Java platform on newer
versions, the library developers have to release a newer version of their library.
Soon, there will be multiple versions of the library being maintained by the
developers, which can be a nightmare. To overcome this limitation, the new feature
of multirelease JAR files allows developers to build JAR files with different versions
of class files for different Java versions. The following example makes it more clear.

Here is an illustration of the current JAR files:
jar root
  • - A.class
  • - B.class
  • - C.class

Here is how multirelease JAR files look:

jar root
- A.class
- B.class
- C.class
  - META-INF
     - versions
        - 9
             - A.class
        - 10
             - B.class
In the preceding illustration, the JAR files support class files for two Java versions--9
and 10. So, when the earlier JAR is executed on Java 9, the
under the
A.class
versions
folder is picked for execution. On a platform that doesn't support multirelease
- 9
JAR files, the classes under the versions directory are never used. So, if you run the
multirelease JAR file on Java 8, it's as good as running a simple JAR file.

Java 9 : jshell -- the Java shell (Read- Eval-Print Loop)

You must have seen languages, such as Ruby, Scala, Groovy, Clojure, and others shipping with a tool, which is often called REPL (Read-Eval-Print-Loop). This REPL tool is extremely useful in trying out the language features. For example, in Scala, we can write a simple
Hello World
program as
scala> println("Hello World");

Some of the advantages of the JShell REPL are as follows:

  • Help language learners to quickly try out the language features
  • Help experienced developers to quickly prototype and experiment before
  • adopting it in their main code base
  • Java developers can now boast of an REPL

Let's quickly spawn our command prompts/terminals and run the JShell command,
as shown in the following image:



Java 9 : milling project coin

In Java SE 7, _ were introduced as part of the numbers, whereby a large number could be conveniently written by introducing _ between the digits. This helped in increasing the readability of the number, for example:

Integer large_Number = 123_123_123;
System.out.println(large_Number);

In Java SE 8, the use of _ in the variable names, as shown earlier, resulted in a warning, but in Java SE 9, this use results in an error, which means that the variables
can no longer have _ in their names.

The other changed part of this JEP is to support private methods in interfaces. Java
started with interfaces with absolutely no method implementations. Then, Java SE 8
introduced default methods that allowed interfaces to have methods with
implementations, called default methods. So any class implementing this interface
could choose not to override the default methods and use the implementation
provided in the interface.

Java SE 9 is introducing private methods, wherein the default methods in the
interfaces can share code between them by refactoring the common code into private
methods.
Another useful feature is the allowing of effectively final variables to be used with
try-with-resources. As of Java SE 8, we needed to declare a variable within the try-with-resources block, such as the following:

try(Connection conn = getConnection()){}catch(Exception ex){};

However, with Java SE 9, we can do the following:

try(conn){}catch(Exception ex){}

Here, is effectively final; that is, it has been declared and defined before, and
conn will never be reassigned during out the course of the program execution.

Java 9 : HTTP/2 client

Java's HTTP API has been the most primitive. Developers often resort to using third
party libraries, such as Apache HTTP, RESTlet, Jersey, and so on. In addition to this,
Java's HTTP API predates the HTTP/1.1 specification and is synchronous and hard
to maintain. These limitations called for the need to add a new API. The new HTTP
client API provides the following:

  • A simple and concise API to deal with most HTTP requests
  • Support for HTTP/2 specification
  • Better performance
  • Better security
  • A few more enhancements


Let's see a sample code to make an HTTP GET request using the new APIs. Below is
the module definition defined within the file

//module-info.java
module newfeatures{
requires jdk.incubator.httpclient;
}

The following code uses the HTTP Client API, which is part of
module:  jdk.incubator.httpclient

import jdk.incubator.http.*;
import java.net.URI;
public class Http2Feature{
public static void main(String[] args) throws Exception{
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://httpbin.org/get"))
.GET()
.version(HttpClient.Version.HTTP_1_1)
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandler.asString());
System.out.println("Status code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}
}


Java 9 : Process API updates

Java's Process API has been quite primitive, with support only to launch new
processes, redirect the processes' output, and error streams. In this release, the
updates to the Process API enable the following:

Get the PID of the current JVM process and any other processes spawned by the
JVM
Enumerate the processes running in the system to get information such as PID,
name, and resource usage
Managing process trees
Managing sub processes

Let's look at a sample code, which prints the current PID as well as the current
process information:

//NewFeatures.java
public class NewFeatures{
public static void main(String [] args) {
ProcessHandle currentProcess = ProcessHandle.current();
System.out.println("PID: " + currentProcess.getPid());
ProcessHandle.Info currentProcessInfo = currentProcess.info();
System.out.println("Info: " + currentProcessInfo);
}
}


Install and maintain Cygwin without Windows admin rights

These are the steps I used:
  1. Download setup-x86.exe (32bit) or setup-x86_64.exe (64bit).
  2. Run it with the “--no-admin” option
  3. During installation select the “wget” package
  4. Create /usr/local/bin/cygwin-setup.sh (for 32bit omit the “_64”):
    #! /bin/sh
    rm setup-x86_64.exe
    wget http://cygwin.com/setup-x86_64.exe
    chmod u+x setup-x86_64.exe
    run ./setup-x86_64.exe --no-admin
    
  5. Make the script executable:
    chmod ugo+x /usr/local/bin/cygwin-setup.sh
  6. Create a copy of the Cygwin terminal shortcut, rename it “Cygwin setup”
  7. Edit the shortcut target, replace
    mintty.exe -i /Cygwin-Terminal.ico -
    with
    mintty.exe -i /Cygwin-Terminal.ico /bin/bash -l -c 'cygwin-setup.sh'
Whenever you want to run the Cygwin installer to install or remove packages, you can just execute the shortcut or run cygwin-setup.sh from the Cygwin command prompt.
Alternatively, you could also use the pure command-line tool apt-cyg.

2018-10-15

java 8 map initialization

Java 8 has a number of features that can be used to create and initialize maps. Take a look at this method:       

    protected static Map<Integer, String> stdJava8() {

        return Collections.unmodifiableMap(Stream.of(
                new SimpleEntry<>(0, "zero"),
                new SimpleEntry<>(1, "one"),
                new SimpleEntry<>(2, "two"),
                new SimpleEntry<>(3, "three"),
                new SimpleEntry<>(4, "four"),
                new SimpleEntry<>(5, "five"),
                new SimpleEntry<>(6, "six"),
                new SimpleEntry<>(7, "seven"),
                new SimpleEntry<>(8, "eight"),
                new SimpleEntry<>(9, "nine"),
                new SimpleEntry<>(10, "ten"),
                new SimpleEntry<>(11, "eleven"),
                new SimpleEntry<>(12, "twelve"))
                .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
    }

Here we create a Stream of map entries. At least two implementations of Entry already exists in the

2018-10-06

Throwing egg from building problem

You have unlimited egg and 100 floor building. If you throw an egg from a floor, If an egg doesn't break when dropped from some floor then try from  others floor. You have to find a exact floor from where if you throw an egg it will break, with minimum try.

2018-10-03

Search a word in a grid

Given a 2D arrays of alphabet, search a word in that grid

Example:

[[A, A, A, R,T],
 [M, A, O, R,W],
 [C, T, L, R, L],
 [Q, A, L, X, C],
 [A, P, T, X, L]]

Search "CAT", shortest path

Found in "(0,2)", "(1,1)", "(1,2)"

2018-10-01

Intellij shortcuts keys : Synchronize

Intellij shortcuts keys : Synchronize

Press Key :   Ctrl + Alt + Y  

Intellij shortcuts keys : Save All

Intellij shortcuts keys : Save All

Press Key :  Ctrl + s 

Intellij shortcuts keys : open corresponding tool windows

Intellij shortcuts keys : open corresponding tool windows

Press Key :  Alt + #[0-9]

write a program to check if strings are rotations of each other or not


check number is power of 2 or not

given n=200
Check this number is power of two or not

Solution:

1 |  01
2 |  10
3 |  011
4 |  100
5 |  101
6 |  110
7 |  0111
8 |  1000

Check the binary digit of the number with power 

if we do n&n-1, Result will be 0

so, n&n-1 result is not 0, then that number not a power of two

Intellij shortcuts keys - Parameter Info

Intellij shortcuts keys - Parameter Info

Ctrl + P

Intellij shortcuts keys - Generate Code

Intellij shortcuts keys - Generate Code

Alt + Ins 

Intellij shortcuts keys - Show intention actions and Quick fixes

Intellij shortcuts keys - Show intention actions and Quick fixes

Alt + Enter




Intellij shortcuts keys - Search Every where

Intellij shortcuts keys for search any where

Double Shift 


Intellij shortcuts keys - Smart Code completion

Intellij IDEA shortcuts keys for Smart Code completion 

Ctrl + Shift + Space





1337x proxy List 2020

How to configure proxy in PyCharm


  1. Open PyCharm, go to File then Settings.
  2. Click at HTTP Proxy under the IDE Settings.
  3. Click and enable the Use HTTP proxy check box.
  4. Fill in the IP address or Hostname of the proxy server you want to connect to and enter the port number which is being used by the proxy server.
  5. Fill in the Login user name and enter the password for the proxy server.
  6. Click Apply then Ok to close the dialog box