Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/Java-Code-Snippets.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions .idea/jarRepositories.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions JsonBasics/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>JsonBasics</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
</dependencies>



</project>
83 changes: 83 additions & 0 deletions JsonBasics/src/main/java/JsonExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JsonExample {
public static void main(String[] args) {

/* Serialize & Deserialize Java object to JSON */

ObjectMapper objectMapper = new ObjectMapper(); // Create an ObjectMapper instance
Person person = new Person("John Doe", 30); // Create a sample object to be converted to JSON
try {
// Serialize Java object to JSON
String json = objectMapper.writeValueAsString(person);
System.out.println("Serialized JSON: " + json);

// Deserialize JSON to Java object
Person deserializedPerson = objectMapper.readValue(json, Person.class);
System.out.println("\nDeserialized Person:");
System.out.println("Name: " + deserializedPerson.getName());
System.out.println("Age: " + deserializedPerson.getAge());

} catch (Exception e) {
e.printStackTrace();
}

/* JSON to Object using Gson Library */

String json = "{\"name\":\"John Doe\",\"age\":30}";
// Create a Gson instance
Gson gson = new Gson();
Person person1 = gson.fromJson(json, Person.class);
// Display information from the converted object
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());

/* Object to JSON using Gson Library */

String obj_to_json = gson.toJson(person);
System.out.println(obj_to_json);

/* Iterating over JSONObject*/

String jsonString = "{\"name\":\"John\",\"age\":30}";
JSONObject obj = new JSONObject(jsonString);
System.out.println("Iterating over JSONObject:");
Iterator<String> keys = obj.keys();//all keys: name & age
while (keys.hasNext()) { //as long as there is another key
String key = keys.next(); //get next key
Object value = obj.get(key); //get next value by key
System.out.println(key + " : " + value);//print key : value
}

/* Iterating over JSONArray*/

System.out.println("Iterating over JSONArray:");
JSONArray arr = new JSONArray();
arr.put("Code");
arr.put("With");
arr.put("Ease");
for(int i=0;i<arr.length();i++)
{
Object value = arr.get(i);
System.out.println(value);
}

/* JsonArray to Java List using Gson Library */

String jsonArray = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]";
Type listType = new TypeToken<List<Person>>() {}.getType();
List<Person> personList = gson.fromJson(jsonArray, listType);
for (Person p : personList) {
System.out.println("Name: " + p.getName() + ", Age: " + p.getAge());
}
}
}
30 changes: 30 additions & 0 deletions JsonBasics/src/main/java/Person.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
public class Person {
private String name;
private int age;

// Default constructor (required for Jackson)
public Person() {}

// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
Binary file added JsonBasics/target/classes/JsonExample$1.class
Binary file not shown.
Binary file added JsonBasics/target/classes/JsonExample.class
Binary file not shown.
Binary file added JsonBasics/target/classes/Person.class
Binary file not shown.
Binary file added LambdasAndStreams/target/classes/Person.class
Binary file not shown.
57 changes: 57 additions & 0 deletions LambdasAndStreams/target/classes/README-Streams.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#

# Java Streams

A *Stream in Java* - **sequence of elements from a source**.

## Background and History

Before Java 8, working with collections in Java involved writing iterative loops and manually performing operations on the data. However, Java 8 introduced Java Streams, a game-changing feature that brought functional programming concepts to the Java language. This opened up new possibilities for writing expressive and concise code when working with collections.


## Importance of Learning Java Streams

Learning Java Streams is crucial for several reasons. Firstly, it enables you to write more readable and maintainable code. With the power of lambda expressions and functional interfaces, you can perform complex operations on collections in a more concise and expressive manner.

Secondly, Java Streams promote a declarative style of programming, where you focus on describing what you want to achieve rather than the step-by-step implementation details. This leads to cleaner code that is easier to understand and maintain.

Furthermore, Java Streams provide a higher level of abstraction, allowing you to perform common data manipulation tasks such as filtering, mapping, and reducing with simplicity and efficiency. This abstraction makes your code more modular and reusable, saving you time and effort in the long run.

## Operations

#### Stream Creation

Streams can be created from various data sources such as collections, arrays, I/O channels, or generator functions. Here are examples of creating stream

```
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> streamFromList = numbers.stream();

int[] array = {1, 2, 3, 4, 5};
IntStream streamFromArray = Arrays.stream(array);

Stream<String> streamFromIO = Files.lines(Paths.get("file.txt"));

Stream<Integer> streamFromGenerator = Stream.generate(() -> 42);

```

#### Intermediate Operations

Intermediate operations are used to transform, filter, or manipulate the elements of a Stream. They return a new Stream as a result. Some commonly used intermediate operations are:

* `filter(Predicate<T>)`: Filters elements based on a given condition.
* `map(Function<T, R>)`: Transforms each element of the Stream to another type.
* `flatMap(Function<T, Stream<R>> )`: Flattens nested Streams into a single Stream.

#### Terminal Operations

Terminal operations produce a final result or a side effect. They trigger the processing of the Stream and do not return another Stream. Examples of terminal operations are:

* `forEach(Consumer<T>)`: Performs an action for each element in the Stream.
* `collect(Collector<T, A, R>)`: Accumulates the elements into a collection or other data structure.
* `reduce(BinaryOperator<T>)`: Performs a reduction on the elements of the Stream.

#### Lazy Evaluation

Java Streams employ lazy evaluation, which means that the elements of a Stream are processed on-demand, only when a terminal operation is invoked. This approach allows for optimization by avoiding unnecessary computations and improving performance when working with large or infinite Streams.
Binary file not shown.
Loading