diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/Java-Code-Snippets.iml b/.idea/Java-Code-Snippets.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/Java-Code-Snippets.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..ad04d8c --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..acf27cb --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,15 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..c311054 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/JsonBasics/pom.xml b/JsonBasics/pom.xml new file mode 100644 index 0000000..3af3f0a --- /dev/null +++ b/JsonBasics/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + com.example + JsonBasics + 1.0-SNAPSHOT + + + + com.fasterxml.jackson.core + jackson-databind + 2.13.0 + + + + com.google.code.gson + gson + 2.8.9 + + + + org.json + json + 20210307 + + + + + + \ No newline at end of file diff --git a/JsonBasics/src/main/java/JsonExample.java b/JsonBasics/src/main/java/JsonExample.java new file mode 100644 index 0000000..eeb0ba4 --- /dev/null +++ b/JsonBasics/src/main/java/JsonExample.java @@ -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 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>() {}.getType(); + List personList = gson.fromJson(jsonArray, listType); + for (Person p : personList) { + System.out.println("Name: " + p.getName() + ", Age: " + p.getAge()); + } + } +} diff --git a/JsonBasics/src/main/java/Person.java b/JsonBasics/src/main/java/Person.java new file mode 100644 index 0000000..27a5d4c --- /dev/null +++ b/JsonBasics/src/main/java/Person.java @@ -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; + } + +} diff --git a/JsonBasics/target/classes/JsonExample$1.class b/JsonBasics/target/classes/JsonExample$1.class new file mode 100644 index 0000000..c15931f Binary files /dev/null and b/JsonBasics/target/classes/JsonExample$1.class differ diff --git a/JsonBasics/target/classes/JsonExample.class b/JsonBasics/target/classes/JsonExample.class new file mode 100644 index 0000000..92d2757 Binary files /dev/null and b/JsonBasics/target/classes/JsonExample.class differ diff --git a/JsonBasics/target/classes/Person.class b/JsonBasics/target/classes/Person.class new file mode 100644 index 0000000..7523efc Binary files /dev/null and b/JsonBasics/target/classes/Person.class differ diff --git a/LambdasAndStreams/target/classes/Person.class b/LambdasAndStreams/target/classes/Person.class new file mode 100644 index 0000000..1dc1948 Binary files /dev/null and b/LambdasAndStreams/target/classes/Person.class differ diff --git a/LambdasAndStreams/target/classes/README-Streams.md b/LambdasAndStreams/target/classes/README-Streams.md new file mode 100644 index 0000000..dd26c58 --- /dev/null +++ b/LambdasAndStreams/target/classes/README-Streams.md @@ -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 numbers = Arrays.asList(1, 2, 3, 4, 5); +Stream streamFromList = numbers.stream(); + +int[] array = {1, 2, 3, 4, 5}; +IntStream streamFromArray = Arrays.stream(array); + +Stream streamFromIO = Files.lines(Paths.get("file.txt")); + +Stream 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)`: Filters elements based on a given condition. +* `map(Function)`: Transforms each element of the Stream to another type. +* `flatMap(Function> )`: 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)`: Performs an action for each element in the Stream. +* `collect(Collector)`: Accumulates the elements into a collection or other data structure. +* `reduce(BinaryOperator)`: 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. diff --git a/LambdasAndStreams/target/classes/StreamsAllCodeSolutions.class b/LambdasAndStreams/target/classes/StreamsAllCodeSolutions.class new file mode 100644 index 0000000..d5e1009 Binary files /dev/null and b/LambdasAndStreams/target/classes/StreamsAllCodeSolutions.class differ diff --git a/LambdasAndStreams/target/classes/StreamsCodePart2 b/LambdasAndStreams/target/classes/StreamsCodePart2 new file mode 100644 index 0000000..0fda2ab --- /dev/null +++ b/LambdasAndStreams/target/classes/StreamsCodePart2 @@ -0,0 +1,136 @@ +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class StreamsCodeDemoPart2 { + public static void main(String[] args) { + + //1. Given a sentence, find and print the frequency of each word. + String sentence = "Java is a programming language. Java is versatile."; + + Map wordFreqMap = Arrays.stream(sentence.split("\\s+")) + .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); + + +// System.out.println(wordFreqMap); + + //2. Given a list of integers, find out all the numbers starting with 1. + + List nums = Arrays.asList(12, 13, 18, 21, 90, 11); + + List numsWithOne = nums.stream().filter( n -> String.valueOf(n).startsWith("1")).collect(Collectors.toList()); + +// System.out.println(numsWithOne); + + //3. Given a list of names, group them by their first letter, and then count the number of names in each group. + + String[] names = {"Alice", "Bob", "Charlie", "Amy", "Bill", "Anna"}; + + Map namesMap = Arrays.stream(names).collect(Collectors.groupingBy(s -> s.charAt(0), Collectors.counting())); + +// System.out.println(namesMap); + + + // 4. Find and print duplicate numbers in an array if it contains multiple duplicates? + + int[] arr = {2,4,2,3,1,5, 5,78,3,1,5}; + +// Arrays.stream(arr).boxed() +// .collect(Collectors.groupingBy(e-> e, Collectors.counting())) +// .entrySet().stream() +// //key -value - 2 (k), 2(val) +// .filter(entry -> entry.getValue() > 1) +// .map(Map.Entry::getKey) +// .forEach(System.out::println); + + + // 5. How are duplicates removed from a given array in Java? +// + int[] arr2 = {2,4,2,3,1,78}; + + int[] newarr = Arrays.stream(arr).distinct().toArray(); + +// System.out.println(Arrays.toString(newarr)); + + + //6. Given a list of words, filter and print the palindromes + + List strings = List.of("level", "hello", "radar", "world", "deed"); + + List palindromeWords = strings.stream(). + filter(str -> str.equals(new StringBuilder(str).reverse().toString())).collect(Collectors.toList()); + +// System.out.println(palindromeWords); + + + // 7. How do you merge two sorted arrays into a single sorted array? + int[] array1 = {1, 3,32, 5, 7}; + int[] array2 = {2, 4, 6,62, 8}; + + int[] sortedArray = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).sorted().toArray(); +// System.out.println(Arrays.toString(sortedArray)); + + + //8. Given two lists of strings, concatenate them and remove duplicates. + + List list1 = List.of("apple", "banana", "orange"); + List list2 = List.of("banana", "kiwi", "grape"); + + List uniqueList = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toList()); +// System.out.println(uniqueList); + + + // 9. Student Grade Classification - 70 and above pass + + List students = List.of( + new Student("Alice", 85), + new Student("Bob", 60), + new Student("Charlie", 75), + new Student("David", 90) + ); + + + Map> studentMap = + students.stream().collect(Collectors.groupingBy(student -> student.grade >= 70 ? "Pass" : "Fail")); + +// System.out.println(studentMap); + + + //10. Given a list of strings, sort them according to increasing order of their length. + + List fruits = Arrays.asList("Mango","pear" ,"Apple", "Banana", "Pineapple", "Kiwi"); + + fruits.stream().sorted(Comparator.comparingInt(String::length)).forEach(System.out::println); + + + //12.Partition a list of numbers into two groups: even and odd, using a custom predicate. + List numbers1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Map> partitionedNumbers = numbers1.stream() + .collect(Collectors.partitioningBy(n -> n % 2 == 0)); + + System.out.println(partitionedNumbers); + + //13. Find the squares of the first three even numbers in a list. + + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + List firstThreeSquares = numbers.stream() + .filter(n -> n % 2 == 0) + .map(n -> n * n) + .limit(3) + .collect(Collectors.toList()); + + // 14. Flatten a list of lists + + List> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6)); + List flattenedList = listOfLists.stream() + .flatMap(List::stream) + .collect(Collectors.toList()); + + System.out.println(flattenedList); + + + + } +} diff --git a/LambdasAndStreams/target/classes/StreamsTenPracticeQuestions.class b/LambdasAndStreams/target/classes/StreamsTenPracticeQuestions.class new file mode 100644 index 0000000..0d0390e Binary files /dev/null and b/LambdasAndStreams/target/classes/StreamsTenPracticeQuestions.class differ diff --git a/LambdasAndStreams/target/classes/assets/Screenshot 2023-07-27 at 11.07.16 PM.png b/LambdasAndStreams/target/classes/assets/Screenshot 2023-07-27 at 11.07.16 PM.png new file mode 100644 index 0000000..cc18a03 Binary files /dev/null and b/LambdasAndStreams/target/classes/assets/Screenshot 2023-07-27 at 11.07.16 PM.png differ