diff --git a/.sonarlint/connectedMode.json b/.sonarlint/connectedMode.json index b5ea7b90..c8dcdede 100644 --- a/.sonarlint/connectedMode.json +++ b/.sonarlint/connectedMode.json @@ -1,4 +1,4 @@ { - "sonarCloudOrganization": "nitinkc", - "projectKey": "nitinkc_JavaConcepts" -} \ No newline at end of file + "projectKey": "nitinkc_JavaConcepts", + "sonarCloudOrganization": "nitinkc" +} diff --git a/build.gradle b/build.gradle index b9277a55..a196b4e2 100644 --- a/build.gradle +++ b/build.gradle @@ -2,7 +2,33 @@ plugins { id 'java' id 'maven-publish' id "org.sonarqube" version "4.4.1.3373" //For local testing + id("com.diffplug.spotless") version "7.1.0" + } + +spotless { + format('misc') { + target '.gitattributes', '.gitignore' + trimTrailingWhitespace() + endWithNewline() + leadingSpacesToTabs() + leadingTabsToSpaces(4) + } + + java { + googleJavaFormat('1.19.2').aosp() +// reflowLongStrings() +// formatJavadoc(false) + removeUnusedImports() + } + + json { + target '**/*.json' + targetExclude '*/target/**' + simple() + } +} + group = 'JavaConcepts' version = '1.0-SNAPSHOT' diff --git a/src/main/java/com/converter/db2Dto/Data.java b/src/main/java/com/converter/db2Dto/Data.java index d4702cb5..dcf34ab5 100644 --- a/src/main/java/com/converter/db2Dto/Data.java +++ b/src/main/java/com/converter/db2Dto/Data.java @@ -11,5 +11,5 @@ public class Data { private String refDataId; private String releaseNumber; - //Other Data Fields + // Other Data Fields } diff --git a/src/main/java/com/converter/db2Dto/DataDto.java b/src/main/java/com/converter/db2Dto/DataDto.java index a1fe25ec..315dc9b4 100644 --- a/src/main/java/com/converter/db2Dto/DataDto.java +++ b/src/main/java/com/converter/db2Dto/DataDto.java @@ -8,5 +8,4 @@ public class DataDto { private String createReleaseNumber; private RefTable refData; - } diff --git a/src/main/java/com/converter/db2Dto/DbToDtoConverter.java b/src/main/java/com/converter/db2Dto/DbToDtoConverter.java index 15e6a2d8..b63dedb5 100644 --- a/src/main/java/com/converter/db2Dto/DbToDtoConverter.java +++ b/src/main/java/com/converter/db2Dto/DbToDtoConverter.java @@ -11,4 +11,4 @@ public interface DbToDtoConverter { default List convert(Collection fromCollection) { return fromCollection.stream().map(this::convert).collect(Collectors.toList()); } -} \ No newline at end of file +} diff --git a/src/main/java/com/converter/db2Dto/MyConverter.java b/src/main/java/com/converter/db2Dto/MyConverter.java index ba314f49..5d49caaf 100644 --- a/src/main/java/com/converter/db2Dto/MyConverter.java +++ b/src/main/java/com/converter/db2Dto/MyConverter.java @@ -11,4 +11,4 @@ public DataDto convert(Data data) { .refData(refDataReadDao.findById(RefTable.class, data.getRefDataId())) .build(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/converter/db2Dto/RefDataReadDao.java b/src/main/java/com/converter/db2Dto/RefDataReadDao.java index 0849140f..a010e962 100644 --- a/src/main/java/com/converter/db2Dto/RefDataReadDao.java +++ b/src/main/java/com/converter/db2Dto/RefDataReadDao.java @@ -8,5 +8,6 @@ public interface RefDataReadDao { K findById(Class theClass, String id); - List findByIds(Class theClass, Collection ids); -} \ No newline at end of file + List findByIds( + Class theClass, Collection ids); +} diff --git a/src/main/java/com/converter/db2Dto/RefTable.java b/src/main/java/com/converter/db2Dto/RefTable.java index c9eb75b3..e27a3ca5 100644 --- a/src/main/java/com/converter/db2Dto/RefTable.java +++ b/src/main/java/com/converter/db2Dto/RefTable.java @@ -1,14 +1,13 @@ package com.converter.db2Dto; +import java.io.Serial; +import javax.persistence.Column; +import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -import javax.persistence.Column; -import javax.persistence.Table; -import java.io.Serial; - @EqualsAndHashCode(callSuper = true) @Data @AllArgsConstructor @@ -17,14 +16,12 @@ public class RefTable extends ReferenceDataAuditFields { public static final String NAME = "REF_TABLE"; - @Serial - private static final long serialVersionUID = -6116147807948969283L; + @Serial private static final long serialVersionUID = -6116147807948969283L; - //@PrimaryKey + // @PrimaryKey @Column(name = "CODE_ID", nullable = false) private String codeId; @Column(name = "DISPLAY_NAME", nullable = false) private String displayName; - } diff --git a/src/main/java/com/converter/db2Dto/ReferenceDataAuditFields.java b/src/main/java/com/converter/db2Dto/ReferenceDataAuditFields.java index b8b98e94..842662f9 100644 --- a/src/main/java/com/converter/db2Dto/ReferenceDataAuditFields.java +++ b/src/main/java/com/converter/db2Dto/ReferenceDataAuditFields.java @@ -1,16 +1,15 @@ package com.converter.db2Dto; +import java.io.Serial; +import java.io.Serializable; +import java.sql.Timestamp; +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; -import java.io.Serial; -import java.io.Serializable; -import java.sql.Timestamp; - @Data @MappedSuperclass @AllArgsConstructor @@ -18,8 +17,7 @@ @SuperBuilder public class ReferenceDataAuditFields implements Serializable { - @Serial - private static final long serialVersionUID = -3784354643L; + @Serial private static final long serialVersionUID = -3784354643L; @Column(name = "START_DATE") private Timestamp startDate; @@ -32,4 +30,4 @@ public class ReferenceDataAuditFields implements Serializable { @Column(name = "CREATE_RELEASE_NUMBER") private Integer releaseNumber; -} \ No newline at end of file +} diff --git a/src/main/java/com/converter/dtoConverter/DtoConverter.java b/src/main/java/com/converter/dtoConverter/DtoConverter.java index f8303928..e235d66a 100644 --- a/src/main/java/com/converter/dtoConverter/DtoConverter.java +++ b/src/main/java/com/converter/dtoConverter/DtoConverter.java @@ -1,9 +1,9 @@ package com.converter.dtoConverter; -import java.util.function.BiConsumer; - import static java.util.Objects.isNull; +import java.util.function.BiConsumer; + public abstract class DtoConverter { public O convert(E from, O to, BiConsumer build) { diff --git a/src/main/java/com/converter/dtoConverter/DtoConvertorRunner.java b/src/main/java/com/converter/dtoConverter/DtoConvertorRunner.java index f5fef5d0..487fab5e 100644 --- a/src/main/java/com/converter/dtoConverter/DtoConvertorRunner.java +++ b/src/main/java/com/converter/dtoConverter/DtoConvertorRunner.java @@ -1,6 +1,5 @@ package com.converter.dtoConverter; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -10,12 +9,13 @@ public class DtoConvertorRunner { static Entity entity; static { - entity = Entity.builder() - .idEntity("uuid") - .someString("some String") - .ssn("ssn") - .age(29) - .build(); + entity = + Entity.builder() + .idEntity("uuid") + .someString("some String") + .ssn("ssn") + .age(29) + .build(); } public static void main(String[] args) { @@ -27,15 +27,16 @@ public static void main(String[] args) { private static List entityToDto(List entityList) { -// if(!(entityList.get(0) instanceof Entity) || entityList == null) -// return null; + // if(!(entityList.get(0) instanceof Entity) || entityList == null) + // return null; EntityToDtoConverter entityToDtoConverter = new EntityToDtoConverter(); - List dtoList = entityList.stream() - .filter(obj -> obj == null) - //.map(entity -> entityToDtoConverter.toDto(entity)) - .map(entityToDtoConverter::toDto) - .collect(Collectors.toList()); + List dtoList = + entityList.stream() + .filter(obj -> obj == null) + // .map(entity -> entityToDtoConverter.toDto(entity)) + .map(entityToDtoConverter::toDto) + .collect(Collectors.toList()); return dtoList; } diff --git a/src/main/java/com/converter/dtoConverter/Entity.java b/src/main/java/com/converter/dtoConverter/Entity.java index ec1210a5..80b56bd2 100644 --- a/src/main/java/com/converter/dtoConverter/Entity.java +++ b/src/main/java/com/converter/dtoConverter/Entity.java @@ -8,6 +8,6 @@ public class Entity { private String idEntity; private String someString; - private String ssn;//PII: Can't be send via Dto - private Integer age;//PII: Can't be send via Dto + private String ssn; // PII: Can't be send via Dto + private Integer age; // PII: Can't be send via Dto } diff --git a/src/main/java/com/converter/dtoConverter/EntityToDtoConverter.java b/src/main/java/com/converter/dtoConverter/EntityToDtoConverter.java index 75c0f67d..009fd287 100644 --- a/src/main/java/com/converter/dtoConverter/EntityToDtoConverter.java +++ b/src/main/java/com/converter/dtoConverter/EntityToDtoConverter.java @@ -4,11 +4,11 @@ public class EntityToDtoConverter extends DtoConverter { - static final BiConsumer ENTITY_TO_DTO = (entity, dto) -> { - - dto.setIdDto(entity.getIdEntity()); - dto.setDoseQtyDto(entity.getSomeString()); - }; + static final BiConsumer ENTITY_TO_DTO = + (entity, dto) -> { + dto.setIdDto(entity.getIdEntity()); + dto.setDoseQtyDto(entity.getSomeString()); + }; @Override protected Dto instantiateDto() { @@ -19,4 +19,3 @@ public Dto toDto(Entity entity) { return convert(entity, null, ENTITY_TO_DTO); } } - diff --git a/src/main/java/com/converter/entityConverter/ConverterRunner.java b/src/main/java/com/converter/entityConverter/ConverterRunner.java index c022a937..7264c238 100644 --- a/src/main/java/com/converter/entityConverter/ConverterRunner.java +++ b/src/main/java/com/converter/entityConverter/ConverterRunner.java @@ -10,6 +10,5 @@ public static void main(String[] args) { SpannerEntity spannerEntity = entityConverter.convert(db2Entity); System.out.println(spannerEntity); - } } diff --git a/src/main/java/com/converter/entityConverter/EntityConverter.java b/src/main/java/com/converter/entityConverter/EntityConverter.java index 55ded8e6..a96b9ef0 100644 --- a/src/main/java/com/converter/entityConverter/EntityConverter.java +++ b/src/main/java/com/converter/entityConverter/EntityConverter.java @@ -1,9 +1,9 @@ package com.converter.entityConverter; -import java.util.function.BiConsumer; - import static java.util.Objects.isNull; +import java.util.function.BiConsumer; + public interface EntityConverter { O convert(I input); diff --git a/src/main/java/com/entity/Address.java b/src/main/java/com/entity/Address.java index cb26140d..5e3ae34d 100644 --- a/src/main/java/com/entity/Address.java +++ b/src/main/java/com/entity/Address.java @@ -6,10 +6,8 @@ import lombok.ToString; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 3:09 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 3:09 AM */ - @Getter @Setter @AllArgsConstructor @@ -23,5 +21,4 @@ public class Address { public String State; public String Country; public int zip; - } diff --git a/src/main/java/com/entity/Beer.java b/src/main/java/com/entity/Beer.java index 33c279b7..d88907f6 100644 --- a/src/main/java/com/entity/Beer.java +++ b/src/main/java/com/entity/Beer.java @@ -1,6 +1,5 @@ package com.entity; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/entity/Cancer.java b/src/main/java/com/entity/Cancer.java index eb66c774..01141f19 100644 --- a/src/main/java/com/entity/Cancer.java +++ b/src/main/java/com/entity/Cancer.java @@ -2,10 +2,7 @@ import lombok.*; -/** - * Created by nichaurasia on Wednesday, January/29/2020 at 6:24 PM - */ - +/** Created by nichaurasia on Wednesday, January/29/2020 at 6:24 PM */ @Getter @Setter @AllArgsConstructor @@ -13,12 +10,12 @@ @ToString @EqualsAndHashCode public class Cancer { - private String state;//0 + private String state; // 0 private String cancer_sites; - private int Year;//2 + private int Year; // 2 private String sex; - private String race;//2 - private float count;//5 + private String race; // 2 + private float count; // 5 private int population; private float age_adj_Rate; } diff --git a/src/main/java/com/entity/Card.java b/src/main/java/com/entity/Card.java index a0065b6d..882eafe0 100644 --- a/src/main/java/com/entity/Card.java +++ b/src/main/java/com/entity/Card.java @@ -3,29 +3,32 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import lombok.Data; - import javax.annotation.processing.Generated; +import lombok.Data; @Data @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "id", - "uid", - "credit_card_number", - "credit_card_expiry_date", - "credit_card_type" + "id", + "uid", + "credit_card_number", + "credit_card_expiry_date", + "credit_card_type" }) @Generated("jsonschema2pojo") public class Card { @JsonProperty("id") public Integer id; + @JsonProperty("uid") public String uid; + @JsonProperty("credit_card_number") public String creditCardNumber; + @JsonProperty("credit_card_expiry_date") public String creditCardExpiryDate; + @JsonProperty("credit_card_type") public String creditCardType; } diff --git a/src/main/java/com/entity/Employee.java b/src/main/java/com/entity/Employee.java index 523b6303..3cfa9cce 100644 --- a/src/main/java/com/entity/Employee.java +++ b/src/main/java/com/entity/Employee.java @@ -1,15 +1,12 @@ package com.entity; +import java.util.Date; import lombok.Getter; import lombok.Setter; -import java.util.Date; - /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 7:36 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 7:36 PM */ - @Getter @Setter public class Employee extends Person { @@ -18,8 +15,16 @@ public class Employee extends Person { private char level; private int experience; - public Employee(String firstName, String lastName, Date dob, Ethnicity ethnicity, Address address, - String employer, double salary, char level, int experience) { + public Employee( + String firstName, + String lastName, + Date dob, + Ethnicity ethnicity, + Address address, + String employer, + double salary, + char level, + int experience) { super(firstName, lastName, dob, ethnicity, address); this.employer = employer; this.experience = experience; diff --git a/src/main/java/com/entity/EmployeeSimple.java b/src/main/java/com/entity/EmployeeSimple.java index 16d7c7a2..7e6ffb47 100644 --- a/src/main/java/com/entity/EmployeeSimple.java +++ b/src/main/java/com/entity/EmployeeSimple.java @@ -2,10 +2,7 @@ import lombok.*; -/** - * Created by nichaurasia on Thursday, February/13/2020 at 11:50 AM - */ - +/** Created by nichaurasia on Thursday, February/13/2020 at 11:50 AM */ @Getter @Setter @AllArgsConstructor diff --git a/src/main/java/com/entity/EngineeringStudent.java b/src/main/java/com/entity/EngineeringStudent.java index 57accd66..54330391 100644 --- a/src/main/java/com/entity/EngineeringStudent.java +++ b/src/main/java/com/entity/EngineeringStudent.java @@ -1,24 +1,28 @@ package com.entity; +import java.util.Date; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.Date; - /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 3:20 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 3:20 AM */ - @Getter @Setter @ToString public class EngineeringStudent extends Student { private int yearEnrolled; - public EngineeringStudent(String firstName, String lastName, Date dob, Ethnicity ethnicity, Address address, - Long enrollmentNumber, StudentOf studentOf, int yearEnrolled) { + public EngineeringStudent( + String firstName, + String lastName, + Date dob, + Ethnicity ethnicity, + Address address, + Long enrollmentNumber, + StudentOf studentOf, + int yearEnrolled) { super(firstName, lastName, dob, ethnicity, address, enrollmentNumber, studentOf); this.yearEnrolled = yearEnrolled; } diff --git a/src/main/java/com/entity/Ethnicity.java b/src/main/java/com/entity/Ethnicity.java index 8a08ed52..8623ffc5 100644 --- a/src/main/java/com/entity/Ethnicity.java +++ b/src/main/java/com/entity/Ethnicity.java @@ -1,10 +1,12 @@ package com.entity; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 3:03 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 3:03 AM */ - public enum Ethnicity { - ASIAN, NORTHAMERICAN, SOUTHAMERICAN, AFRICAN, EUROPEAN + ASIAN, + NORTHAMERICAN, + SOUTHAMERICAN, + AFRICAN, + EUROPEAN } diff --git a/src/main/java/com/entity/Person.java b/src/main/java/com/entity/Person.java index 21cc0081..ec3a1127 100644 --- a/src/main/java/com/entity/Person.java +++ b/src/main/java/com/entity/Person.java @@ -1,14 +1,11 @@ package com.entity; -import lombok.*; - import java.util.Date; +import lombok.*; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 2:58 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 2:58 AM */ - @Getter @Setter @AllArgsConstructor @@ -21,5 +18,4 @@ public class Person { private Date dob; private Ethnicity ethnicity; private Address address; - -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/SampleData.java b/src/main/java/com/entity/SampleData.java index 8aca8d6b..57761666 100644 --- a/src/main/java/com/entity/SampleData.java +++ b/src/main/java/com/entity/SampleData.java @@ -1,85 +1,168 @@ package com.entity; - import java.util.*; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 10:04 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 10:04 PM */ - public class SampleData { public static List EMPLOYEES = Arrays.asList( - new Employee("Nalini", "Parekh", new Date("03/09/1989"), Ethnicity.ASIAN, - null, "Infosys", 65256.25, 'C', 5), - new Employee("Max", "Plank", new Date("12/15/1979"), Ethnicity.NORTHAMERICAN, + new Employee( + "Nalini", + "Parekh", + new Date("03/09/1989"), + Ethnicity.ASIAN, + null, + "Infosys", + 65256.25, + 'C', + 5), + new Employee( + "Max", + "Plank", + new Date("12/15/1979"), + Ethnicity.NORTHAMERICAN, new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), - "Deloitte", 158965, 'A', 10), - new Employee("Lfg", "Ksdfewrt", new Date("02/11/1995"), Ethnicity.NORTHAMERICAN, + "Deloitte", + 158965, + 'A', + 10), + new Employee( + "Lfg", + "Ksdfewrt", + new Date("02/11/1995"), + Ethnicity.NORTHAMERICAN, new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), - "TCS", 25478, 'C', 7), - new Employee("John", "Doe", new Date("12/15/1979"), Ethnicity.NORTHAMERICAN, + "TCS", + 25478, + 'C', + 7), + new Employee( + "John", + "Doe", + new Date("12/15/1979"), + Ethnicity.NORTHAMERICAN, new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), - "Deloitte", 35698, 'C', 6), - new Employee("Android", "Apple", new Date("01/02/1990"), Ethnicity.NORTHAMERICAN, + "Deloitte", + 35698, + 'C', + 6), + new Employee( + "Android", + "Apple", + new Date("01/02/1990"), + Ethnicity.NORTHAMERICAN, new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), - "Deloitte", 78956, 'C', 6), - new Employee("Butter", "Chicken", new Date("03/01/1986"), Ethnicity.NORTHAMERICAN, + "Deloitte", + 78956, + 'C', + 6), + new Employee( + "Butter", + "Chicken", + new Date("03/01/1986"), + Ethnicity.NORTHAMERICAN, new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), - "Deloitte", 96856, 'B', 5) - ); - public static List STUDENTS = Arrays.asList( - new Student("Abbott", "Zimmerman", - new Date("01/01/1990"), Ethnicity.NORTHAMERICAN, - new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), - Long.valueOf(1100112233), StudentOf.ENGINEERING), - new Student("Abraham", "Lincoln", - new Date("01/01/1985"), Ethnicity.NORTHAMERICAN, - new Address("121 Crazy Street", null, "Nashville", "TN", "USA", 37221), - Long.valueOf(1100123456), StudentOf.ENGINEERING), - new Student("Nicholas", "D'Costa", - new Date("03/01/1978"), Ethnicity.SOUTHAMERICAN, - new Address("121 Crazy Street", null, "Mexico City", "MC", "Mexico", 123456), - Long.valueOf(1100985632), StudentOf.MEDICINE), - new Student("Mohandas", "Gandhi", - new Date("05/11/1975"), Ethnicity.ASIAN, - new Address("121 Crazy Street", null, "Porbandar", "GJ", "India", 486001), - Long.valueOf(1025698745), StudentOf.LAW), - new Student("Xi", "Xinpi", - new Date("01/12/1983"), Ethnicity.ASIAN, - new Address("121 Crazy Street", null, "Beijing", "MD", "China", 45875), - Long.valueOf(1125698745), StudentOf.SPORTS), - new Student("Nelson", "Mandella", - new Date("01/01/1989"), Ethnicity.AFRICAN, - new Address("121 Crazy Street", null, "Johannesburg", "FT", "South Africa", 147852), - Long.valueOf(1002300568), StudentOf.NURSING), - new Student("Abbott", "Zimmerman", - new Date("01/01/1990"), Ethnicity.SOUTHAMERICAN, - new Address("121 Crazy Street", null, "MAchu pichu", "MP", "Peru", 589652), - Long.valueOf(1100112233), StudentOf.ENGINEERING), - new Student("Abbott", "Zimmerman", - new Date("01/01/1990"), Ethnicity.NORTHAMERICAN, - new Address("121 Crazy Street", null, "Seattle", "WA", "USA", 84258), - Long.valueOf(1100112233), StudentOf.ENGINEERING) - ); - private static final List SIMPLE_EMPLOYEES = Arrays.asList( - new EmployeeSimple("John", 20, Double.valueOf("65000"), 'C', 5), - new EmployeeSimple("Wayne", 20, Double.valueOf("65430"), 'C', 4), - new EmployeeSimple("Dow", 30, Double.valueOf("74445"), 'B', 6), - new EmployeeSimple("Jane", 35, Double.valueOf("76546"), 'B', 5), - new EmployeeSimple("Don", 35, Double.valueOf("90000"), 'A', 10), - new EmployeeSimple("Wayne", 45, Double.valueOf("65430"), 'C', 4), - new EmployeeSimple("John", 23, Double.valueOf("75430"), 'B', 5), - new EmployeeSimple("John", 32, Double.valueOf("85430"), 'C', 12), - new EmployeeSimple(),//Testing for nulls - new EmployeeSimple(null, 99, Double.valueOf("85430"), 'C', 12), - new EmployeeSimple(null, 35, Double.valueOf("90000"), 'A', 10) - - ); + "Deloitte", + 96856, + 'B', + 5)); + public static List STUDENTS = + Arrays.asList( + new Student( + "Abbott", + "Zimmerman", + new Date("01/01/1990"), + Ethnicity.NORTHAMERICAN, + new Address("121 Crazy Street", null, "Sanford", "FL", "USA", 32771), + Long.valueOf(1100112233), + StudentOf.ENGINEERING), + new Student( + "Abraham", + "Lincoln", + new Date("01/01/1985"), + Ethnicity.NORTHAMERICAN, + new Address("121 Crazy Street", null, "Nashville", "TN", "USA", 37221), + Long.valueOf(1100123456), + StudentOf.ENGINEERING), + new Student( + "Nicholas", + "D'Costa", + new Date("03/01/1978"), + Ethnicity.SOUTHAMERICAN, + new Address( + "121 Crazy Street", + null, + "Mexico City", + "MC", + "Mexico", + 123456), + Long.valueOf(1100985632), + StudentOf.MEDICINE), + new Student( + "Mohandas", + "Gandhi", + new Date("05/11/1975"), + Ethnicity.ASIAN, + new Address( + "121 Crazy Street", null, "Porbandar", "GJ", "India", 486001), + Long.valueOf(1025698745), + StudentOf.LAW), + new Student( + "Xi", + "Xinpi", + new Date("01/12/1983"), + Ethnicity.ASIAN, + new Address("121 Crazy Street", null, "Beijing", "MD", "China", 45875), + Long.valueOf(1125698745), + StudentOf.SPORTS), + new Student( + "Nelson", + "Mandella", + new Date("01/01/1989"), + Ethnicity.AFRICAN, + new Address( + "121 Crazy Street", + null, + "Johannesburg", + "FT", + "South Africa", + 147852), + Long.valueOf(1002300568), + StudentOf.NURSING), + new Student( + "Abbott", + "Zimmerman", + new Date("01/01/1990"), + Ethnicity.SOUTHAMERICAN, + new Address( + "121 Crazy Street", null, "MAchu pichu", "MP", "Peru", 589652), + Long.valueOf(1100112233), + StudentOf.ENGINEERING), + new Student( + "Abbott", + "Zimmerman", + new Date("01/01/1990"), + Ethnicity.NORTHAMERICAN, + new Address("121 Crazy Street", null, "Seattle", "WA", "USA", 84258), + Long.valueOf(1100112233), + StudentOf.ENGINEERING)); + private static final List SIMPLE_EMPLOYEES = + Arrays.asList( + new EmployeeSimple("John", 20, Double.valueOf("65000"), 'C', 5), + new EmployeeSimple("Wayne", 20, Double.valueOf("65430"), 'C', 4), + new EmployeeSimple("Dow", 30, Double.valueOf("74445"), 'B', 6), + new EmployeeSimple("Jane", 35, Double.valueOf("76546"), 'B', 5), + new EmployeeSimple("Don", 35, Double.valueOf("90000"), 'A', 10), + new EmployeeSimple("Wayne", 45, Double.valueOf("65430"), 'C', 4), + new EmployeeSimple("John", 23, Double.valueOf("75430"), 'B', 5), + new EmployeeSimple("John", 32, Double.valueOf("85430"), 'C', 12), + new EmployeeSimple(), // Testing for nulls + new EmployeeSimple(null, 99, Double.valueOf("85430"), 'C', 12), + new EmployeeSimple(null, 35, Double.valueOf("90000"), 'A', 10)); - private SampleData() { - } // Uninstantiatable class + private SampleData() {} // Uninstantiatable class public static List getEmployees() { return (EMPLOYEES); diff --git a/src/main/java/com/entity/Student.java b/src/main/java/com/entity/Student.java index 359ee26e..f98db2d2 100644 --- a/src/main/java/com/entity/Student.java +++ b/src/main/java/com/entity/Student.java @@ -1,16 +1,13 @@ package com.entity; +import java.util.Date; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.Date; - /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 3:11 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 3:11 AM */ - @Setter @Getter @ToString @@ -18,8 +15,14 @@ public class Student extends Person { public Long enrollmentNumber; public StudentOf studentOf; - public Student(String firstName, String lastName, Date dob, Ethnicity ethnicity, - Address address, Long enrollmentNumber, StudentOf studentOf) { + public Student( + String firstName, + String lastName, + Date dob, + Ethnicity ethnicity, + Address address, + Long enrollmentNumber, + StudentOf studentOf) { super(firstName, lastName, dob, ethnicity, address); this.enrollmentNumber = enrollmentNumber; diff --git a/src/main/java/com/entity/StudentOf.java b/src/main/java/com/entity/StudentOf.java index 845ed43d..cacadee4 100644 --- a/src/main/java/com/entity/StudentOf.java +++ b/src/main/java/com/entity/StudentOf.java @@ -1,10 +1,13 @@ package com.entity; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 3:18 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 3:18 AM */ - public enum StudentOf { - ENGINEERING, NURSING, MEDICINE, LAW, MUSIC, SPORTS + ENGINEERING, + NURSING, + MEDICINE, + LAW, + MUSIC, + SPORTS } diff --git a/src/main/java/com/entity/SuspendedEmployee.java b/src/main/java/com/entity/SuspendedEmployee.java index 85f7cdbf..3e67a443 100644 --- a/src/main/java/com/entity/SuspendedEmployee.java +++ b/src/main/java/com/entity/SuspendedEmployee.java @@ -1,16 +1,13 @@ package com.entity; +import java.util.Date; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.Date; - /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 7:39 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 7:39 PM */ - @Getter @Setter @ToString @@ -18,9 +15,18 @@ public class SuspendedEmployee extends Employee { private String suspensionReasonCode; private String suspensionDuration; - public SuspendedEmployee(String firstName, String lastName, Date dob, Ethnicity ethnicity, Address address, - String employer, double salary, char level, int experience, String suspensionReasonCode, - String suspensionDuration) { + public SuspendedEmployee( + String firstName, + String lastName, + Date dob, + Ethnicity ethnicity, + Address address, + String employer, + double salary, + char level, + int experience, + String suspensionReasonCode, + String suspensionDuration) { super(firstName, lastName, dob, ethnicity, address, employer, salary, level, experience); this.suspensionReasonCode = suspensionReasonCode; this.suspensionDuration = suspensionDuration; diff --git a/src/main/java/com/entity/Vehicle.java b/src/main/java/com/entity/Vehicle.java index d06ad52e..76b69fd1 100644 --- a/src/main/java/com/entity/Vehicle.java +++ b/src/main/java/com/entity/Vehicle.java @@ -1,33 +1,31 @@ package com.entity; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.processing.Generated; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import javax.annotation.processing.Generated; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "id", - "uid", - "vin", - "make_and_model", - "color", - "transmission", - "drive_type", - "fuel_type", - "car_type", - "car_options", - "specs", - "doors", - "mileage", - "kilometrage", - "license_plate" + "id", + "uid", + "vin", + "make_and_model", + "color", + "transmission", + "drive_type", + "fuel_type", + "car_type", + "car_options", + "specs", + "doors", + "mileage", + "kilometrage", + "license_plate" }) @Generated("jsonschema2pojo") @Getter @@ -37,33 +35,46 @@ public class Vehicle { @JsonProperty("id") private Integer id; + @JsonProperty("uid") private String uid; + @JsonProperty("vin") private String vin; + @JsonProperty("make_and_model") private String makeAndModel; + @JsonProperty("color") private String color; + @JsonProperty("transmission") private String transmission; + @JsonProperty("drive_type") private String driveType; + @JsonProperty("fuel_type") private String fuelType; + @JsonProperty("car_type") private String carType; + @JsonProperty("car_options") private List carOptions = null; + @JsonProperty("specs") private List specs = null; + @JsonProperty("doors") private Integer doors; + @JsonProperty("mileage") private Integer mileage; + @JsonProperty("kilometrage") private Integer kilometrage; + @JsonProperty("license_plate") private String licensePlate; - } diff --git a/src/main/java/com/entity/WordResponse.java b/src/main/java/com/entity/WordResponse.java index a4fb6890..c2e40968 100644 --- a/src/main/java/com/entity/WordResponse.java +++ b/src/main/java/com/entity/WordResponse.java @@ -2,10 +2,7 @@ import lombok.*; -/** - * Created by nitin on Saturday, February/15/2020 at 10:17 PM - */ - +/** Created by nitin on Saturday, February/15/2020 at 10:17 PM */ @Getter @Setter @NoArgsConstructor diff --git a/src/main/java/com/entity/crossRef/Author.java b/src/main/java/com/entity/crossRef/Author.java index a5008f79..ed3e5142 100755 --- a/src/main/java/com/entity/crossRef/Author.java +++ b/src/main/java/com/entity/crossRef/Author.java @@ -4,21 +4,15 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.processing.Generated; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.annotation.processing.Generated; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "given", - "family", - "sequence", - "affiliation" -}) +@JsonPropertyOrder({"given", "family", "sequence", "affiliation"}) @Generated("jsonschema2pojo") @JsonIgnoreProperties(ignoreUnknown = true) @AllArgsConstructor @@ -29,11 +23,13 @@ public class Author { @JsonProperty("given") public String given; + @JsonProperty("family") public String family; + @JsonProperty("sequence") public String sequence; + @JsonProperty("affiliation") public List affiliation = null; - } diff --git a/src/main/java/com/entity/crossRef/ContentDomain.java b/src/main/java/com/entity/crossRef/ContentDomain.java index 82bf8d47..902ef34f 100755 --- a/src/main/java/com/entity/crossRef/ContentDomain.java +++ b/src/main/java/com/entity/crossRef/ContentDomain.java @@ -4,18 +4,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "domain", - "crossmark-restriction" -}) +@JsonPropertyOrder({"domain", "crossmark-restriction"}) @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @NoArgsConstructor @@ -25,7 +21,7 @@ public class ContentDomain { @JsonProperty("domain") public List domain = null; + @JsonProperty("crossmark-restriction") public Boolean crossmarkRestriction; - } diff --git a/src/main/java/com/entity/crossRef/Created.java b/src/main/java/com/entity/crossRef/Created.java index 4dcc4b24..5677480a 100755 --- a/src/main/java/com/entity/crossRef/Created.java +++ b/src/main/java/com/entity/crossRef/Created.java @@ -4,19 +4,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts", - "date-time", - "timestamp" -}) +@JsonPropertyOrder({"date-parts", "date-time", "timestamp"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -26,9 +21,10 @@ public class Created { @JsonProperty("date-parts") public List> dateParts = null; + @JsonProperty("date-time") public String dateTime; + @JsonProperty("timestamp") public Long timestamp; - } diff --git a/src/main/java/com/entity/crossRef/CrossRef.java b/src/main/java/com/entity/crossRef/CrossRef.java index 7855f123..78a46384 100755 --- a/src/main/java/com/entity/crossRef/CrossRef.java +++ b/src/main/java/com/entity/crossRef/CrossRef.java @@ -10,12 +10,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "status", - "message-type", - "message-version", - "message" -}) +@JsonPropertyOrder({"status", "message-type", "message-version", "message"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -25,11 +20,13 @@ public class CrossRef { @JsonProperty("status") public String status; + @JsonProperty("message-type") public String messageType; + @JsonProperty("message-version") public String messageVersion; + @JsonProperty("message") public Message message; - } diff --git a/src/main/java/com/entity/crossRef/Deposited.java b/src/main/java/com/entity/crossRef/Deposited.java index ae925aaa..ff739e25 100755 --- a/src/main/java/com/entity/crossRef/Deposited.java +++ b/src/main/java/com/entity/crossRef/Deposited.java @@ -3,19 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts", - "date-time", - "timestamp" -}) +@JsonPropertyOrder({"date-parts", "date-time", "timestamp"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -24,9 +19,10 @@ public class Deposited { @JsonProperty("date-parts") public List> dateParts = null; + @JsonProperty("date-time") public String dateTime; + @JsonProperty("timestamp") public Long timestamp; - } diff --git a/src/main/java/com/entity/crossRef/Editor.java b/src/main/java/com/entity/crossRef/Editor.java index 384fa08f..c43c61f4 100755 --- a/src/main/java/com/entity/crossRef/Editor.java +++ b/src/main/java/com/entity/crossRef/Editor.java @@ -3,20 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "given", - "family", - "sequence", - "affiliation" -}) +@JsonPropertyOrder({"given", "family", "sequence", "affiliation"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -25,11 +19,13 @@ public class Editor { @JsonProperty("given") public String given; + @JsonProperty("family") public String family; + @JsonProperty("sequence") public String sequence; + @JsonProperty("affiliation") public List affiliation = null; - } diff --git a/src/main/java/com/entity/crossRef/Facets.java b/src/main/java/com/entity/crossRef/Facets.java index a00d21eb..c055e3e8 100755 --- a/src/main/java/com/entity/crossRef/Facets.java +++ b/src/main/java/com/entity/crossRef/Facets.java @@ -7,13 +7,8 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - -}) +@JsonPropertyOrder({}) @NoArgsConstructor @Getter @Setter -public class Facets { - - -} +public class Facets {} diff --git a/src/main/java/com/entity/crossRef/Indexed.java b/src/main/java/com/entity/crossRef/Indexed.java index 900704ad..fc3b9dcc 100755 --- a/src/main/java/com/entity/crossRef/Indexed.java +++ b/src/main/java/com/entity/crossRef/Indexed.java @@ -3,19 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts", - "date-time", - "timestamp" -}) +@JsonPropertyOrder({"date-parts", "date-time", "timestamp"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -24,9 +19,10 @@ public class Indexed { @JsonProperty("date-parts") public List> dateParts = null; + @JsonProperty("date-time") public String dateTime; + @JsonProperty("timestamp") public Long timestamp; - } diff --git a/src/main/java/com/entity/crossRef/IsbnType.java b/src/main/java/com/entity/crossRef/IsbnType.java index 41149657..9da502f3 100755 --- a/src/main/java/com/entity/crossRef/IsbnType.java +++ b/src/main/java/com/entity/crossRef/IsbnType.java @@ -9,11 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "value", - "type" -}) - +@JsonPropertyOrder({"value", "type"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -22,7 +18,7 @@ public class IsbnType { @JsonProperty("value") public String value; + @JsonProperty("type") public String type; - } diff --git a/src/main/java/com/entity/crossRef/IssnType.java b/src/main/java/com/entity/crossRef/IssnType.java index d407d664..d08d401d 100755 --- a/src/main/java/com/entity/crossRef/IssnType.java +++ b/src/main/java/com/entity/crossRef/IssnType.java @@ -9,10 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "value", - "type" -}) +@JsonPropertyOrder({"value", "type"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -21,7 +18,7 @@ public class IssnType { @JsonProperty("value") public String value; + @JsonProperty("type") public String type; - } diff --git a/src/main/java/com/entity/crossRef/Issued.java b/src/main/java/com/entity/crossRef/Issued.java index 24550572..9bd46194 100755 --- a/src/main/java/com/entity/crossRef/Issued.java +++ b/src/main/java/com/entity/crossRef/Issued.java @@ -3,17 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts" -}) +@JsonPropertyOrder({"date-parts"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -22,5 +19,4 @@ public class Issued { @JsonProperty("date-parts") public List> dateParts = null; - } diff --git a/src/main/java/com/entity/crossRef/Item.java b/src/main/java/com/entity/crossRef/Item.java index 6ca5c641..ac294501 100755 --- a/src/main/java/com/entity/crossRef/Item.java +++ b/src/main/java/com/entity/crossRef/Item.java @@ -4,60 +4,59 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.ArrayList; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.ArrayList; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "indexed", - "publisher-location", - "reference-count", - "publisher", - "content-domain", - "published-print", - "DOI", - "type", - "created", - "source", - "is-referenced-by-count", - "title", - "prefix", - "author", - "member", - "deposited", - "score", - "resource", - "issued", - "references-count", - "URL", - "published", - "isbn-type", - "page", - "published-online", - "container-title", - "ISBN", - "alternative-id", - "issue", - "short-container-title", - "volume", - "language", - "subtitle", - "journal-issue", - "ISSN", - "issn-type", - "subject", - "reference", - "link", - "editor", - "edition-number", - "license", - "abstract", - "original-title" + "indexed", + "publisher-location", + "reference-count", + "publisher", + "content-domain", + "published-print", + "DOI", + "type", + "created", + "source", + "is-referenced-by-count", + "title", + "prefix", + "author", + "member", + "deposited", + "score", + "resource", + "issued", + "references-count", + "URL", + "published", + "isbn-type", + "page", + "published-online", + "container-title", + "ISBN", + "alternative-id", + "issue", + "short-container-title", + "volume", + "language", + "subtitle", + "journal-issue", + "ISSN", + "issn-type", + "subject", + "reference", + "link", + "editor", + "edition-number", + "license", + "abstract", + "original-title" }) @AllArgsConstructor @NoArgsConstructor @@ -68,91 +67,133 @@ public class Item { @JsonProperty("indexed") public Indexed indexed; + @JsonProperty("publisher-location") public String publisherLocation; + @JsonProperty("reference-count") public Integer referenceCount; + @JsonProperty("publisher") public String publisher; + @JsonProperty("content-domain") public ContentDomain contentDomain; + @JsonProperty("published-print") public PublishedPrint publishedPrint; + @JsonProperty("DOI") public String doi; + @JsonProperty("type") public String type; + @JsonProperty("created") public Created created; + @JsonProperty("source") public String source; + @JsonProperty("is-referenced-by-count") public Integer isReferencedByCount; + @JsonProperty("title") public List title = null; + @JsonProperty("prefix") public String prefix; + @JsonProperty("author") public List author = null; + @JsonProperty("member") public String member; + @JsonProperty("deposited") public Deposited deposited; + @JsonProperty("score") public Float score; + @JsonProperty("resource") public Resource resource; + @JsonProperty("issued") public Issued issued; + @JsonProperty("references-count") public Integer referencesCount; + @JsonProperty("URL") public String url; + @JsonProperty("published") public Published published; + @JsonProperty("isbn-type") public List isbnType = null; + @JsonProperty("page") public String page; + @JsonProperty("published-online") public PublishedOnline publishedOnline; + @JsonProperty("container-title") public List containerTitle = null; + @JsonProperty("ISBN") public List isbn = new ArrayList<>(); + @JsonProperty("alternative-id") public List alternativeId = null; + @JsonProperty("issue") public String issue; + @JsonProperty("short-container-title") public List shortContainerTitle = null; + @JsonProperty("volume") public String volume; + @JsonProperty("language") public String language; + @JsonProperty("subtitle") public List subtitle = null; + @JsonProperty("journal-issue") public JournalIssue journalIssue; + @JsonProperty("ISSN") public List issn = null; + @JsonProperty("issn-type") public List issnType = null; + @JsonProperty("subject") public List subject = null; + @JsonProperty("reference") public List reference = null; + @JsonProperty("link") public List link = null; + @JsonProperty("editor") public List editor = null; + @JsonProperty("edition-number") public String editionNumber; + @JsonProperty("license") public List license = null; + @JsonProperty("abstract") public String _abstract; + @JsonProperty("original-title") public List originalTitle = null; - } diff --git a/src/main/java/com/entity/crossRef/JournalIssue.java b/src/main/java/com/entity/crossRef/JournalIssue.java index 49f24d6c..0aa7975b 100755 --- a/src/main/java/com/entity/crossRef/JournalIssue.java +++ b/src/main/java/com/entity/crossRef/JournalIssue.java @@ -10,9 +10,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "issue" -}) +@JsonPropertyOrder({"issue"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -22,5 +20,4 @@ public class JournalIssue { @JsonProperty("issue") public String issue; - } diff --git a/src/main/java/com/entity/crossRef/License.java b/src/main/java/com/entity/crossRef/License.java index a9e84bab..3a2f1212 100755 --- a/src/main/java/com/entity/crossRef/License.java +++ b/src/main/java/com/entity/crossRef/License.java @@ -9,12 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "start", - "content-version", - "delay-in-days", - "URL" -}) +@JsonPropertyOrder({"start", "content-version", "delay-in-days", "URL"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -23,11 +18,13 @@ public class License { @JsonProperty("start") public Start start; + @JsonProperty("content-version") public String contentVersion; + @JsonProperty("delay-in-days") public Integer delayInDays; + @JsonProperty("URL") public String url; - } diff --git a/src/main/java/com/entity/crossRef/Link.java b/src/main/java/com/entity/crossRef/Link.java index 018cab0c..8ea86411 100755 --- a/src/main/java/com/entity/crossRef/Link.java +++ b/src/main/java/com/entity/crossRef/Link.java @@ -9,12 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "URL", - "content-type", - "content-version", - "intended-application" -}) +@JsonPropertyOrder({"URL", "content-type", "content-version", "intended-application"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -23,11 +18,13 @@ public class Link { @JsonProperty("URL") public String url; + @JsonProperty("content-type") public String contentType; + @JsonProperty("content-version") public String contentVersion; + @JsonProperty("intended-application") public String intendedApplication; - } diff --git a/src/main/java/com/entity/crossRef/Message.java b/src/main/java/com/entity/crossRef/Message.java index 1701e4d6..2adc370f 100755 --- a/src/main/java/com/entity/crossRef/Message.java +++ b/src/main/java/com/entity/crossRef/Message.java @@ -3,21 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "facets", - "total-results", - "items", - "items-per-page", - "query" -}) +@JsonPropertyOrder({"facets", "total-results", "items", "items-per-page", "query"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -26,13 +19,16 @@ public class Message { @JsonProperty("facets") public Facets facets; + @JsonProperty("total-results") public Integer totalResults; + @JsonProperty("items") public List items = null; + @JsonProperty("items-per-page") public Integer itemsPerPage; + @JsonProperty("query") public Query query; - } diff --git a/src/main/java/com/entity/crossRef/Primary.java b/src/main/java/com/entity/crossRef/Primary.java index de4003df..1190e79e 100755 --- a/src/main/java/com/entity/crossRef/Primary.java +++ b/src/main/java/com/entity/crossRef/Primary.java @@ -9,9 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "URL" -}) +@JsonPropertyOrder({"URL"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -20,5 +18,4 @@ public class Primary { @JsonProperty("URL") public String url; - } diff --git a/src/main/java/com/entity/crossRef/Published.java b/src/main/java/com/entity/crossRef/Published.java index 939da854..61a7f3e6 100755 --- a/src/main/java/com/entity/crossRef/Published.java +++ b/src/main/java/com/entity/crossRef/Published.java @@ -3,17 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts" -}) +@JsonPropertyOrder({"date-parts"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -22,5 +19,4 @@ public class Published { @JsonProperty("date-parts") public List> dateParts = null; - } diff --git a/src/main/java/com/entity/crossRef/PublishedOnline.java b/src/main/java/com/entity/crossRef/PublishedOnline.java index 72d0854d..a29efe52 100755 --- a/src/main/java/com/entity/crossRef/PublishedOnline.java +++ b/src/main/java/com/entity/crossRef/PublishedOnline.java @@ -3,18 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts" -}) - +@JsonPropertyOrder({"date-parts"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -23,5 +19,4 @@ public class PublishedOnline { @JsonProperty("date-parts") public List> dateParts = null; - } diff --git a/src/main/java/com/entity/crossRef/PublishedPrint.java b/src/main/java/com/entity/crossRef/PublishedPrint.java index b48a03e8..75f29de8 100755 --- a/src/main/java/com/entity/crossRef/PublishedPrint.java +++ b/src/main/java/com/entity/crossRef/PublishedPrint.java @@ -3,17 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts" -}) +@JsonPropertyOrder({"date-parts"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -22,5 +19,4 @@ public class PublishedPrint { @JsonProperty("date-parts") public List> dateParts = null; - } diff --git a/src/main/java/com/entity/crossRef/Query.java b/src/main/java/com/entity/crossRef/Query.java index 5ae75bcb..04374b02 100755 --- a/src/main/java/com/entity/crossRef/Query.java +++ b/src/main/java/com/entity/crossRef/Query.java @@ -9,10 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "start-index", - "search-terms" -}) +@JsonPropertyOrder({"start-index", "search-terms"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -21,7 +18,7 @@ public class Query { @JsonProperty("start-index") public Integer startIndex; + @JsonProperty("search-terms") public Object searchTerms; - } diff --git a/src/main/java/com/entity/crossRef/Reference.java b/src/main/java/com/entity/crossRef/Reference.java index d25d9da9..2ad08259 100755 --- a/src/main/java/com/entity/crossRef/Reference.java +++ b/src/main/java/com/entity/crossRef/Reference.java @@ -10,10 +10,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "key", - "unstructured" -}) +@JsonPropertyOrder({"key", "unstructured"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -23,7 +20,7 @@ public class Reference { @JsonProperty("key") public String key; + @JsonProperty("unstructured") public String unstructured; - } diff --git a/src/main/java/com/entity/crossRef/Resource.java b/src/main/java/com/entity/crossRef/Resource.java index 47ea5860..160b46e5 100755 --- a/src/main/java/com/entity/crossRef/Resource.java +++ b/src/main/java/com/entity/crossRef/Resource.java @@ -9,9 +9,7 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "primary" -}) +@JsonPropertyOrder({"primary"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -20,5 +18,4 @@ public class Resource { @JsonProperty("primary") public Primary primary; - } diff --git a/src/main/java/com/entity/crossRef/Start.java b/src/main/java/com/entity/crossRef/Start.java index 131bfeea..16c8ceca 100755 --- a/src/main/java/com/entity/crossRef/Start.java +++ b/src/main/java/com/entity/crossRef/Start.java @@ -3,19 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "date-parts", - "date-time", - "timestamp" -}) +@JsonPropertyOrder({"date-parts", "date-time", "timestamp"}) @AllArgsConstructor @NoArgsConstructor @Getter @@ -24,9 +19,10 @@ public class Start { @JsonProperty("date-parts") public List> dateParts = null; + @JsonProperty("date-time") public String dateTime; + @JsonProperty("timestamp") public Long timestamp; - } diff --git a/src/main/java/com/entity/currencyExchange/CurrencyExchange.java b/src/main/java/com/entity/currencyExchange/CurrencyExchange.java index 9ea87e69..d0dfe29e 100755 --- a/src/main/java/com/entity/currencyExchange/CurrencyExchange.java +++ b/src/main/java/com/entity/currencyExchange/CurrencyExchange.java @@ -7,15 +7,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "motd", - "success", - "query", - "info", - "historical", - "date", - "result" -}) +@JsonPropertyOrder({"motd", "success", "query", "info", "historical", "date", "result"}) @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) @@ -27,16 +19,22 @@ public class CurrencyExchange { @JsonProperty("motd") public Motd motd; + @JsonProperty("success") public Boolean success; + @JsonProperty("query") public Query query; + @JsonProperty("info") public Info info; + @JsonProperty("historical") public Boolean historical; + @JsonProperty("date") public String date; + @JsonProperty("result") public Float result; -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/currencyExchange/Info.java b/src/main/java/com/entity/currencyExchange/Info.java index 298cef65..4c104ac0 100755 --- a/src/main/java/com/entity/currencyExchange/Info.java +++ b/src/main/java/com/entity/currencyExchange/Info.java @@ -7,9 +7,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "rate" -}) +@JsonPropertyOrder({"rate"}) @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) @@ -21,5 +19,4 @@ public class Info { @JsonProperty("rate") public Float rate; - } diff --git a/src/main/java/com/entity/currencyExchange/Motd.java b/src/main/java/com/entity/currencyExchange/Motd.java index 96ff8813..3e26e4a4 100755 --- a/src/main/java/com/entity/currencyExchange/Motd.java +++ b/src/main/java/com/entity/currencyExchange/Motd.java @@ -7,10 +7,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "msg", - "url" -}) +@JsonPropertyOrder({"msg", "url"}) @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) @@ -22,7 +19,7 @@ public class Motd { @JsonProperty("msg") public String msg; + @JsonProperty("url") public String url; - } diff --git a/src/main/java/com/entity/currencyExchange/Query.java b/src/main/java/com/entity/currencyExchange/Query.java index a6d8b1e0..5e51384d 100755 --- a/src/main/java/com/entity/currencyExchange/Query.java +++ b/src/main/java/com/entity/currencyExchange/Query.java @@ -7,11 +7,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "from", - "to", - "amount" -}) +@JsonPropertyOrder({"from", "to", "amount"}) @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) @@ -23,9 +19,10 @@ public class Query { @JsonProperty("from") public String from; + @JsonProperty("to") public String to; + @JsonProperty("amount") public Integer amount; - } diff --git a/src/main/java/com/entity/dto/CovidIndiaTransformed.java b/src/main/java/com/entity/dto/CovidIndiaTransformed.java index a2986106..2933f310 100644 --- a/src/main/java/com/entity/dto/CovidIndiaTransformed.java +++ b/src/main/java/com/entity/dto/CovidIndiaTransformed.java @@ -1,23 +1,22 @@ package com.entity.dto; +import java.time.ZonedDateTime; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.time.ZonedDateTime; - @Getter @Setter @NoArgsConstructor public class CovidIndiaTransformed { private String country; - //public String countryCode; - //public String province; - //public String city; + // public String countryCode; + // public String province; + // public String city; private String cityAndState; - //public String cityCode; - //public String lat; Not needed - //public String lon; + // public String cityCode; + // public String lat; Not needed + // public String lon; private Integer confirmed; private Integer deaths; private Integer recovered; diff --git a/src/main/java/com/entity/dto/VehicleTransformed.java b/src/main/java/com/entity/dto/VehicleTransformed.java index fe17512e..5db4b048 100644 --- a/src/main/java/com/entity/dto/VehicleTransformed.java +++ b/src/main/java/com/entity/dto/VehicleTransformed.java @@ -19,10 +19,10 @@ public class VehicleTransformed { private String driveType; private String fuelType; private String carType; - private String carOptions;//Transforming from List of Strings into semi-colon separated String - private String specs;//Transforming from List of Strings into semi-colon separated String + private String carOptions; // Transforming from List of Strings into semi-colon separated String + private String specs; // Transforming from List of Strings into semi-colon separated String private Integer doors; private Integer mileage; private Integer kilometrage; private String licensePlate; -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/git/GitUser.java b/src/main/java/com/entity/git/GitUser.java index 28825531..d828e0bb 100644 --- a/src/main/java/com/entity/git/GitUser.java +++ b/src/main/java/com/entity/git/GitUser.java @@ -6,29 +6,25 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; - import javax.annotation.processing.Generated; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "provider", - "uid", - "info", - "credentials", - "extra" -}) +@JsonPropertyOrder({"provider", "uid", "info", "credentials", "extra"}) @Generated("jsonschema2pojo") public class GitUser { @JsonProperty("provider") public String provider; + @JsonProperty("uid") public String uid; + @JsonProperty("info") public Info info; + @JsonProperty("credentials") public Credentials credentials; + @JsonProperty("extra") public Extra extra; - } diff --git a/src/main/java/com/entity/git/supportEntities/Credentials.java b/src/main/java/com/entity/git/supportEntities/Credentials.java index eaa61c0f..86ecafd2 100644 --- a/src/main/java/com/entity/git/supportEntities/Credentials.java +++ b/src/main/java/com/entity/git/supportEntities/Credentials.java @@ -3,20 +3,16 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; - import javax.annotation.processing.Generated; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "token", - "expires" -}) +@JsonPropertyOrder({"token", "expires"}) @Generated("jsonschema2pojo") public class Credentials { @JsonProperty("token") public String token; + @JsonProperty("expires") public Boolean expires; - -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/git/supportEntities/Extra.java b/src/main/java/com/entity/git/supportEntities/Extra.java index a210ca1a..58e86ae2 100644 --- a/src/main/java/com/entity/git/supportEntities/Extra.java +++ b/src/main/java/com/entity/git/supportEntities/Extra.java @@ -3,17 +3,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; - import javax.annotation.processing.Generated; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "raw_info" -}) +@JsonPropertyOrder({"raw_info"}) @Generated("jsonschema2pojo") public class Extra { @JsonProperty("raw_info") public RawInfo rawInfo; - -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/git/supportEntities/Info.java b/src/main/java/com/entity/git/supportEntities/Info.java index f796a1dd..74151843 100644 --- a/src/main/java/com/entity/git/supportEntities/Info.java +++ b/src/main/java/com/entity/git/supportEntities/Info.java @@ -3,29 +3,25 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; - import javax.annotation.processing.Generated; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "nickname", - "email", - "name", - "image", - "urls" -}) +@JsonPropertyOrder({"nickname", "email", "name", "image", "urls"}) @Generated("jsonschema2pojo") public class Info { @JsonProperty("nickname") public String nickname; + @JsonProperty("email") public String email; + @JsonProperty("name") public String name; + @JsonProperty("image") public String image; + @JsonProperty("urls") public Urls urls; } diff --git a/src/main/java/com/entity/git/supportEntities/RawInfo.java b/src/main/java/com/entity/git/supportEntities/RawInfo.java index e00e6855..764e453b 100644 --- a/src/main/java/com/entity/git/supportEntities/RawInfo.java +++ b/src/main/java/com/entity/git/supportEntities/RawInfo.java @@ -3,104 +3,131 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; - import javax.annotation.processing.Generated; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "login", - "id", - "avatar_url", - "gravatar_id", - "url", - "html_url", - "followers_url", - "following_url", - "gists_url", - "starred_url", - "subscriptions_url", - "organizations_url", - "repos_url", - "events_url", - "received_events_url", - "type", - "site_admin", - "name", - "company", - "blog", - "location", - "email", - "hireable", - "bio", - "public_repos", - "public_gists", - "followers", - "following", - "created_at", - "updated_at" + "login", + "id", + "avatar_url", + "gravatar_id", + "url", + "html_url", + "followers_url", + "following_url", + "gists_url", + "starred_url", + "subscriptions_url", + "organizations_url", + "repos_url", + "events_url", + "received_events_url", + "type", + "site_admin", + "name", + "company", + "blog", + "location", + "email", + "hireable", + "bio", + "public_repos", + "public_gists", + "followers", + "following", + "created_at", + "updated_at" }) @Generated("jsonschema2pojo") public class RawInfo { @JsonProperty("login") public String login; + @JsonProperty("id") public String id; + @JsonProperty("avatar_url") public String avatarUrl; + @JsonProperty("gravatar_id") public String gravatarId; + @JsonProperty("url") public String url; + @JsonProperty("html_url") public String htmlUrl; + @JsonProperty("followers_url") public String followersUrl; + @JsonProperty("following_url") public String followingUrl; + @JsonProperty("gists_url") public String gistsUrl; + @JsonProperty("starred_url") public String starredUrl; + @JsonProperty("subscriptions_url") public String subscriptionsUrl; + @JsonProperty("organizations_url") public String organizationsUrl; + @JsonProperty("repos_url") public String reposUrl; + @JsonProperty("events_url") public String eventsUrl; + @JsonProperty("received_events_url") public String receivedEventsUrl; + @JsonProperty("type") public String type; + @JsonProperty("site_admin") public Boolean siteAdmin; + @JsonProperty("name") public String name; + @JsonProperty("company") public Object company; + @JsonProperty("blog") public Object blog; + @JsonProperty("location") public String location; + @JsonProperty("email") public String email; + @JsonProperty("hireable") public Object hireable; + @JsonProperty("bio") public Object bio; + @JsonProperty("public_repos") public Integer publicRepos; + @JsonProperty("public_gists") public Integer publicGists; + @JsonProperty("followers") public Integer followers; + @JsonProperty("following") public Integer following; + @JsonProperty("created_at") public String createdAt; + @JsonProperty("updated_at") public String updatedAt; - } diff --git a/src/main/java/com/entity/git/supportEntities/Urls.java b/src/main/java/com/entity/git/supportEntities/Urls.java index 4a695a29..18d046ee 100644 --- a/src/main/java/com/entity/git/supportEntities/Urls.java +++ b/src/main/java/com/entity/git/supportEntities/Urls.java @@ -3,17 +3,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; - import javax.annotation.processing.Generated; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "GitHub" -}) +@JsonPropertyOrder({"GitHub"}) @Generated("jsonschema2pojo") public class Urls { @JsonProperty("GitHub") public String gitHub; - -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/gutendex/Author.java b/src/main/java/com/entity/gutendex/Author.java index e8f41afd..5e7c1083 100755 --- a/src/main/java/com/entity/gutendex/Author.java +++ b/src/main/java/com/entity/gutendex/Author.java @@ -3,19 +3,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.processing.Generated; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.annotation.processing.Generated; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "name", - "birth_year", - "death_year" -}) +@JsonPropertyOrder({"name", "birth_year", "death_year"}) @Generated("jsonschema2pojo") @Getter @Setter @@ -25,9 +20,10 @@ public class Author { @JsonProperty("name") public String name; + @JsonProperty("birth_year") public Integer birthYear; + @JsonProperty("death_year") public Object deathYear; - } diff --git a/src/main/java/com/entity/gutendex/Formats.java b/src/main/java/com/entity/gutendex/Formats.java index 763767e7..3f8bdf03 100755 --- a/src/main/java/com/entity/gutendex/Formats.java +++ b/src/main/java/com/entity/gutendex/Formats.java @@ -4,31 +4,30 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.processing.Generated; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.annotation.processing.Generated; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "text/plain; charset=us-ascii", - "application/x-mobipocket-ebook", - "application/rdf+xml", - "application/epub+zip", - "text/plain", - "text/html; charset=iso-8859-1", - "text/html", - "application/zip", - "image/jpeg", - "text/plain; charset=iso-8859-1", - "text/html; charset=us-ascii", - "text/plain; charset=utf-8", - "text/html; charset=utf-8", - "audio/mpeg", - "audio/mp4", - "audio/ogg" + "text/plain; charset=us-ascii", + "application/x-mobipocket-ebook", + "application/rdf+xml", + "application/epub+zip", + "text/plain", + "text/html; charset=iso-8859-1", + "text/html", + "application/zip", + "image/jpeg", + "text/plain; charset=iso-8859-1", + "text/html; charset=us-ascii", + "text/plain; charset=utf-8", + "text/html; charset=utf-8", + "audio/mpeg", + "audio/mp4", + "audio/ogg" }) @Generated("jsonschema2pojo") @Getter @@ -40,35 +39,49 @@ public class Formats { @JsonProperty("text/plain; charset=us-ascii") public String textPlainCharsetUsAscii; + @JsonProperty("application/x-mobipocket-ebook") public String applicationXMobipocketEbook; + @JsonProperty("application/rdf+xml") public String applicationRdfXml; + @JsonProperty("application/epub+zip") public String applicationEpubZip; + @JsonProperty("text/plain") public String textPlain; + @JsonProperty("text/html; charset=iso-8859-1") public String textHtmlCharsetIso88591; + @JsonProperty("text/html") public String textHtml; + @JsonProperty("application/zip") public String applicationZip; + @JsonProperty("image/jpeg") public String imageJpeg; + @JsonProperty("text/plain; charset=iso-8859-1") public String textPlainCharsetIso88591; + @JsonProperty("text/html; charset=us-ascii") public String textHtmlCharsetUsAscii; + @JsonProperty("text/plain; charset=utf-8") public String textPlainCharsetUtf8; + @JsonProperty("text/html; charset=utf-8") public String textHtmlCharsetUtf8; + @JsonProperty("audio/mpeg") public String audioMpeg; + @JsonProperty("audio/mp4") public String audioMp4; + @JsonProperty("audio/ogg") public String audioOgg; - } diff --git a/src/main/java/com/entity/gutendex/Gutendex.java b/src/main/java/com/entity/gutendex/Gutendex.java index 6fe608ae..ac3adc19 100755 --- a/src/main/java/com/entity/gutendex/Gutendex.java +++ b/src/main/java/com/entity/gutendex/Gutendex.java @@ -3,21 +3,15 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.processing.Generated; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.annotation.processing.Generated; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "count", - "next", - "previous", - "results" -}) +@JsonPropertyOrder({"count", "next", "previous", "results"}) @Generated("jsonschema2pojo") @Getter @Setter @@ -27,11 +21,13 @@ public class Gutendex { @JsonProperty("count") public Integer count; + @JsonProperty("next") public String next; + @JsonProperty("previous") public Object previous; + @JsonProperty("results") public List results = null; - } diff --git a/src/main/java/com/entity/gutendex/Result.java b/src/main/java/com/entity/gutendex/Result.java index b87eaca3..f7d886f7 100755 --- a/src/main/java/com/entity/gutendex/Result.java +++ b/src/main/java/com/entity/gutendex/Result.java @@ -3,27 +3,26 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.processing.Generated; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.annotation.processing.Generated; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "id", - "title", - "authors", - "translators", - "subjects", - "bookshelves", - "languages", - "copyright", - "media_type", - "formats", - "download_count" + "id", + "title", + "authors", + "translators", + "subjects", + "bookshelves", + "languages", + "copyright", + "media_type", + "formats", + "download_count" }) @Generated("jsonschema2pojo") @Getter @@ -34,25 +33,34 @@ public class Result { @JsonProperty("id") public Integer id; + @JsonProperty("title") public String title; + @JsonProperty("authors") public List authors = null; + @JsonProperty("translators") public List translators = null; + @JsonProperty("subjects") public List subjects = null; + @JsonProperty("bookshelves") public List bookshelves = null; + @JsonProperty("languages") public List languages = null; + @JsonProperty("copyright") public Boolean copyright; + @JsonProperty("media_type") public String mediaType; + @JsonProperty("formats") public Formats formats; + @JsonProperty("download_count") public Integer downloadCount; - } diff --git a/src/main/java/com/entity/openLibrary/Author.java b/src/main/java/com/entity/openLibrary/Author.java index dd25fba3..9ac5ec08 100755 --- a/src/main/java/com/entity/openLibrary/Author.java +++ b/src/main/java/com/entity/openLibrary/Author.java @@ -6,10 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "url", - "name" -}) +@JsonPropertyOrder({"url", "name"}) @Getter @Setter @AllArgsConstructor @@ -20,7 +17,7 @@ public class Author { @JsonProperty("url") public String url; + @JsonProperty("name") public String name; - } diff --git a/src/main/java/com/entity/openLibrary/Classifications.java b/src/main/java/com/entity/openLibrary/Classifications.java index 6414c164..e7d3942d 100755 --- a/src/main/java/com/entity/openLibrary/Classifications.java +++ b/src/main/java/com/entity/openLibrary/Classifications.java @@ -3,15 +3,11 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import lombok.*; - import java.util.List; +import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "lc_classifications", - "dewey_decimal_class" -}) +@JsonPropertyOrder({"lc_classifications", "dewey_decimal_class"}) @Getter @Setter @AllArgsConstructor @@ -22,7 +18,7 @@ public class Classifications { @JsonProperty("lc_classifications") public List lcClassifications = null; + @JsonProperty("dewey_decimal_class") public List deweyDecimalClass = null; - } diff --git a/src/main/java/com/entity/openLibrary/Cover.java b/src/main/java/com/entity/openLibrary/Cover.java index f36f026f..3b40d7cd 100755 --- a/src/main/java/com/entity/openLibrary/Cover.java +++ b/src/main/java/com/entity/openLibrary/Cover.java @@ -6,11 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "small", - "medium", - "large" -}) +@JsonPropertyOrder({"small", "medium", "large"}) @Getter @Setter @AllArgsConstructor @@ -21,9 +17,10 @@ public class Cover { @JsonProperty("small") public String small; + @JsonProperty("medium") public String medium; + @JsonProperty("large") public String large; - } diff --git a/src/main/java/com/entity/openLibrary/Ebook.java b/src/main/java/com/entity/openLibrary/Ebook.java index 09a33ea6..65a61ed1 100755 --- a/src/main/java/com/entity/openLibrary/Ebook.java +++ b/src/main/java/com/entity/openLibrary/Ebook.java @@ -6,13 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "preview_url", - "availability", - "formats", - "borrow_url", - "checkedout" -}) +@JsonPropertyOrder({"preview_url", "availability", "formats", "borrow_url", "checkedout"}) @Getter @Setter @AllArgsConstructor @@ -23,13 +17,16 @@ public class Ebook { @JsonProperty("preview_url") public String previewUrl; + @JsonProperty("availability") public String availability; + @JsonProperty("formats") public Formats formats; + @JsonProperty("borrow_url") public String borrowUrl; + @JsonProperty("checkedout") public Boolean checkedout; - } diff --git a/src/main/java/com/entity/openLibrary/Formats.java b/src/main/java/com/entity/openLibrary/Formats.java index b0472cbb..920420a5 100755 --- a/src/main/java/com/entity/openLibrary/Formats.java +++ b/src/main/java/com/entity/openLibrary/Formats.java @@ -5,15 +5,10 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - -}) +@JsonPropertyOrder({}) @Getter @Setter @AllArgsConstructor @ToString @EqualsAndHashCode -public class Formats { - - -} +public class Formats {} diff --git a/src/main/java/com/entity/openLibrary/Identifiers.java b/src/main/java/com/entity/openLibrary/Identifiers.java index ad62938e..b657a1fb 100755 --- a/src/main/java/com/entity/openLibrary/Identifiers.java +++ b/src/main/java/com/entity/openLibrary/Identifiers.java @@ -3,21 +3,20 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import lombok.*; - import java.util.List; +import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "amazon", - "google", - "librarything", - "goodreads", - "isbn_10", - "isbn_13", - "lccn", - "oclc", - "openlibrary" + "amazon", + "google", + "librarything", + "goodreads", + "isbn_10", + "isbn_13", + "lccn", + "oclc", + "openlibrary" }) @Getter @Setter @@ -29,21 +28,28 @@ public class Identifiers { @JsonProperty("amazon") public List amazon = null; + @JsonProperty("google") public List google = null; + @JsonProperty("librarything") public List librarything = null; + @JsonProperty("goodreads") public List goodreads = null; + @JsonProperty("isbn_10") public List isbn10 = null; + @JsonProperty("isbn_13") public List isbn13 = null; + @JsonProperty("lccn") public List lccn = null; + @JsonProperty("oclc") public List oclc = null; + @JsonProperty("openlibrary") public List openlibrary = null; - } diff --git a/src/main/java/com/entity/openLibrary/Isbn.java b/src/main/java/com/entity/openLibrary/Isbn.java index c227003c..6f73ea67 100755 --- a/src/main/java/com/entity/openLibrary/Isbn.java +++ b/src/main/java/com/entity/openLibrary/Isbn.java @@ -2,9 +2,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - import java.util.List; +import lombok.*; @Getter @Setter @@ -17,41 +16,58 @@ public class Isbn { @JsonProperty("url") public String url; + @JsonProperty("key") public String key; + @JsonProperty("title") public String title; + @JsonProperty("authors") public List authors = null; + @JsonProperty("number_of_pages") public Integer numberOfPages; + @JsonProperty("pagination") public String pagination; + @JsonProperty("weight") public String weight; + @JsonProperty("by_statement") public String byStatement; + @JsonProperty("identifiers") public Identifiers identifiers; + @JsonProperty("classifications") public Classifications classifications; + @JsonProperty("publishers") public List publishers = null; + @JsonProperty("publish_places") public List publishPlaces = null; + @JsonProperty("publish_date") public String publishDate; + @JsonProperty("subjects") public List subjects = null; + @JsonProperty("notes") public String notes; + @JsonProperty("table_of_contents") public List tableOfContents = null; + @JsonProperty("links") public List links = null; + @JsonProperty("ebooks") public List ebooks = null; + @JsonProperty("cover") public Cover cover; - } diff --git a/src/main/java/com/entity/openLibrary/Link.java b/src/main/java/com/entity/openLibrary/Link.java index 3dfad7e8..472178d9 100755 --- a/src/main/java/com/entity/openLibrary/Link.java +++ b/src/main/java/com/entity/openLibrary/Link.java @@ -6,10 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "title", - "url" -}) +@JsonPropertyOrder({"title", "url"}) @Getter @Setter @AllArgsConstructor @@ -20,7 +17,7 @@ public class Link { @JsonProperty("title") public String title; + @JsonProperty("url") public String url; - } diff --git a/src/main/java/com/entity/openLibrary/OpenLibDto.java b/src/main/java/com/entity/openLibrary/OpenLibDto.java index 8e4224ec..7204dcc3 100644 --- a/src/main/java/com/entity/openLibrary/OpenLibDto.java +++ b/src/main/java/com/entity/openLibrary/OpenLibDto.java @@ -3,10 +3,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - import java.util.ArrayList; import java.util.List; +import lombok.*; @Getter @Setter @@ -19,10 +18,13 @@ public class OpenLibDto { @JsonProperty("title") public String title; + @JsonProperty("number_of_pages") public Integer numberOfPages; + @JsonProperty("weight") public String weight; + @JsonProperty("table_of_contents") public List tableOfContents = new ArrayList<>(); } diff --git a/src/main/java/com/entity/openLibrary/OpenLibrary.java b/src/main/java/com/entity/openLibrary/OpenLibrary.java index c7048873..4d04e287 100755 --- a/src/main/java/com/entity/openLibrary/OpenLibrary.java +++ b/src/main/java/com/entity/openLibrary/OpenLibrary.java @@ -6,9 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "ISBN" -}) +@JsonPropertyOrder({"ISBN"}) @Getter @Setter @AllArgsConstructor @@ -19,5 +17,4 @@ public class OpenLibrary { @JsonProperty("ISBN") public Isbn isbn; - } diff --git a/src/main/java/com/entity/openLibrary/PublishPlace.java b/src/main/java/com/entity/openLibrary/PublishPlace.java index c1fa2559..43054213 100755 --- a/src/main/java/com/entity/openLibrary/PublishPlace.java +++ b/src/main/java/com/entity/openLibrary/PublishPlace.java @@ -6,9 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "name" -}) +@JsonPropertyOrder({"name"}) @Getter @Setter @AllArgsConstructor @@ -19,5 +17,4 @@ public class PublishPlace { @JsonProperty("name") public String name; - } diff --git a/src/main/java/com/entity/openLibrary/Publisher.java b/src/main/java/com/entity/openLibrary/Publisher.java index 13f53246..667e3dda 100755 --- a/src/main/java/com/entity/openLibrary/Publisher.java +++ b/src/main/java/com/entity/openLibrary/Publisher.java @@ -6,9 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "name" -}) +@JsonPropertyOrder({"name"}) @Getter @Setter @AllArgsConstructor @@ -19,5 +17,4 @@ public class Publisher { @JsonProperty("name") public String name; - } diff --git a/src/main/java/com/entity/openLibrary/Subject.java b/src/main/java/com/entity/openLibrary/Subject.java index 827d58ca..1013a01a 100755 --- a/src/main/java/com/entity/openLibrary/Subject.java +++ b/src/main/java/com/entity/openLibrary/Subject.java @@ -6,10 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "name", - "url" -}) +@JsonPropertyOrder({"name", "url"}) @Getter @Setter @AllArgsConstructor @@ -20,7 +17,7 @@ public class Subject { @JsonProperty("name") public String name; + @JsonProperty("url") public String url; - } diff --git a/src/main/java/com/entity/openLibrary/TableOfContent.java b/src/main/java/com/entity/openLibrary/TableOfContent.java index 041bb830..25e8ee60 100755 --- a/src/main/java/com/entity/openLibrary/TableOfContent.java +++ b/src/main/java/com/entity/openLibrary/TableOfContent.java @@ -6,12 +6,7 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "level", - "label", - "title", - "pagenum" -}) +@JsonPropertyOrder({"level", "label", "title", "pagenum"}) @Getter @Setter @AllArgsConstructor @@ -22,11 +17,13 @@ public class TableOfContent { @JsonProperty("level") public Integer level; + @JsonProperty("label") public String label; + @JsonProperty("title") public String title; + @JsonProperty("pagenum") public String pagenum; - } diff --git a/src/main/java/com/entity/reports/EventComments.java b/src/main/java/com/entity/reports/EventComments.java index 4e79fe7b..77d46989 100644 --- a/src/main/java/com/entity/reports/EventComments.java +++ b/src/main/java/com/entity/reports/EventComments.java @@ -1,13 +1,12 @@ package com.entity.reports; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @Data @NoArgsConstructor @AllArgsConstructor diff --git a/src/main/java/com/entity/reports/IntraStatsLine.java b/src/main/java/com/entity/reports/IntraStatsLine.java index dad6534d..51d26b23 100644 --- a/src/main/java/com/entity/reports/IntraStatsLine.java +++ b/src/main/java/com/entity/reports/IntraStatsLine.java @@ -1,9 +1,8 @@ package com.entity.reports; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.*; - import java.util.List; +import lombok.*; @Data @NoArgsConstructor @@ -14,4 +13,4 @@ public class IntraStatsLine implements Payloadable { List eventComments; private String varianceCount; -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/reports/Payloadable.java b/src/main/java/com/entity/reports/Payloadable.java index 5baefce4..1f27b1f5 100644 --- a/src/main/java/com/entity/reports/Payloadable.java +++ b/src/main/java/com/entity/reports/Payloadable.java @@ -1,4 +1,3 @@ package com.entity.reports; -public interface Payloadable { -} +public interface Payloadable {} diff --git a/src/main/java/com/entity/reports/SampleIntraStatLine.java b/src/main/java/com/entity/reports/SampleIntraStatLine.java index ff66b2fe..ff9d9c09 100644 --- a/src/main/java/com/entity/reports/SampleIntraStatLine.java +++ b/src/main/java/com/entity/reports/SampleIntraStatLine.java @@ -5,44 +5,54 @@ public class SampleIntraStatLine { public static IntraStatsLine getIntraStatsLine() { - EventComments eventComments = EventComments.builder() - .facilityId("11019") - .orderId("5b571d0a-1124-45b2-9985-373799d97a96") - .sectionName(null) - .someStats(Collections.singletonList(SomeStats.builder() - .eventType("Initial Entry") - .eventid("1") - .eventsComments("09:17 EDT Initial Entry Joe, Dow RM") - .timeDtDisplay("09:17") - .build())) - .someClass(SomeClass.builder() - .index(101) - .noOfYears(5) - .someStr("one O one") - .build()) - .build(); + EventComments eventComments = + EventComments.builder() + .facilityId("11019") + .orderId("5b571d0a-1124-45b2-9985-373799d97a96") + .sectionName(null) + .someStats( + Collections.singletonList( + SomeStats.builder() + .eventType("Initial Entry") + .eventid("1") + .eventsComments( + "09:17 EDT Initial Entry Joe, Dow RM") + .timeDtDisplay("09:17") + .build())) + .someClass( + SomeClass.builder() + .index(101) + .noOfYears(5) + .someStr("one O one") + .build()) + .build(); - EventComments eventComments2 = EventComments.builder() - .facilityId("11019") - .orderId("5b571d0a-1124-45b2-9985-373799d97a96") - .sectionName(null) - .someStats(Collections.singletonList(SomeStats.builder() - .eventType("Updated by") - .eventid("2") - .eventsComments("09:19 EDT Updated by Joe, Dow RM") - .timeDtDisplay("09:19") - .build())) - .someClass(SomeClass.builder() - .index(201) - .noOfYears(9) - .someStr("Two O one") - .build()) - .build(); + EventComments eventComments2 = + EventComments.builder() + .facilityId("11019") + .orderId("5b571d0a-1124-45b2-9985-373799d97a96") + .sectionName(null) + .someStats( + Collections.singletonList( + SomeStats.builder() + .eventType("Updated by") + .eventid("2") + .eventsComments("09:19 EDT Updated by Joe, Dow RM") + .timeDtDisplay("09:19") + .build())) + .someClass( + SomeClass.builder() + .index(201) + .noOfYears(9) + .someStr("Two O one") + .build()) + .build(); - IntraStatsLine intraStatsLine = IntraStatsLine.builder() - .eventComments(Arrays.asList(eventComments, eventComments2)) - .varianceCount("9") - .build(); + IntraStatsLine intraStatsLine = + IntraStatsLine.builder() + .eventComments(Arrays.asList(eventComments, eventComments2)) + .varianceCount("9") + .build(); return (intraStatsLine); } -} \ No newline at end of file +} diff --git a/src/main/java/com/entity/reports/SomeStats.java b/src/main/java/com/entity/reports/SomeStats.java index 099544e4..879f8c61 100644 --- a/src/main/java/com/entity/reports/SomeStats.java +++ b/src/main/java/com/entity/reports/SomeStats.java @@ -16,4 +16,4 @@ public class SomeStats { private String eventType; private String timeDtDisplay; private String eventsComments; -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/CsvReadUtility.java b/src/main/java/com/utilities/CsvReadUtility.java index fd6578f7..24d8e16e 100644 --- a/src/main/java/com/utilities/CsvReadUtility.java +++ b/src/main/java/com/utilities/CsvReadUtility.java @@ -1,9 +1,6 @@ package com.utilities; import com.entity.Cancer; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -12,6 +9,8 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; public class CsvReadUtility { @@ -20,28 +19,31 @@ public static List getCancerData() { Path path = Paths.get(fileName); List list = null; - //read file into stream, try-with-resources + // read file into stream, try-with-resources try (Stream stream = Files.lines(Paths.get(fileName))) { - list = stream - .map(str -> str.split(",", -1)) - .skip(1) - - .map(strArr -> { - String[] temp = strArr; - Cancer c; - c = new Cancer( - org.apache.commons.lang3.StringUtils.defaultString(temp[0], null), - org.apache.commons.lang3.StringUtils.defaultString(temp[1], null), - NumberUtils.toInt(temp[2], -1), - org.apache.commons.lang3.StringUtils.defaultString(temp[3], null), - StringUtils.defaultString(temp[4], null), - NumberUtils.toFloat(temp[5], -1), - NumberUtils.toInt(temp[6], -1), - NumberUtils.toFloat(temp[7], -1) - ); - return c; - }) - .collect(Collectors.toCollection(ArrayList::new)); + list = + stream.map(str -> str.split(",", -1)) + .skip(1) + .map( + strArr -> { + String[] temp = strArr; + Cancer c; + c = + new Cancer( + org.apache.commons.lang3.StringUtils + .defaultString(temp[0], null), + org.apache.commons.lang3.StringUtils + .defaultString(temp[1], null), + NumberUtils.toInt(temp[2], -1), + org.apache.commons.lang3.StringUtils + .defaultString(temp[3], null), + StringUtils.defaultString(temp[4], null), + NumberUtils.toFloat(temp[5], -1), + NumberUtils.toInt(temp[6], -1), + NumberUtils.toFloat(temp[7], -1)); + return c; + }) + .collect(Collectors.toCollection(ArrayList::new)); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/com/utilities/FibStream.java b/src/main/java/com/utilities/FibStream.java index d65d561b..026794aa 100755 --- a/src/main/java/com/utilities/FibStream.java +++ b/src/main/java/com/utilities/FibStream.java @@ -4,46 +4,32 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -/** - * A class with static methods to build streams of Fibonacci numbers. - */ - +/** A class with static methods to build streams of Fibonacci numbers. */ public class FibStream { - private FibStream() { - } // Uninstantiatable class + private FibStream() {} // Uninstantiatable class /** - * Makes an "infinite" (unbounded) stream of Fibonacci numbers - * (1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth). - * This method is for when you want to control the size-limiting steps later. - * The more common usage is the next method, where you limit the - * size in the call to the original method. + * Makes an "infinite" (unbounded) stream of Fibonacci numbers (1, 1, 2, 3, 5, 8, 13, 21, 34, + * and so forth). This method is for when you want to control the size-limiting steps later. The + * more common usage is the next method, where you limit the size in the call to the original + * method. */ public static Stream makeFibStream() { return (Stream.generate(new FibonacciMaker())); } - /** - * Makes a Stream of the specified number of Fibonacci numbers. - */ - + /** Makes a Stream of the specified number of Fibonacci numbers. */ public static Stream makeFibStream(int numFibs) { return (makeFibStream().limit(numFibs)); } - /** - * Makes a List of the specified number of Fibonacci numbers. - */ - + /** Makes a List of the specified number of Fibonacci numbers. */ public static List makeFibList(int numFibs) { return (makeFibStream(numFibs).collect(Collectors.toList())); } - /** - * Makes an array of the specified number of consecutive n-digit primes - */ - + /** Makes an array of the specified number of consecutive n-digit primes */ public static Long[] makeFibArray(int numFibs) { return (makeFibStream(numFibs).toArray(Long[]::new)); } diff --git a/src/main/java/com/utilities/InternetUtilities.java b/src/main/java/com/utilities/InternetUtilities.java index a8c3f6f1..0eac6040 100644 --- a/src/main/java/com/utilities/InternetUtilities.java +++ b/src/main/java/com/utilities/InternetUtilities.java @@ -4,26 +4,25 @@ import com.entity.WordResponse; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - import java.io.IOException; import java.net.URL; import java.util.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; public class InternetUtilities { private static final String URL = "https://www.mit.edu/~ecprice/wordlist.100000"; - private static final String DATA_MUSE_WORDS_URL = "https://api.datamuse.com/words?ml={word}&max={max}"; + private static final String DATA_MUSE_WORDS_URL = + "https://api.datamuse.com/words?ml={word}&max={max}"; private static final String RANDOM_BEERS_URL = "https://random-data-api.com/api/v2/beers?size="; ObjectMapper mapper = new ObjectMapper(); - public static List bringWordListFromNet() { Scanner s = getScannerFromURL(); - //Construct a list of Long Words + // Construct a list of Long Words List list = new ArrayList<>(); while (s.hasNext()) { String word = s.nextLine(); @@ -42,16 +41,18 @@ public static List getWords(String[] args) { uriVariables.put("max", max); RestTemplate restTemplate = new RestTemplate(); - //Response response = restTemplate.getForObject("https://api.datamuse.com/words?ml={word}&max={max}", Response.class); - ResponseEntity response = restTemplate.getForEntity(DATA_MUSE_WORDS_URL, WordResponse[].class, uriVariables); + // Response response = + // restTemplate.getForObject("https://api.datamuse.com/words?ml={word}&max={max}", + // Response.class); + ResponseEntity response = + restTemplate.getForEntity(DATA_MUSE_WORDS_URL, WordResponse[].class, uriVariables); - //RestResponse responseNEW = response.getBody(); + // RestResponse responseNEW = response.getBody(); System.out.println("==== RESTful API Response using Spring RESTTemplate START ======="); - List wordList = new ArrayList<>(); for (WordResponse x : response.getBody()) { - //System.out.println(x.getWord()); + // System.out.println(x.getWord()); wordList.add(x.getWord()); } System.out.println("======= RESTful API Response using Spring RESTTemplate END ======="); @@ -64,8 +65,9 @@ public static List getBeers(int size) { List beerList = new ArrayList<>(); try { - beerList = mapper.readValue(new URL(RANDOM_BEERS_URL + size), new TypeReference>() { - }); + beerList = + mapper.readValue( + new URL(RANDOM_BEERS_URL + size), new TypeReference>() {}); } catch (IOException e) { e.printStackTrace(); } @@ -73,10 +75,10 @@ public static List getBeers(int size) { } private static Scanner getScannerFromURL() { - //Read Files from the net + // Read Files from the net Scanner s = null; try { - //The English word List + // The English word List URL url = new URL(URL); s = new Scanner(url.openStream()); } catch (IOException ex) { diff --git a/src/main/java/com/utilities/JsonUtils.java b/src/main/java/com/utilities/JsonUtils.java index f0f0a166..595d43d8 100644 --- a/src/main/java/com/utilities/JsonUtils.java +++ b/src/main/java/com/utilities/JsonUtils.java @@ -10,4 +10,4 @@ public static String getJsonStringFromFile(String path) throws IOException { // Read the content of the file as a string return new String(Files.readAllBytes(Paths.get(path))); } -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/MathUtils.java b/src/main/java/com/utilities/MathUtils.java index f8a6f382..3138b5e5 100644 --- a/src/main/java/com/utilities/MathUtils.java +++ b/src/main/java/com/utilities/MathUtils.java @@ -2,10 +2,7 @@ import java.math.BigInteger; -/** - * Created by nichaurasia on Friday, May/29/2020 at 4:45 PM - */ - +/** Created by nichaurasia on Friday, May/29/2020 at 4:45 PM */ public class MathUtils { public static BigInteger factorial(int i) { @@ -20,13 +17,11 @@ public static BigInteger factorial(int i) { BigInteger ret = BigInteger.valueOf(1); long begin = System.currentTimeMillis(); for (int x = i; i > 1; i--) { - ret = BigInteger - .valueOf(x) - .multiply(ret); + ret = BigInteger.valueOf(x).multiply(ret); } long end = System.currentTimeMillis(); System.out.println("total time take : " + (end - begin) + " secs"); return ret; } -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/MultiThreadUtility.java b/src/main/java/com/utilities/MultiThreadUtility.java index 18700267..abac8e08 100644 --- a/src/main/java/com/utilities/MultiThreadUtility.java +++ b/src/main/java/com/utilities/MultiThreadUtility.java @@ -1,11 +1,10 @@ package com.utilities; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import static java.lang.Thread.sleep; import java.time.Duration; - -import static java.lang.Thread.sleep; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; public class MultiThreadUtility { @@ -32,7 +31,7 @@ public static void logShortMessage(String message) { } public static void logMessage(String message) { - System.out.printf("%s %s\n", Thread.currentThread(), message ); + System.out.printf("%s %s\n", Thread.currentThread(), message); } public static void foreverThread() { diff --git a/src/main/java/com/utilities/OldDateUtilities.java b/src/main/java/com/utilities/OldDateUtilities.java index 08d0d4e8..a9a804b7 100644 --- a/src/main/java/com/utilities/OldDateUtilities.java +++ b/src/main/java/com/utilities/OldDateUtilities.java @@ -1,14 +1,13 @@ package com.utilities; -import org.joda.time.DateTime; -import org.joda.time.DateTimeConstants; - import java.io.Serializable; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; +import org.joda.time.DateTime; +import org.joda.time.DateTimeConstants; public class OldDateUtilities implements Serializable { private static final long serialVersionUID = -1L; @@ -26,11 +25,13 @@ public static long numberOfMonthsBetween(Date d1, Date d2) { earlier.setTime(nullifyTime(d2)); later.setTime(nullifyTime(d1)); } - diffrence = (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR)) - * 12 - + (later.get(Calendar.MONTH) - earlier.get(Calendar.MONTH)) - + (later.get(Calendar.DAY_OF_MONTH) >= earlier - .get(Calendar.DAY_OF_MONTH) ? 0 : -1); + diffrence = + (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR)) * 12 + + (later.get(Calendar.MONTH) - earlier.get(Calendar.MONTH)) + + (later.get(Calendar.DAY_OF_MONTH) + >= earlier.get(Calendar.DAY_OF_MONTH) + ? 0 + : -1); } return diffrence; } @@ -106,8 +107,9 @@ public static Date getLastDayOfMonth(Date inDate) { } else { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(inDate); - cal.set(GregorianCalendar.DAY_OF_MONTH, cal - .getActualMaximum(GregorianCalendar.DAY_OF_MONTH)); + cal.set( + GregorianCalendar.DAY_OF_MONTH, + cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)); return nullifyTime(cal.getTime()); } } @@ -118,8 +120,9 @@ public static Date getFirstDayOfMonth(Date inDate) { } else { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(inDate); - cal.set(GregorianCalendar.DAY_OF_MONTH, cal - .getActualMinimum(GregorianCalendar.DAY_OF_MONTH)); + cal.set( + GregorianCalendar.DAY_OF_MONTH, + cal.getActualMinimum(GregorianCalendar.DAY_OF_MONTH)); return nullifyTime(cal.getTime()); } } @@ -227,9 +230,7 @@ public static Timestamp addDays(Timestamp tsTimestamp1, int iNoOfDays) { return (new Timestamp(calendar.getTimeInMillis())); } - public static Timestamp addMonths( - Timestamp tsTimestamp1, - int iNoOfMonths) { + public static Timestamp addMonths(Timestamp tsTimestamp1, int iNoOfMonths) { Calendar calendar = new GregorianCalendar(); calendar.setTime(tsTimestamp1); calendar.add(Calendar.MONTH, iNoOfMonths); @@ -398,8 +399,7 @@ public static boolean isLeapYear(int year) { public static Timestamp getLocalesDate() { Locale lCurrentLocale = new Locale("en", "US"); String dateOut = null; - DateFormat dateFormatter = - DateFormat.getDateInstance(DateFormat.DEFAULT, lCurrentLocale); + DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, lCurrentLocale); dateOut = dateFormatter.format(Calendar.getInstance().getTime()); Timestamp tsLocalesDate = null; try { @@ -414,7 +414,8 @@ public static Timestamp getLocalesTimestamp() { Locale lCurrentLocale = new Locale("en", "US"); String dateOut = null; DateFormat dateFormatter = - DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, lCurrentLocale); + DateFormat.getDateTimeInstance( + DateFormat.DEFAULT, DateFormat.DEFAULT, lCurrentLocale); dateOut = dateFormatter.format(Calendar.getInstance().getTime()); Timestamp tsLocalesDate = null; try { @@ -426,18 +427,14 @@ public static Timestamp getLocalesTimestamp() { } public static java.math.BigDecimal getAgeInYearsNMonths( - Timestamp tsTimestamp1, - Timestamp tsTimestamp2) { + Timestamp tsTimestamp1, Timestamp tsTimestamp2) { int iAge = getMonthsBetween(tsTimestamp1, tsTimestamp2); Integer IAge = Integer.valueOf(iAge); - java.math.BigDecimal bdYear = - java.math.BigDecimal.valueOf(IAge.doubleValue() / 12.0); + java.math.BigDecimal bdYear = java.math.BigDecimal.valueOf(IAge.doubleValue() / 12.0); return bdYear; } - public static int getMonthsBetween( - Timestamp tsTimestamp1, - Timestamp tsTimestamp2) { + public static int getMonthsBetween(Timestamp tsTimestamp1, Timestamp tsTimestamp2) { Calendar calendarInstance1 = Calendar.getInstance(); Calendar calendarInstance2 = Calendar.getInstance(); @@ -447,11 +444,8 @@ public static int getMonthsBetween( Timestamp tsLateDate = (Timestamp) hmSetDates.get("dLateDate"); calendarInstance1.setTime(tsEarlyDate); calendarInstance2.setTime(tsLateDate); - return ( - (calendarInstance2.get(Calendar.YEAR) - calendarInstance1.get(Calendar.YEAR)) - * 12 - + (calendarInstance2.get(Calendar.MONTH) - - calendarInstance1.get(Calendar.MONTH))); + return ((calendarInstance2.get(Calendar.YEAR) - calendarInstance1.get(Calendar.YEAR)) * 12 + + (calendarInstance2.get(Calendar.MONTH) - calendarInstance1.get(Calendar.MONTH))); } public static Timestamp getTimeStampFromString(String YYYYMMDD) { @@ -468,9 +462,7 @@ public static Timestamp getTimeStampFromString(String YYYYMMDD) { return tsDate; } - public static long getDaysBetween( - Timestamp tsTimestamp1, - Timestamp tsTimestamp2) { + public static long getDaysBetween(Timestamp tsTimestamp1, Timestamp tsTimestamp2) { Calendar calendarInstance1 = Calendar.getInstance(); Calendar calendarInstance2 = Calendar.getInstance(); @@ -553,11 +545,10 @@ public static Timestamp getLastDayOfDate(Timestamp tsTimestamp1) { strDay = 29; } else if (nMonthIndex == 1) { strDay = 28; - } else if ( - (nMonthIndex == 3) - || (nMonthIndex == 5) - || (nMonthIndex == 8) - || (nMonthIndex == 10)) { + } else if ((nMonthIndex == 3) + || (nMonthIndex == 5) + || (nMonthIndex == 8) + || (nMonthIndex == 10)) { strDay = 30; } else { strDay = 31; @@ -566,8 +557,7 @@ public static Timestamp getLastDayOfDate(Timestamp tsTimestamp1) { return (new Timestamp(gregorianCalendar.getTimeInMillis())); } - public static Timestamp getLastDayOfPreviousMonth( - Timestamp tsTimestamp1) { + public static Timestamp getLastDayOfPreviousMonth(Timestamp tsTimestamp1) { GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(tsTimestamp1); @@ -585,11 +575,10 @@ public static Timestamp getLastDayOfPreviousMonth( iLastDay = 29; } else if (iMonthIndex == 1) { iLastDay = 28; - } else if ( - (iMonthIndex == 3) - || (iMonthIndex == 5) - || (iMonthIndex == 8) - || (iMonthIndex == 10)) { + } else if ((iMonthIndex == 3) + || (iMonthIndex == 5) + || (iMonthIndex == 8) + || (iMonthIndex == 10)) { iLastDay = 30; } else { iLastDay = 31; @@ -601,8 +590,7 @@ public static Timestamp getLastDayOfPreviousMonth( return new Timestamp(gregorianCalendar.getTimeInMillis()); } - public static Timestamp getLastDayOfCurrentMonth( - Timestamp tsTimestamp1) { + public static Timestamp getLastDayOfCurrentMonth(Timestamp tsTimestamp1) { GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(tsTimestamp1); @@ -620,11 +608,10 @@ public static Timestamp getLastDayOfCurrentMonth( iLastDay = 29; } else if (iMonthIndex == 1) { iLastDay = 28; - } else if ( - (iMonthIndex == 3) - || (iMonthIndex == 5) - || (iMonthIndex == 8) - || (iMonthIndex == 10)) { + } else if ((iMonthIndex == 3) + || (iMonthIndex == 5) + || (iMonthIndex == 8) + || (iMonthIndex == 10)) { iLastDay = 30; } else { iLastDay = 31; @@ -636,9 +623,7 @@ public static Timestamp getLastDayOfCurrentMonth( return new Timestamp(gregorianCalendar.getTimeInMillis()); } - public static ArrayList getMonthsArrayBetween( - Timestamp tsTimestamp1, - Timestamp tsTimestamp2) { + public static ArrayList getMonthsArrayBetween(Timestamp tsTimestamp1, Timestamp tsTimestamp2) { Calendar calendarInstance1 = Calendar.getInstance(); Calendar calendarInstance2 = Calendar.getInstance(); @@ -701,9 +686,7 @@ public static ArrayList getMonthsArrayBetween( return arrayList1; } - public static int getMonthsIncludedBetween( - Timestamp tsTimestamp1, - Timestamp tsTimestamp2) { + public static int getMonthsIncludedBetween(Timestamp tsTimestamp1, Timestamp tsTimestamp2) { Calendar calendarInstance1 = Calendar.getInstance(); Calendar calendarInstance2 = Calendar.getInstance(); @@ -712,11 +695,8 @@ public static int getMonthsIncludedBetween( Timestamp tsLateDate = (Timestamp) hmSetDates.get("dLateDate"); calendarInstance1.setTime(tsEarlyDate); calendarInstance2.setTime(tsLateDate); - return ( - (calendarInstance2.get(Calendar.YEAR) - calendarInstance1.get(Calendar.YEAR)) - * 12 - + ((calendarInstance2.get(Calendar.MONTH) - - calendarInstance1.get(Calendar.MONTH)) + return ((calendarInstance2.get(Calendar.YEAR) - calendarInstance1.get(Calendar.YEAR)) * 12 + + ((calendarInstance2.get(Calendar.MONTH) - calendarInstance1.get(Calendar.MONTH)) + 1)); } @@ -735,11 +715,12 @@ public static String getPreviousDate(Timestamp tsFromThisDate) { gregorianCalendar.setTime(tsFromThisDate); int iDay = gregorianCalendar.get(Calendar.DATE); gregorianCalendar.set((Calendar.DATE), iDay - 1); - String sbPreviousDate = (gregorianCalendar.get(Calendar.MONTH) + 1) + - "-" + - gregorianCalendar.get(Calendar.DATE) + - "-" + - gregorianCalendar.get(Calendar.YEAR); + String sbPreviousDate = + (gregorianCalendar.get(Calendar.MONTH) + 1) + + "-" + + gregorianCalendar.get(Calendar.DATE) + + "-" + + gregorianCalendar.get(Calendar.YEAR); return sbPreviousDate; } @@ -749,11 +730,12 @@ public static String getPreviousTimeStamp(Timestamp tsFromThisDate) { gregorianCalendar.setTime(tsFromThisDate); int iDay = gregorianCalendar.get(Calendar.DATE); gregorianCalendar.set((Calendar.DATE), iDay - 1); - String sbPreviousDate = (gregorianCalendar.get(Calendar.MONTH) + 1) + - "/" + - gregorianCalendar.get(Calendar.DATE) + - "/" + - gregorianCalendar.get(Calendar.YEAR); + String sbPreviousDate = + (gregorianCalendar.get(Calendar.MONTH) + 1) + + "/" + + gregorianCalendar.get(Calendar.DATE) + + "/" + + gregorianCalendar.get(Calendar.YEAR); return sbPreviousDate; } @@ -763,11 +745,12 @@ public static String getPreviousMonth(Timestamp tsGivenTimestamp) { gregorianCalendar.setTime(tsGivenTimestamp); int iMonth = gregorianCalendar.get(Calendar.MONTH); gregorianCalendar.set((Calendar.MONTH), iMonth - 1); - String sbPreviousMonth = (gregorianCalendar.get(Calendar.MONTH) + 1) + - "/" + - gregorianCalendar.get(Calendar.DATE) + - "/" + - gregorianCalendar.get(Calendar.YEAR); + String sbPreviousMonth = + (gregorianCalendar.get(Calendar.MONTH) + 1) + + "/" + + gregorianCalendar.get(Calendar.DATE) + + "/" + + gregorianCalendar.get(Calendar.YEAR); return sbPreviousMonth; } @@ -780,8 +763,7 @@ public static Timestamp getTimestamp(Timestamp tsDate1) { } public static int getYearsBetween( - java.sql.Timestamp tsYearsBetween1, - java.sql.Timestamp tsYearsBetween2) { + java.sql.Timestamp tsYearsBetween1, java.sql.Timestamp tsYearsBetween2) { Calendar calendarInstance1 = Calendar.getInstance(); Calendar calendarInstance2 = Calendar.getInstance(); @@ -795,8 +777,7 @@ public static int getYearsBetween( iYearsBetweenDates = calendarInstance2.get(Calendar.YEAR) - calendarInstance1.get(Calendar.YEAR); calendarInstance1.add(Calendar.YEAR, iYearsBetweenDates); - if ((calendarInstance1.getTime()).getTime() - > (calendarInstance2.getTime()).getTime()) { + if ((calendarInstance1.getTime()).getTime() > (calendarInstance2.getTime()).getTime()) { return (iYearsBetweenDates - 1); } else { return (iYearsBetweenDates); @@ -830,9 +811,7 @@ public static Timestamp subDays(Timestamp tsTimestamp1, int iNoOfDays) { return (new Timestamp(calendar.getTimeInMillis())); } - public static Timestamp subMonths( - Timestamp tsTimestamp1, - int iNoOfMonths) { + public static Timestamp subMonths(Timestamp tsTimestamp1, int iNoOfMonths) { Calendar calendar = new GregorianCalendar(); @@ -878,11 +857,7 @@ public static java.sql.Timestamp getTimestamp(String sMonth, String sYear) { } else if (sMonth.equals("December")) { imonth = 12; } - String sbDate = imonth + - "/" + - iday + - "/" + - sYear; + String sbDate = imonth + "/" + iday + "/" + sYear; return getTimestamp(sbDate); } @@ -933,8 +908,7 @@ public static boolean dateGTDateInTimestamp(Timestamp ts, Timestamp ts1) { } private static HashMap setConvertedDates( - java.sql.Timestamp tsTimestamp1, - java.sql.Timestamp tsTimestamp2) { + java.sql.Timestamp tsTimestamp1, java.sql.Timestamp tsTimestamp2) { Timestamp dConvertedDate1 = null; Timestamp dConvertedDate2 = null; @@ -1121,7 +1095,8 @@ public static String getStringYYYYMMDD(Timestamp tsTimestamp1) { return sYYYYMM; } - public static boolean isRangeOverlapping(Timestamp[] datesToCompare, ArrayList rangeDates) { + public static boolean isRangeOverlapping( + Timestamp[] datesToCompare, ArrayList rangeDates) { Timestamp begDate = datesToCompare[0]; Timestamp endDate = datesToCompare[1]; if (endDate == null) { @@ -1140,8 +1115,10 @@ public static boolean isRangeOverlapping(Timestamp[] datesToCompare, ArrayList getWeekendsInAYear(int year) throws ParseException { public static List getLastNFridays(int n) throws ParseException { // create a Calendar for the 1st of the required month List lastNFridayDates = new ArrayList<>(); - //Calendar cal = new GregorianCalendar(year, month, 1); + // Calendar cal = new GregorianCalendar(year, month, 1); Calendar calendar = Calendar.getInstance(); int daysBackToFriday = 0; - //System.out.println(authTimestamp); + // System.out.println(authTimestamp); for (int i = 0; i < n; i++) { daysBackToFriday = calendar.get(Calendar.DAY_OF_WEEK) + 1; calendar.add(Calendar.DATE, daysBackToFriday * -1); - //System.out.println(sdf.format(calendar.getTime())); + // System.out.println(sdf.format(calendar.getTime())); lastNFridayDates.add(OldDateUtilities.nullifyTime(calendar.getTime())); } return lastNFridayDates; } public static List findLastNFridaysJodaTime(int N) { - if (N < 1) - return null; + if (N < 1) return null; List ret = new ArrayList(); DateTime today = DateTime.now(); DateTime sameDayLastWeek = today.minusWeeks(1); - //Friday of last week + // Friday of last week DateTime fridayOfWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.FRIDAY); - //DateTime saturdayOfLastWeek = fridayOfWeek.plusDays(1); + // DateTime saturdayOfLastWeek = fridayOfWeek.plusDays(1); ret.add(fridayOfWeek); - //ret.add(saturdayOfLastWeek); + // ret.add(saturdayOfLastWeek); for (int i = 0; i < N - 1; i++) { fridayOfWeek = fridayOfWeek.minusWeeks(1); ret.add(fridayOfWeek); diff --git a/src/main/java/com/utilities/PrimeStream.java b/src/main/java/com/utilities/PrimeStream.java index a87ea6f3..2622e4cf 100755 --- a/src/main/java/com/utilities/PrimeStream.java +++ b/src/main/java/com/utilities/PrimeStream.java @@ -6,43 +6,33 @@ import java.util.stream.Stream; public class PrimeStream { - private PrimeStream() { - } // Uninstantiatable class + private PrimeStream() {} // Uninstantiatable class /** - * Makes an "infinite" (unbounded) stream of consecutive prime numbers. - * This method is for when you want to control the size-limiting steps later. - * The more common usage is the next method, where you limit the - * size in the call to the original method. + * Makes an "infinite" (unbounded) stream of consecutive prime numbers. This method is for when + * you want to control the size-limiting steps later. The more common usage is the next method, + * where you limit the size in the call to the original method. */ public static Stream makePrimeStream(int numDigits) { return (Stream.iterate(Primes.findPrime(numDigits), Primes::nextPrime)); } - /** - * Makes a Stream of the specified number of consecutive n-digit primes. - */ - + /** Makes a Stream of the specified number of consecutive n-digit primes. */ public static Stream makePrimeStream(int numDigits, int numPrimes) { return (makePrimeStream(numDigits).limit(numPrimes)); } - /** - * Makes a List of the specified number of consecutive n-digit primes. - */ - + /** Makes a List of the specified number of consecutive n-digit primes. */ public static List makePrimeList(int numDigits, int numPrimes) { return (makePrimeStream(numDigits, numPrimes).collect(Collectors.toList())); } - /** - * Makes an array of the specified number of consecutive n-digit primes. - */ + /** Makes an array of the specified number of consecutive n-digit primes. */ // toArray returns Object[], not T[], so the typecast is needed - //public static BigInteger[] makePrimeArray(int numDigits, int numPrimes) { + // public static BigInteger[] makePrimeArray(int numDigits, int numPrimes) { // return((BigInteger[])makePrimeStream(numDigits, numPrimes).toArray()); - //} + // } public static BigInteger[] makePrimeArray(int numDigits, int numPrimes) { return (makePrimeStream(numDigits, numPrimes).toArray(BigInteger[]::new)); } diff --git a/src/main/java/com/utilities/Primes.java b/src/main/java/com/utilities/Primes.java index c10be979..b69968aa 100755 --- a/src/main/java/com/utilities/Primes.java +++ b/src/main/java/com/utilities/Primes.java @@ -3,10 +3,9 @@ import java.math.BigInteger; /** - * A few utilities to generate a large random BigInteger, - * and find the next prime number above a given BigInteger. + * A few utilities to generate a large random BigInteger, and find the next prime number above a + * given BigInteger. */ - public class Primes { private static final BigInteger ZERO = BigInteger.ZERO; private static final BigInteger ONE = BigInteger.ONE; @@ -17,17 +16,12 @@ public class Primes { // equivalent, and thus is NOT fooled by Carmichael numbers. // See Cormen et al.'s Introduction to Algorithms for details. private static final int ERR_VAL = 100; - private static final String[] DIGITS = - "0,1,2,3,4,5,6,7,8,9".split(","); - private static final String[] NON_ZERO_DIGITS = - "0,1,2,3,4,5,6,7,8,9".split(","); + private static final String[] DIGITS = "0,1,2,3,4,5,6,7,8,9".split(","); + private static final String[] NON_ZERO_DIGITS = "0,1,2,3,4,5,6,7,8,9".split(","); - private Primes() { - } // Uninstantiatable class + private Primes() {} // Uninstantiatable class - /** - * Finds the next prime number above a threshold. - */ + /** Finds the next prime number above a threshold. */ public static BigInteger nextPrime(BigInteger start) { if (isEven(start)) { start = start.add(ONE); @@ -41,8 +35,8 @@ public static BigInteger nextPrime(BigInteger start) { } /** - * Generates a random number of the given length, - * then finds the first prime number above that random number. + * Generates a random number of the given length, then finds the first prime number above that + * random number. */ public static BigInteger findPrime(int numDigits) { if (numDigits < 1) { @@ -63,11 +57,9 @@ private static String randomDigit(boolean isZeroOk) { } /** - * Creates a random big integer where every digit is - * selected randomly (except that the first digit - * cannot be a zero). + * Creates a random big integer where every digit is selected randomly (except that the first + * digit cannot be a zero). */ - public static BigInteger randomNum(int numDigits) { StringBuilder s = new StringBuilder(); // First digit must be non-zero. @@ -79,12 +71,9 @@ public static BigInteger randomNum(int numDigits) { } /** - * Simple command-line program to test. Enter number - * of digits, and the program picks a random number of that - * length and then prints the first 50 prime numbers - * above that. + * Simple command-line program to test. Enter number of digits, and the program picks a random + * number of that length and then prints the first 50 prime numbers above that. */ - public static void main(String[] args) { int numDigits; try { diff --git a/src/main/java/com/utilities/RandomUtils.java b/src/main/java/com/utilities/RandomUtils.java index f3ffa553..8beb911c 100755 --- a/src/main/java/com/utilities/RandomUtils.java +++ b/src/main/java/com/utilities/RandomUtils.java @@ -4,38 +4,28 @@ /** * An example to demonstrate writing your own generic method. - *

- * From the - * coreservlets.com tutorials on JSF 2, PrimeFaces, Ajax, jQuery, GWT, Android, - * Spring, Hibernate, JPA, RESTful Web Services, Hadoop, - * servlets, JSP, and Java 7 and Java 8 programming. + * + *

From the coreservlets.com + * tutorials on JSF 2, PrimeFaces, Ajax, jQuery, GWT, Android, Spring, Hibernate, JPA, RESTful Web + * Services, Hadoop, servlets, JSP, and Java 7 and Java 8 programming. */ public class RandomUtils { private static final Random r = new Random(); - /** - * Return a random int from 0 to range-1. So, randomInt(4) - * returns any of 0, 1, 2, or 3. - */ - + /** Return a random int from 0 to range-1. So, randomInt(4) returns any of 0, 1, 2, or 3. */ public static int randomInt(int range) { return (r.nextInt(range)); } - /** - * Return a random index of an array. - */ - + /** Return a random index of an array. */ public static int randomIndex(Object[] array) { return (randomInt(array.length)); } /** - * Return a random element from an array. - * Uses generics, so no typecast is required - * for the return value. + * Return a random element from an array. Uses generics, so no typecast is required for the + * return value. */ - public static T randomElement(T[] array) { return (array[randomIndex(array)]); } diff --git a/src/main/java/com/utilities/ReactorUtils.java b/src/main/java/com/utilities/ReactorUtils.java index 03fd55ba..bb087776 100644 --- a/src/main/java/com/utilities/ReactorUtils.java +++ b/src/main/java/com/utilities/ReactorUtils.java @@ -1,7 +1,6 @@ package com.utilities; import com.github.javafaker.Faker; - import java.util.function.Consumer; public class ReactorUtils { @@ -27,4 +26,4 @@ public static Runnable onComplete() { public static Faker faker() { return FAKER; } -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/RestGETReadUtility.java b/src/main/java/com/utilities/RestGETReadUtility.java index a1fb80a1..6289b0da 100644 --- a/src/main/java/com/utilities/RestGETReadUtility.java +++ b/src/main/java/com/utilities/RestGETReadUtility.java @@ -15,7 +15,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -26,7 +25,8 @@ public class RestGETReadUtility { - private static final String VEHICLE_URL = "https://random-data-api.com/api/vehicle/random_vehicle?size="; + private static final String VEHICLE_URL = + "https://random-data-api.com/api/vehicle/random_vehicle?size="; ObjectMapper mapper = new ObjectMapper(); public static void cardReader() { @@ -47,13 +47,13 @@ public static List getRandomVehicles(int size) { List randomVehicleList = new ArrayList<>(); try { - randomVehicleList = mapper.readValue(new URL(VEHICLE_URL + size), new TypeReference>() { - }); + randomVehicleList = + mapper.readValue( + new URL(VEHICLE_URL + size), new TypeReference>() {}); } catch (IOException e) { e.printStackTrace(); } return randomVehicleList; - } private static int getConnectionResponse(String urlLink) throws IOException { @@ -64,11 +64,16 @@ private static int getConnectionResponse(String urlLink) throws IOException { public static GitUser getRandomGitUsers() { ObjectMapper mapper = new ObjectMapper(); GitUser randomGitUser = null; - String url = "https://random-data-api.com/api/omniauth/github_get?size=100";//Returns a single git user - + String url = + "https://random-data-api.com/api/omniauth/github_get?size=100"; // Returns a single + // git user try { - randomGitUser = mapper.readValue(new URL(url), GitUser.class);//TODO : NOT WORKING, find a way to map to an array of GitUSers + randomGitUser = + mapper.readValue( + new URL(url), + GitUser.class); // TODO : NOT WORKING, find a way to map to an array of + // GitUSers } catch (IOException e) { e.printStackTrace(); } @@ -78,7 +83,8 @@ public static GitUser getRandomGitUsers() { public static Gutendex getGutenbergResults(String searchString) { ObjectMapper mapper = new ObjectMapper(); Gutendex results = null; - String url = "https://gutendex.com/books/?search=" + searchString;//Returns a singl;e git user + String url = + "https://gutendex.com/books/?search=" + searchString; // Returns a singl;e git user try { results = mapper.readValue(new URL(url), Gutendex.class); @@ -91,7 +97,9 @@ public static Gutendex getGutenbergResults(String searchString) { public static CrossRef getCrossRef(String searchString) { ObjectMapper mapper = new ObjectMapper(); CrossRef results = null; - String url = "https://api.crossref.org/works?query.author=" + searchString;//Returns a singl;e git user + String url = + "https://api.crossref.org/works?query.author=" + + searchString; // Returns a singl;e git user try { results = mapper.readValue(new URL(url), CrossRef.class); @@ -102,19 +110,24 @@ public static CrossRef getCrossRef(String searchString) { } public static List getBookDetailsOpenLibrary(String searchString) { - //Form the Search string like : ISBN:9780980200447,ISBN:0385472579,LCCN:62019420 - //Given Comma separated search strings + // Form the Search string like : ISBN:9780980200447,ISBN:0385472579,LCCN:62019420 + // Given Comma separated search strings String[] isbnStr = searchString.split(","); StringBuilder searchStringBuilder = new StringBuilder(); for (int i = 0; i < isbnStr.length; i++) { searchStringBuilder.append("ISBN:"); searchStringBuilder.append(isbnStr[i]); - searchStringBuilder.append(",");//Will result in Off-By-One error, but doesn't affec t results + searchStringBuilder.append( + ","); // Will result in Off-By-One error, but doesn't affec t results } URL url = null; try { - url = new URL("https://openlibrary.org/api/books?bibkeys=" + searchStringBuilder + "&format=json&jscmd=data"); + url = + new URL( + "https://openlibrary.org/api/books?bibkeys=" + + searchStringBuilder + + "&format=json&jscmd=data"); } catch (MalformedURLException e) { e.printStackTrace(); } @@ -130,20 +143,26 @@ public static List getBookDetailsOpenLibrary(String searchString) { } List openLibDtos = new ArrayList<>(); - Iterator itr = resultsMap.keySet().iterator();//Reponse from the service is in the dynamic form ISBN:9780980200447: { + Iterator itr = + resultsMap.keySet().iterator(); // Reponse from the service is in the dynamic form + // ISBN:9780980200447: { while (itr.hasNext()) { - String key = itr.next();//ISBN:9780980200447 is the key + String key = itr.next(); // ISBN:9780980200447 is the key openLibDtos.add(mapper.convertValue(resultsMap.get(key), OpenLibDto.class)); } return openLibDtos; } public static void getOpenLibIsbnSearchResultsWithGson() throws IOException { - URL url = new URL("https://openlibrary.org/api/books?bibkeys=ISBN:9780980200447,ISBN:0385472579,LCCN:62019420&jscmd=data&format=json"); + URL url = + new URL( + "https://openlibrary.org/api/books?bibkeys=ISBN:9780980200447,ISBN:0385472579,LCCN:62019420&jscmd=data&format=json"); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("GET"); // Google GSON library used - JsonObject jsonobj = JsonParser.parseReader(new InputStreamReader((InputStream) httpConn.getContent())).getAsJsonObject(); + JsonObject jsonobj = + JsonParser.parseReader(new InputStreamReader((InputStream) httpConn.getContent())) + .getAsJsonObject(); Gson gson = new Gson(); for (Map.Entry entry : jsonobj.entrySet()) { String key = entry.getKey(); @@ -155,7 +174,8 @@ public static void getOpenLibIsbnSearchResultsWithGson() throws IOException { } public static CurrencyExchange convertCurrency() { - String url_string = "https://api.exchangerate.host/convert?from=USD&to=INR&base=USD&historical=true&format=json"; + String url_string = + "https://api.exchangerate.host/convert?from=USD&to=INR&base=USD&historical=true&format=json"; ObjectMapper mapper = new ObjectMapper(); CurrencyExchange results = new CurrencyExchange(); @@ -170,23 +190,22 @@ public static CurrencyExchange convertCurrency() { } public static void main(String[] args) throws IOException { - //cardReader(); -// List list = covidReader(); -// list.forEach(x -> System.out.println(x.toString())); - //System.out.println(getRandomGitUsers().credentials.token); + // cardReader(); + // List list = covidReader(); + // list.forEach(x -> System.out.println(x.toString())); + // System.out.println(getRandomGitUsers().credentials.token); // System.out.println(getRandomVehicles().size()); /*getGutenbergResults("Pride+and+Prejudice") - .results.forEach(result -> result.getAuthors().forEach(author -> System.out.println(author.name))); + .results.forEach(result -> result.getAuthors().forEach(author -> System.out.println(author.name))); - //Item -> Author and Indexed - getCrossRef("jane+austin").getMessage().getItems().forEach(item -> System.out.println(item.getIsbn())); + //Item -> Author and Indexed + getCrossRef("jane+austin").getMessage().getItems().forEach(item -> System.out.println(item.getIsbn())); - //System.out.println(getBookDetailsOpenLibrary("9781108074568").getIsbn().getNumberOfPages()); + //System.out.println(getBookDetailsOpenLibrary("9781108074568").getIsbn().getNumberOfPages()); - getBookDetailsOpenLibrary("9780980200447,0385472579").forEach(isbn -> System.out.println(isbn.getNumberOfPages())); - getOpenLibIsbnSearchResultsWithGson(); -*/ + getBookDetailsOpenLibrary("9780980200447,0385472579").forEach(isbn -> System.out.println(isbn.getNumberOfPages())); + getOpenLibIsbnSearchResultsWithGson(); + */ System.out.println(convertCurrency().getResult()); } - -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/StringUtility.java b/src/main/java/com/utilities/StringUtility.java index 904c79d3..a192da91 100644 --- a/src/main/java/com/utilities/StringUtility.java +++ b/src/main/java/com/utilities/StringUtility.java @@ -1,13 +1,9 @@ package com.utilities; -import lombok.NoArgsConstructor; - import java.util.Arrays; +import lombok.NoArgsConstructor; -/** - * Created by nichaurasia on Saturday, April/25/2020 at 3:46 AM - */ - +/** Created by nichaurasia on Saturday, April/25/2020 at 3:46 AM */ @NoArgsConstructor public class StringUtility { public static boolean isEmpty(String obj) { @@ -37,4 +33,4 @@ public static String sortString(String str) { public static String reverseString(String str) { return new StringBuilder(str).reverse().toString(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/TimeStampUtilities.java b/src/main/java/com/utilities/TimeStampUtilities.java index 8bfcead4..e7385d11 100644 --- a/src/main/java/com/utilities/TimeStampUtilities.java +++ b/src/main/java/com/utilities/TimeStampUtilities.java @@ -92,4 +92,4 @@ public String convertTimestampToString(Timestamp aTimestamp, String pattern) { } return aDateStr; } -} \ No newline at end of file +} diff --git a/src/main/java/com/utilities/UuidUtils.java b/src/main/java/com/utilities/UuidUtils.java index f21de9be..b9e95f0f 100644 --- a/src/main/java/com/utilities/UuidUtils.java +++ b/src/main/java/com/utilities/UuidUtils.java @@ -5,7 +5,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -//@NoArgsConstructor(access = AccessLevel.PUBLIC) +// @NoArgsConstructor(access = AccessLevel.PUBLIC) public class UuidUtils { public static String getUuidId(String id) { @@ -14,13 +14,10 @@ public static String getUuidId(String id) { } public static Map getIdToIdMap(List idList) { - return idList.stream() - .collect(Collectors.toMap(Function.identity(), UuidUtils::getUuidId)); + return idList.stream().collect(Collectors.toMap(Function.identity(), UuidUtils::getUuidId)); } public static List getPatientIds(Collection idList) { - return idList.stream() - .map(UuidUtils::getUuidId) - .collect(Collectors.toList()); + return idList.stream().map(UuidUtils::getUuidId).collect(Collectors.toList()); } } diff --git a/src/main/java/com/utilities/ZonedDateTimeUtility.java b/src/main/java/com/utilities/ZonedDateTimeUtility.java index 89b1e3e8..79764e12 100644 --- a/src/main/java/com/utilities/ZonedDateTimeUtility.java +++ b/src/main/java/com/utilities/ZonedDateTimeUtility.java @@ -21,11 +21,14 @@ public static ZonedDateTime getZonedDateTime(String startDateTime, String timeZo String inputDateTimePattern = "yyyy-MM-dd HH:mm:ssX"; ZonedDateTime zonedDateTime = null; try { - zonedDateTime = ZonedDateTime - .parse(startDateTime, - DateTimeFormatter.ofPattern(inputDateTimePattern)//Date Time format of incomming String - .withZone(ZoneOffset.UTC)) - .withZoneSameInstant(ZoneId.of(timeZoneIso)); + zonedDateTime = + ZonedDateTime.parse( + startDateTime, + DateTimeFormatter.ofPattern( + inputDateTimePattern) // Date Time format of + // incomming String + .withZone(ZoneOffset.UTC)) + .withZoneSameInstant(ZoneId.of(timeZoneIso)); } catch (ZoneRulesException e) { System.out.println(e.getMessage()); @@ -34,21 +37,27 @@ public static ZonedDateTime getZonedDateTime(String startDateTime, String timeZo return zonedDateTime; } - public static Result getFormattedTimezoneString(String startDateTime, String endDateTime, String timeZoneIso) { - String outputDiffDateFormat = "MM/dd/yyyy HH:mm zzz"; - String outputSameDateFormat = "HH:mm zzz"; + public static Result getFormattedTimezoneString( + String startDateTime, String endDateTime, String timeZoneIso) { + String outputDiffDateFormat = "MM/dd/yyyy HH:mm zzz"; + String outputSameDateFormat = "HH:mm zzz"; ZonedDateTime zonedStartDateTime = getZonedDateTime(startDateTime, timeZoneIso); ZonedDateTime zonedEndDateTime = getZonedDateTime(endDateTime, timeZoneIso); String startDate; String endDate; - //If there is a Difference is of One day, Show both date and Time - if (zonedEndDateTime.toLocalDate().minusDays(1L).isEqual(zonedStartDateTime.toLocalDate())) { - startDate = zonedStartDateTime.format(DateTimeFormatter.ofPattern(outputDiffDateFormat)); + // If there is a Difference is of One day, Show both date and Time + if (zonedEndDateTime + .toLocalDate() + .minusDays(1L) + .isEqual(zonedStartDateTime.toLocalDate())) { + startDate = + zonedStartDateTime.format(DateTimeFormatter.ofPattern(outputDiffDateFormat)); endDate = zonedEndDateTime.format(DateTimeFormatter.ofPattern(outputDiffDateFormat)); - } else {//Else show just the time for the same dat scenario - startDate = zonedStartDateTime.format(DateTimeFormatter.ofPattern(outputSameDateFormat)); + } else { // Else show just the time for the same dat scenario + startDate = + zonedStartDateTime.format(DateTimeFormatter.ofPattern(outputSameDateFormat)); endDate = zonedEndDateTime.format(DateTimeFormatter.ofPattern(outputSameDateFormat)); } @@ -56,7 +65,5 @@ public static Result getFormattedTimezoneString(String startDateTime, String end return result; } - public record Result(String startDate, String endDate) { - } - + public record Result(String startDate, String endDate) {} } diff --git a/src/main/java/nitin/AccessingAllClassesInPackage.java b/src/main/java/nitin/AccessingAllClassesInPackage.java index de02a9a0..727d0f65 100644 --- a/src/main/java/nitin/AccessingAllClassesInPackage.java +++ b/src/main/java/nitin/AccessingAllClassesInPackage.java @@ -1,20 +1,20 @@ package nitin; import com.google.common.reflect.ClassPath; -import org.reflections.Reflections; -import org.reflections.scanners.SubTypesScanner; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Set; import java.util.stream.Collectors; +import org.reflections.Reflections; +import org.reflections.scanners.SubTypesScanner; public class AccessingAllClassesInPackage { public Set findAllClassesUsingClassLoader(String packageName) { - InputStream stream = ClassLoader.getSystemClassLoader() - .getResourceAsStream(packageName.replaceAll("[.]", "/")); + InputStream stream = + ClassLoader.getSystemClassLoader() + .getResourceAsStream(packageName.replaceAll("[.]", "/")); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); return reader.lines() .filter(line -> line.endsWith(".class")) @@ -24,8 +24,8 @@ public Set findAllClassesUsingClassLoader(String packageName) { private Class getClass(String className, String packageName) { try { - return Class.forName(packageName + "." - + className.substring(0, className.lastIndexOf('.'))); + return Class.forName( + packageName + "." + className.substring(0, className.lastIndexOf('.'))); } catch (ClassNotFoundException e) { // handle the exception } @@ -33,19 +33,14 @@ private Class getClass(String className, String packageName) { } public Set findAllClassesUsingGoogleGuava(String packageName) throws IOException { - return ClassPath.from(ClassLoader.getSystemClassLoader()) - .getAllClasses() - .stream() - .filter(clazz -> clazz.getPackageName() - .equalsIgnoreCase(packageName)) + return ClassPath.from(ClassLoader.getSystemClassLoader()).getAllClasses().stream() + .filter(clazz -> clazz.getPackageName().equalsIgnoreCase(packageName)) .map(clazz -> clazz.load()) .collect(Collectors.toSet()); } public Set findAllClassesUsingReflectionsLibrary(String packageName) { Reflections reflections = new Reflections(packageName, new SubTypesScanner(false)); - return reflections.getSubTypesOf(Object.class) - .stream() - .collect(Collectors.toSet()); + return reflections.getSubTypesOf(Object.class).stream().collect(Collectors.toSet()); } } diff --git a/src/main/java/nitin/ApacheCommons.java b/src/main/java/nitin/ApacheCommons.java index 5f7e41f4..b9171dfe 100644 --- a/src/main/java/nitin/ApacheCommons.java +++ b/src/main/java/nitin/ApacheCommons.java @@ -10,14 +10,14 @@ public static void main(String[] args) { } private static void compareString() { - //No exception handling required + // No exception handling required System.out.println(StringUtils.equalsIgnoreCase("Nitin", null)); - //If above Apache commons is not used + // If above Apache commons is not used System.out.println("Nitin".equalsIgnoreCase("null")); - //Null needs be handled - //System.out.println(null.equalsIgnoreCase("Nitin")); + // Null needs be handled + // System.out.println(null.equalsIgnoreCase("Nitin")); } private static void stringToCurrency() { @@ -30,9 +30,10 @@ private static void stringToCurrency() { } if (str != null) { - //Number format exception on str="NK" - //str = "$" + new java.text.DecimalFormat("##0.00").format(Double.parseDouble(str)); - //System.out.println(str); + // Number format exception on str="NK" + // str = "$" + new + // java.text.DecimalFormat("##0.00").format(Double.parseDouble(str)); + // System.out.println(str); } } } diff --git a/src/main/java/nitin/AutoBoxingNUnboxing.java b/src/main/java/nitin/AutoBoxingNUnboxing.java index 6e1e10de..c3075944 100644 --- a/src/main/java/nitin/AutoBoxingNUnboxing.java +++ b/src/main/java/nitin/AutoBoxingNUnboxing.java @@ -3,29 +3,26 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by Nitin Chaurasia on 2/1/18 at 9:03 PM. - */ +/** Created by Nitin Chaurasia on 2/1/18 at 9:03 PM. */ public class AutoBoxingNUnboxing { public static void main(String[] args) { int i = 5; long j = 105L; - //passed the int, will get converted to Integer a5object at Runtime + // passed the int, will get converted to Integer a5object at Runtime doSomething(i); List list = new ArrayList<>(); - //autoboxing to add primitive type in collection classes + // autoboxing to add primitive type in collection classes list.add(j); } private static void doSomething(Integer wrapperInt) { - //unboxing, at runtime Integer.intValue() is called implicitly to return int + // unboxing, at runtime Integer.intValue() is called implicitly to return int int j = wrapperInt; - //unboxing, Integer is passed where int was expected + // unboxing, Integer is passed where int was expected doPrimitive(wrapperInt); } - private static void doPrimitive(int i) { - } -} \ No newline at end of file + private static void doPrimitive(int i) {} +} diff --git a/src/main/java/nitin/JDBC/BasicConnection.java b/src/main/java/nitin/JDBC/BasicConnection.java index b01743ab..5c10e521 100644 --- a/src/main/java/nitin/JDBC/BasicConnection.java +++ b/src/main/java/nitin/JDBC/BasicConnection.java @@ -2,17 +2,16 @@ import java.sql.*; -/** - * Created by Nitin C on 3/4/2016. - */ +/** Created by Nitin C on 3/4/2016. */ public class BasicConnection { public static void main(String[] args) throws SQLException { - //final String DB_URL = "//localhost:3306/test"; - //To avoid java.sql.SQLException: The server timezone value 'UTC' is unrecognized - //?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC + // final String DB_URL = "//localhost:3306/test"; + // To avoid java.sql.SQLException: The server timezone value 'UTC' is unrecognized + // ?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC // SET GLOBAL time_zone = '+3:00'; - final String DB_URL = "//localhost:3306/HabitTracking?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; + final String DB_URL = + "//localhost:3306/HabitTracking?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; final String USER = "root"; final String PASSWORD = "root"; @@ -30,15 +29,15 @@ public static void main(String[] args) throws SQLException { // 3. Create Query PreparedStatement ps = conn.prepareStatement(QUERY); - //ps.setString(1,"id"); + // ps.setString(1,"id"); // 4. Execute statement ResultSet rs = ps.executeQuery(); - //Traverse through the Cursor - //if (rs.next()){ //To Print just one row + // Traverse through the Cursor + // if (rs.next()){ //To Print just one row while (rs.next()) { - //Traverse through the iterator. + // Traverse through the iterator. int e_id = rs.getInt(1); String e_name = rs.getString(2); @@ -49,4 +48,4 @@ public static void main(String[] args) throws SQLException { rs.close(); conn.close(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/LambdaExpressions/L0SpottingInvalidLambdas.java b/src/main/java/nitin/LambdaExpressions/L0SpottingInvalidLambdas.java index b284b25e..aff4b0dc 100644 --- a/src/main/java/nitin/LambdaExpressions/L0SpottingInvalidLambdas.java +++ b/src/main/java/nitin/LambdaExpressions/L0SpottingInvalidLambdas.java @@ -1,30 +1,27 @@ package nitin.LambdaExpressions; - import com.entity.SampleData; - import java.util.List; -/** - * Created by Nitin C on 3/5/2016. - */ +/** Created by Nitin C on 3/5/2016. */ public class L0SpottingInvalidLambdas { public static void main(String[] args) { - TestInterfaceReturnMethod y;//Functional Interface + TestInterfaceReturnMethod y; // Functional Interface - //Defining Lambda - y = (arg1, arg2) -> arg1 + arg2;//Providing implementation to the abstract method + // Defining Lambda + y = (arg1, arg2) -> arg1 + arg2; // Providing implementation to the abstract method int resultForStoringY = y.methodWtih2Args(1, 2); System.out.println(resultForStoringY); - y = (n, m) -> n * m;//redefining implementation + y = (n, m) -> n * m; // redefining implementation System.out.println(y.methodWtih2Args(2, 3)); /* Without Curly braces we can't use return keyword */ - y = (n, m) -> {//if using curly braces, have to use return statement - return n * m; - }; + y = + (n, m) -> { // if using curly braces, have to use return statement + return n * m; + }; /* RETURN Always need curly braces and ends with a colon */ /********************* INVALID LAMBDAS ********************/ @@ -36,38 +33,37 @@ public static void main(String[] args) { // () can be omitted only if there is EXACTLY ONE Parameter and NO DATA TYPE - /* - String a = "Nitin"; - - //VALID Lambdas - MyFunctionalInterface t; - t = () -> true; //ZERO Parameter, return Boolean - t = a -> {return a.startsWith("Ni");} - t = (String a) -> a.startsWith("Ni") - t = (int x) -> {} //One parameter and no function body - t = (int y) -> {return;} - - s = (a , b) -> a.startsWith("Ni")//2 parameters - - multiple parameters need to be enclosed in the brackets. - a,b -> a.startsWith("Ni")//DOES NOT COMPILE : need small brackets - CORRECT: (a,b) -> a.startsWith("Ni") - - c -> return 10;// DOES NOT COMPILE : return keyword without {} - CORRECT: c -> { return 10; } - a -> {return a.startsWith("test")}//DOES NOT COMPILE : need ; after return - CORRECT: - a -> { return a.startsWith("test"); } - - // DATA TYPES FOR THE INPUT PARAMETERS OF A LAMBDA EXPRESSION IS OPTIONAL - (int y, z) -> { int x = 1; return x+y; }// DOES NOT COMPILE : Either both have data types or none - CORRECT: ( y, z) -> { int x = 1; return x+y; } - OR CORRECT: (int y, int z) -> { int x = 1; return x+y; } - - (a,b) -> { int a = 9; return a+b }//DOES NOT COMPILE: Redeclaration of a - (a,b) -> { int c = 9; return a+b }// CORRECT AS C is an independent local variable -*/ + String a = "Nitin"; + + //VALID Lambdas + MyFunctionalInterface t; + t = () -> true; //ZERO Parameter, return Boolean + t = a -> {return a.startsWith("Ni");} + t = (String a) -> a.startsWith("Ni") + t = (int x) -> {} //One parameter and no function body + t = (int y) -> {return;} + + s = (a , b) -> a.startsWith("Ni")//2 parameters + + multiple parameters need to be enclosed in the brackets. + a,b -> a.startsWith("Ni")//DOES NOT COMPILE : need small brackets + CORRECT: (a,b) -> a.startsWith("Ni") + + c -> return 10;// DOES NOT COMPILE : return keyword without {} + CORRECT: c -> { return 10; } + a -> {return a.startsWith("test")}//DOES NOT COMPILE : need ; after return + CORRECT: + a -> { return a.startsWith("test"); } + + // DATA TYPES FOR THE INPUT PARAMETERS OF A LAMBDA EXPRESSION IS OPTIONAL + (int y, z) -> { int x = 1; return x+y; }// DOES NOT COMPILE : Either both have data types or none + CORRECT: ( y, z) -> { int x = 1; return x+y; } + OR CORRECT: (int y, int z) -> { int x = 1; return x+y; } + + (a,b) -> { int a = 9; return a+b }//DOES NOT COMPILE: Redeclaration of a + (a,b) -> { int c = 9; return a+b }// CORRECT AS C is an independent local variable + */ int a = 10, b = 20; List list = SampleData.intCargoSequence(5, 10); @@ -79,10 +75,10 @@ public static void main(String[] args) { x = () -> System.out.print(resultForStoringY); x.voidMethod(); - //for each expects a Consumer - //list.forEach((element) -> System.out.println(element)); - //for void or one parameter, the same can be written as - //list.forEach(System.out :: println); + // for each expects a Consumer + // list.forEach((element) -> System.out.println(element)); + // for void or one parameter, the same can be written as + // list.forEach(System.out :: println); } @FunctionalInterface diff --git a/src/main/java/nitin/LambdaExpressions/L1BasicWithListIteration.java b/src/main/java/nitin/LambdaExpressions/L1BasicWithListIteration.java index bc16ee83..9b64b61f 100644 --- a/src/main/java/nitin/LambdaExpressions/L1BasicWithListIteration.java +++ b/src/main/java/nitin/LambdaExpressions/L1BasicWithListIteration.java @@ -6,9 +6,9 @@ /** * Created by Nitin C on 2/27/2016. - *

- * The biggest change in the Java 8 is in the minds of the programmers. - * A lot of fun to be learning a better way of programming + * + *

The biggest change in the Java 8 is in the minds of the programmers. A lot of fun to be + * learning a better way of programming */ public class L1BasicWithListIteration { public static void main(String[] args) { @@ -21,12 +21,12 @@ public static void main(String[] args) { // Complex, initial (boundary less than or less than equal to) // Self inflicted wound pattern for (int i = 0; i < list.size(); i++) { - //System.out.println(list.get(i)); + // System.out.println(list.get(i)); } // Fewer moving parts for (int element : list) { - //System.out.println(element); + // System.out.println(element); } /************************ @@ -38,12 +38,14 @@ public static void main(String[] args) { // Anonymous inner class // This gives polymorphism // forEach method is now on a10collections - list.forEach(new Consumer() {//Consumer is a new interface in java 8 - @Override - public void accept(Integer value) {// method of consumer, which accepts the array - //System.out.println(value); - } - }); + list.forEach( + new Consumer() { // Consumer is a new interface in java 8 + @Override + public void accept( + Integer value) { // method of consumer, which accepts the array + // System.out.println(value); + } + }); // FUNDAMENTAL DIFFERENCE SEMANTICALLY @@ -51,7 +53,8 @@ public void accept(Integer value) {// method of consumer, which accepts the arra // and decide the implementation at one time. Whether its sequential or concurrent or lazy, // i don't want now, it want to postpone the decision to a later time - // Ceremony is the things that you HAVE do before you do before you do what you REALLY want to do + // Ceremony is the things that you HAVE do before you do before you do what you REALLY want + // to do list.forEach((Integer element) -> System.out.print(element)); System.out.println(); /* forEach says i am accepting a function CONSUMER @@ -71,13 +74,14 @@ public void accept(Integer value) {// method of consumer, which accepts the arra list.forEach(element -> System.out.print(element)); System.out.println(); - //Even Shorter + // Even Shorter list.forEach(System.out::print); System.out.println(); // ForEach receives a Consumer functional parameter // Functional Interface : can be automatically be elevated to lambda expression // In other words, you can Only use lambdas for functional interfaces - // A functional interface is a SAM (Single abstract Method) interface. it can only have one abstract method + // A functional interface is a SAM (Single abstract Method) interface. it can only have one + // abstract method // that method has signature with parameter coming in. // Functional interface assign a contract!! @@ -94,14 +98,11 @@ public void accept(Integer value) {// method of consumer, which accepts the arra System.out.println(total); - //Declarative style - System.out.println( - list.stream() - .map(e -> e * 2) - .reduce(0, (c, e) -> c + e)); + // Declarative style + System.out.println(list.stream().map(e -> e * 2).reduce(0, (c, e) -> c + e)); } // Old interface evolved : through default methods - //Default method is a method implementation, you can write within an interface + // Default method is a method implementation, you can write within an interface -} \ No newline at end of file +} diff --git a/src/main/java/nitin/LambdaExpressions/L2.java b/src/main/java/nitin/LambdaExpressions/L2.java index 5d427b95..626e384b 100644 --- a/src/main/java/nitin/LambdaExpressions/L2.java +++ b/src/main/java/nitin/LambdaExpressions/L2.java @@ -16,7 +16,6 @@ default void cruise() { default void land() { System.out.println("Fly::land"); } - } interface FastFly extends Fly { @@ -33,12 +32,10 @@ default void cruise() { } /** - * Created by Nitin C on 2/27/2016. - * 4 Rules of Default Methods - * 1. methods are automatically inherited eg - * 2. Override a default method, if it doesn't find in the child, it goes up the hierarchy top check the method out - * 3. Methods in a class Hierarchy RULES!! - * 4. if there is a collision in interface + * Created by Nitin C on 2/27/2016. 4 Rules of Default Methods 1. methods are automatically + * inherited eg 2. Override a default method, if it doesn't find in the child, it goes up the + * hierarchy top check the method out 3. Methods in a class Hierarchy RULES!! 4. if there is a + * collision in interface */ // Till Java 7, only method signature // Now we can set to Default and implement @@ -57,11 +54,11 @@ public static void main(String[] args) { public void use() { SeaPlane seaPlane = new SeaPlane(); - seaPlane.takeOff();//Calls from fast Fly, the nearest implementation + seaPlane.takeOff(); // Calls from fast Fly, the nearest implementation seaPlane.turn(); seaPlane.cruise(); // which land, vehicle land or Fly land - seaPlane.land();//if the method is in class hierarchy, thjat methid rules!! + seaPlane.land(); // if the method is in class hierarchy, thjat methid rules!! } } @@ -72,13 +69,13 @@ public void land() { } } -//default cruise method is available in both the interfaces -//SeaPlane inherits unrelated defaults for cruise() from types Fly and Sail +// default cruise method is available in both the interfaces +// SeaPlane inherits unrelated defaults for cruise() from types Fly and Sail class SeaPlane extends Vehicle implements FastFly, Sail { - //To avoid the method HAVE TO OVER WRITE + // To avoid the method HAVE TO OVER WRITE public void cruise() { System.out.println("Seaplane::cruise"); - FastFly.super.cruise();//super has to be used because interfaces can have static methoids + FastFly.super.cruise(); // super has to be used because interfaces can have static methoids // If you dont use super, it will thin u are calling static method. with super, its default } } diff --git a/src/main/java/nitin/LambdaExpressions/L3FunctionalInterfaceAsArgument.java b/src/main/java/nitin/LambdaExpressions/L3FunctionalInterfaceAsArgument.java index 6e4873aa..d28a78d0 100644 --- a/src/main/java/nitin/LambdaExpressions/L3FunctionalInterfaceAsArgument.java +++ b/src/main/java/nitin/LambdaExpressions/L3FunctionalInterfaceAsArgument.java @@ -6,27 +6,25 @@ /** * Created by Nitin C on 2/27/2016. - *

- * Strategy pattern. writing a function to be called from Lambda + * + *

Strategy pattern. writing a function to be called from Lambda */ public class L3FunctionalInterfaceAsArgument { public static void main(String[] args) { List values = Arrays.asList(1, 2, 3, 4, 5, 6); - //Print sum of all numbers + // Print sum of all numbers System.out.println(totalValues(values, e -> true)); - //Print sum of all all Even numbers + // Print sum of all all Even numbers System.out.println(totalValues(values, e -> e % 2 == 0)); - //Print sum of all odd numbers + // Print sum of all odd numbers System.out.println(totalValues(values, e -> e % 2 != 0)); } public static int totalValues(List numbers, Predicate selector) { - return numbers.stream() - .filter(selector) - .reduce(0, (c, e) -> c + e); + return numbers.stream().filter(selector).reduce(0, (c, e) -> c + e); // reduce (0, (c,e) ...) needs a seed value to begin with // thus c = 0 and subsquiently c becomes the result of the previous call } diff --git a/src/main/java/nitin/LambdaExpressions/L4LazyEvaluation.java b/src/main/java/nitin/LambdaExpressions/L4LazyEvaluation.java index fd85edcb..55d3d3b1 100644 --- a/src/main/java/nitin/LambdaExpressions/L4LazyEvaluation.java +++ b/src/main/java/nitin/LambdaExpressions/L4LazyEvaluation.java @@ -5,53 +5,61 @@ /** * Created by Nitin C on 2/27/2016. - *

- * The double of the first even number > 3 and in the a_list + * + *

The double of the first even number > 3 and in the a_list */ - public class L4LazyEvaluation { public static void main(String[] args) { List values = Arrays.asList(1, 2, 3, 4, 5, 6); - //Imparative Code + // Imparative Code int result = 0; for (int e : values) { - if (e > 3 && e % 2 == 0) {// testing for 1,2,3,4 and the break: 8 times if test + if (e > 3 && e % 2 == 0) { // testing for 1,2,3,4 and the break: 8 times if test result = e * 2; break; } } System.out.println(result); - //Returns 0 if there is no integer exists - //This code reveals the details + // Returns 0 if there is no integer exists + // This code reveals the details System.out.println( values.stream() .filter(e -> e > 3) .filter(e -> e % 2 == 0) .map(e -> e * 2) .findFirst() - .orElse(0) - ); + .orElse(0)); - //testing for the number of time it is working - //Demonstrating the LAZY + // testing for the number of time it is working + // Demonstrating the LAZY System.out.println( values.stream() - .filter(L4LazyEvaluation::isGT3)//another way of calling a method from lambda - //.filter(value -> L4LazyEvaluation.isGT3(value)) - .filter(L4LazyEvaluation::isEven)//functions like filter and map are called intermediate functions. They are LAzy + .filter( + L4LazyEvaluation + ::isGT3) // another way of calling a method from lambda + // .filter(value -> L4LazyEvaluation.isGT3(value)) + .filter( + L4LazyEvaluation + ::isEven) // functions like filter and map are called + // intermediate functions. They are LAzy .map(L4LazyEvaluation::doubleIt) - .findFirst() //terminal Function: triggers the computations, the code ACTUALLY STARTS WORKING - // FROM THIS POINT ON due to LAziness. The computations are only enough to get the work done - .orElse(0) - ); + .findFirst() // terminal Function: triggers the computations, the code + // ACTUALLY STARTS WORKING + // FROM THIS POINT ON due to LAziness. The computations are only enough to + // get the work done + .orElse(0)); - //Demonstrating the LAZY way by removing the terminal function. the intermediatry doent even do anything + // Demonstrating the LAZY way by removing the terminal function. the intermediatry doent + // even do anything // this is LAZY evaluation. in Java its called efficient!! values.stream() - .filter(L4LazyEvaluation::isGT3)//another way of calling a method from lambda - .filter(L4LazyEvaluation::isEven)//functions like filter and map are called intermediate functions. They are LAzy + .filter(L4LazyEvaluation::isGT3) // another way of calling a method from lambda + .filter( + L4LazyEvaluation + ::isEven) // functions like filter and map are called intermediate + // functions. They are LAzy .map(L4LazyEvaluation::doubleIt); System.out.println("here"); diff --git a/src/main/java/nitin/LambdaExpressions/LocalVarLambda.java b/src/main/java/nitin/LambdaExpressions/LocalVarLambda.java index 907e3b9a..1d5756e7 100644 --- a/src/main/java/nitin/LambdaExpressions/LocalVarLambda.java +++ b/src/main/java/nitin/LambdaExpressions/LocalVarLambda.java @@ -6,19 +6,18 @@ import java.util.stream.Collectors; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 5:43 PM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 5:43 PM */ - public class LocalVarLambda { public static void main(String[] args) { List list = Arrays.asList("a", "b", "c", null); - String result = list.stream() - //.map(x -> x.toUpperCase()) - .filter(Objects::nonNull) - .map((var x) -> x.toUpperCase()) - .collect(Collectors.joining(",")); + String result = + list.stream() + // .map(x -> x.toUpperCase()) + .filter(Objects::nonNull) + .map((var x) -> x.toUpperCase()) + .collect(Collectors.joining(",")); System.out.println(result); } } diff --git a/src/main/java/nitin/LambdaExpressions/LoopThroughCollections.java b/src/main/java/nitin/LambdaExpressions/LoopThroughCollections.java index b4403289..95c0c8dd 100644 --- a/src/main/java/nitin/LambdaExpressions/LoopThroughCollections.java +++ b/src/main/java/nitin/LambdaExpressions/LoopThroughCollections.java @@ -4,9 +4,7 @@ import java.util.List; import java.util.function.Consumer; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class LoopThroughCollections { public static void main(String[] args) { List list = Arrays.asList(1, 2, 1, 4, 5, 6); @@ -14,24 +12,24 @@ public static void main(String[] args) { // PRINT USING ArrayList Default toString method System.out.println(list); - //Print Using Lambda with CONSUMER - not very Common - list.forEach(l -> System.out.print(l + ", "));// Off by one for the last comma!! + // Print Using Lambda with CONSUMER - not very Common + list.forEach(l -> System.out.print(l + ", ")); // Off by one for the last comma!! System.out.println(); - //Print using static reference - list.forEach(System.out::print);// How to insert a comma between elements + // Print using static reference + list.forEach(System.out::print); // How to insert a comma between elements System.out.println(); - //Demonstration that forEach accepts Consumer + // Demonstration that forEach accepts Consumer Consumer c1 = (System.out::print); // Prints com.nitin.a15java8.lambda.LoopThroughCollections$$Lambda$3/1023892928@214c265e // This is the result of calling toString() on a Lambda - //Fully Qualified Class name is followed by $$ which means that the class doesn't exist in a class file + // Fully Qualified Class name is followed by $$ which means that the class doesn't exist in + // a class file // on the file system. IT exists only in the memory System.out.println(c1); list.forEach(c1); - } } diff --git a/src/main/java/nitin/LambdaExpressions/joining/JoiningElements.java b/src/main/java/nitin/LambdaExpressions/joining/JoiningElements.java index 52bf41da..629df68b 100644 --- a/src/main/java/nitin/LambdaExpressions/joining/JoiningElements.java +++ b/src/main/java/nitin/LambdaExpressions/joining/JoiningElements.java @@ -4,9 +4,7 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by nitin on Thursday, February/13/2020 at 9:50 PM - */ +/** Created by nitin on Thursday, February/13/2020 at 9:50 PM */ public class JoiningElements { public static void main(String[] args) { List list = Arrays.asList("John", "Doe", "Jane", "Dow", "Yong", "Lee"); @@ -20,9 +18,7 @@ public static void main(String[] args) { // No more Off-By-One Error System.out.println(String.join(", ", list)); - String list2 = list.stream() - .map(String::toUpperCase) - .collect(Collectors.joining(" && ")); + String list2 = list.stream().map(String::toUpperCase).collect(Collectors.joining(" && ")); System.out.println(list2); } diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/Example.java b/src/main/java/nitin/LambdaExpressions/methodRef/Example.java index 5cc3c2d3..d846db46 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/Example.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/Example.java @@ -8,22 +8,27 @@ interface Display { public class Example { public static void main(String[] args) { - //Declare the Lambda directly - Display displayDeclaredHere = (a, b) -> System.out.println("method reference in java 8 : " + (a + b)); + // Declare the Lambda directly + Display displayDeclaredHere = + (a, b) -> System.out.println("method reference in java 8 : " + (a + b)); displayDeclaredHere.displayResults(5, 55); - //extracted method - Display displayExtractedSameClass = getDisplay();//this::getDisplay works with non-static classes + // extracted method + Display displayExtractedSameClass = + getDisplay(); // this::getDisplay works with non-static classes displayExtractedSameClass.displayResults(10, 20); - //Taking the definition into another class, or using another class to define the interface + // Taking the definition into another class, or using another class to define the interface MethodReferences obj = new MethodReferences(); // Reference to the method using the a5object of the class myMethod - Display displayInstanceMethodParticularObject = ((a, b) -> obj.myMethod(a, b));//putting the definition in a5object of another class + Display displayInstanceMethodParticularObject = + ((a, b) -> + obj.myMethod(a, b)); // putting the definition in a5object of another class // Calling the method inside the functional interface Display displayInstanceMethodParticularObject.displayResults(1, 3); - Display displayReferenceInstanceMethodParticularObject = obj::myMethod;//calling the same via method reference + Display displayReferenceInstanceMethodParticularObject = + obj::myMethod; // calling the same via method reference displayReferenceInstanceMethodParticularObject.displayResults(6, 6); } @@ -31,4 +36,3 @@ private static Display getDisplay() { return (a, b) -> System.out.println("method reference in java 8 : " + a + b); } } - diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/Example2.java b/src/main/java/nitin/LambdaExpressions/methodRef/Example2.java index d4a8df59..3cd2c1e4 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/Example2.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/Example2.java @@ -2,7 +2,6 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.io.PrintStream; import java.util.List; @@ -16,11 +15,13 @@ public static void main(String[] args) { // Reference to an instance method of an **arbitrary a5object** of a particular type System.out.println(myApp.playBiFunction("Hello ", "World!", String::concat)); // Reference to an **instance method** of a particular a5object - System.out.println(myApp.playBiFunction("Hello ", "World!", ((a, b) -> myApp.appendStrings(a, b)))); + System.out.println( + myApp.playBiFunction("Hello ", "World!", ((a, b) -> myApp.appendStrings(a, b)))); System.out.println(myApp.playBiFunction("Hello ", "World!", myApp::appendStrings)); // Reference to a static method - System.out.println(myApp.playBiFunction("Hello ", "World!", MethodReferences::staticAppendStrings)); + System.out.println( + myApp.playBiFunction("Hello ", "World!", MethodReferences::staticAppendStrings)); // Calling Static method From Math Library System.out.println(myApp.playBiFunction(3.0, 4.0, (x, y) -> Math.hypot(x, y))); @@ -33,7 +34,7 @@ public static void main(String[] args) { // Reference to an **instance method** of a particular a5object list.forEach(printStream::println); - //Reference to an Instance Method of an Arbitrary Object of a Particular Type + // Reference to an Instance Method of an Arbitrary Object of a Particular Type list.forEach(EmployeeSimple::printNameWithSalary); } } diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/MethodRefTypes.java b/src/main/java/nitin/LambdaExpressions/methodRef/MethodRefTypes.java index 39f80773..a4ec79ed 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/MethodRefTypes.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/MethodRefTypes.java @@ -12,15 +12,11 @@ public static void main(String[] args) { List list = Arrays.asList(str2.split(",")); - List updatedList = list - .stream() - .map(String::toUpperCase) - .collect(Collectors.toList()); + List updatedList = + list.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println(updatedList); System.out.println(str1.concat(str2)); - - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/MethodReferences.java b/src/main/java/nitin/LambdaExpressions/methodRef/MethodReferences.java index 47f9da4d..2d0f23d7 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/MethodReferences.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/MethodReferences.java @@ -4,7 +4,7 @@ public class MethodReferences { - //Static method Demonstration to be called as MethodReferences::staticAppendStrings + // Static method Demonstration to be called as MethodReferences::staticAppendStrings public static String staticAppendStrings(String a, String b) { return a + b; } @@ -13,7 +13,7 @@ public T playBiFunction(T a, T b, BiFunction biFunction) { return biFunction.apply(a, b); } - //Instance method + // Instance method public void myMethod(int a, int b, Display display) { System.out.println("method reference in java 8 : "); display.displayResults(a, b); diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Learnable.java b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Learnable.java index 8f19869b..c3048cd9 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Learnable.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Learnable.java @@ -3,4 +3,4 @@ @FunctionalInterface interface Learnable { T learn(T a, T b); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Runner.java b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Runner.java index 9027938f..431fa94b 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Runner.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Runner.java @@ -2,8 +2,6 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; -import org.apache.commons.math3.util.MathUtils; - import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -11,6 +9,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; +import org.apache.commons.math3.util.MathUtils; public class Runner { @@ -20,18 +19,21 @@ public void runMeFirst() { System.out.println(methodRefTest.testMethodRef("John", "Doe", (p, q) -> p.concat(q))); System.out.println(methodRefTest.testMethodRef("John", "Doe", (String::concat))); - //Reference to a static method + // Reference to a static method System.out.println(methodRefTest.testMethodRef(3.0, 4.0, (a, b) -> findHypotenous(a, b))); - System.out.println(methodRefTest.testMethodRef(3.0, 4.0, Math::hypot));//Static + System.out.println(methodRefTest.testMethodRef(3.0, 4.0, Math::hypot)); // Static System.out.println(methodRefTest.testMethodRef(3.0, 4.0, MathUtils::normalizeAngle)); ObjectTypeTest obj = new ObjectTypeTest(); - //Ref. to an instance method of a particular a5object - System.out.println(methodRefTest.testMethodRef("John", "Doe", (p, q) -> obj.appendAndCapitalize(p, q))); + // Ref. to an instance method of a particular a5object + System.out.println( + methodRefTest.testMethodRef( + "John", "Doe", (p, q) -> obj.appendAndCapitalize(p, q))); System.out.println(methodRefTest.testMethodRef("John", "Doe", obj::appendAndCapitalize)); - System.out.println(methodRefTest.testMethodRef(3.0, 4.0, this::findHypotenous));//using this + System.out.println( + methodRefTest.testMethodRef(3.0, 4.0, this::findHypotenous)); // using this - //Ref. to an instance method of an arbitrary a5object of a particular type + // Ref. to an instance method of an arbitrary a5object of a particular type System.out.println(methodRefTest.testMethodRef("Jane", "Doe", (p, q) -> p.concat(q))); System.out.println(methodRefTest.testMethodRef("Jane", "Doe", String::concat)); } @@ -39,7 +41,7 @@ public void runMeFirst() { public void runMe() { System.out.println("*********************************************************"); List list = SampleData.getSimpleEmployees(); - //Ref. to an instance method of an arbitrary a5object of a particular typ + // Ref. to an instance method of an arbitrary a5object of a particular typ list.forEach(emp -> emp.printNameWithSalary()); System.out.println("--------------------------------------------------------"); Predicate notNull = Objects::nonNull; @@ -50,22 +52,25 @@ public void runMe() { Supplier> supplier = ArrayList::new; Transformer transformer = new Transformer(); - List simpleEmployeeList = list.stream() - //.filter(notNull.and(notEmptyName).and(notEmptySalary).and(notEmptyAge)) - .filter(((Predicate) Objects::nonNull)// use inline Predicate by casting the Predicate - .and(emp -> (null != emp.getName())) - .and(emp -> (null != emp.getSalary())) - .and(emp -> (null != emp.getAge())) - ) - //.map(emp -> transformer.getEmployee(emp)) - .map(transformer::getEmployee) - .sorted(Comparator.comparing(SimpleEmployee::getSalary).reversed()) - .collect(Collectors.toList()); + List simpleEmployeeList = + list.stream() + // .filter(notNull.and(notEmptyName).and(notEmptySalary).and(notEmptyAge)) + .filter( + ((Predicate) + Objects::nonNull) // use inline Predicate by + // casting the Predicate + .and(emp -> (null != emp.getName())) + .and(emp -> (null != emp.getSalary())) + .and(emp -> (null != emp.getAge()))) + // .map(emp -> transformer.getEmployee(emp)) + .map(transformer::getEmployee) + .sorted(Comparator.comparing(SimpleEmployee::getSalary).reversed()) + .collect(Collectors.toList()); - //Find diff between list.stream.sorted vs list.sort + // Find diff between list.stream.sorted vs list.sort simpleEmployeeList.forEach(SimpleEmployee::printMe); - //What is static factory + // What is static factory simpleEmployeeList.sort(Comparator.comparing(SimpleEmployee::getSalary).reversed()); } diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/SimpleEmployee.java b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/SimpleEmployee.java index 4bae598c..5f143958 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/SimpleEmployee.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/SimpleEmployee.java @@ -11,13 +11,11 @@ @NoArgsConstructor public class SimpleEmployee { private String name; - private String jobLevel;//level + exp + age + private String jobLevel; // level + exp + age private String salary; public void printMe() { - String sb = this.getName() + " " + - this.getJobLevel() + " " + - this.getSalary() + " "; + String sb = this.getName() + " " + this.getJobLevel() + " " + this.getSalary() + " "; System.out.println(sb); } diff --git a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Transformer.java b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Transformer.java index e7ce98fe..e5706623 100644 --- a/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Transformer.java +++ b/src/main/java/nitin/LambdaExpressions/methodRef/ex3/Transformer.java @@ -8,13 +8,13 @@ public class Transformer { public SimpleEmployee getEmployee(EmployeeSimple emp) { // EmployeeSimple -> Simpleemployee conversion - SimpleEmployee simpleEmployee = SimpleEmployee.builder() - .name(emp.getName()) - .jobLevel(emp.getLevel() + SPACE + - emp.getExperience() + SPACE + - emp.getAge()) - .salary(Double.toString(emp.getSalary())) - .build(); + SimpleEmployee simpleEmployee = + SimpleEmployee.builder() + .name(emp.getName()) + .jobLevel( + emp.getLevel() + SPACE + emp.getExperience() + SPACE + emp.getAge()) + .salary(Double.toString(emp.getSalary())) + .build(); return simpleEmployee; } } diff --git a/src/main/java/nitin/LambdaExpressions/zVariablesInLambdas.java b/src/main/java/nitin/LambdaExpressions/zVariablesInLambdas.java index b26f5b96..a1466a52 100644 --- a/src/main/java/nitin/LambdaExpressions/zVariablesInLambdas.java +++ b/src/main/java/nitin/LambdaExpressions/zVariablesInLambdas.java @@ -5,12 +5,11 @@ interface Gorilla { } /** - * Created by Nitin C on 3/3/2016. - * Lambda expression can access static variables, instance variables, - * effectively final variables and effectively Final local variables + * Created by Nitin C on 3/3/2016. Lambda expression can access static variables, instance + * variables, effectively final variables and effectively Final local variables */ public class zVariablesInLambdas { - String walk = "walk";//Instance Variable + String walk = "walk"; // Instance Variable public static void main(String[] args) { zVariablesInLambdas f = new zVariablesInLambdas(); @@ -24,7 +23,7 @@ void everyonePlay(boolean baby) { play(() -> walk); // uses instance variable in Lambda play(() -> baby ? "hitch a ride" : "run"); // using the method parameter - play(() -> approach);//Effectively Final Local Variable as approach is not re-assigned + play(() -> approach); // Effectively Final Local Variable as approach is not re-assigned } void play(Gorilla g) { diff --git a/src/main/java/nitin/PassByValuePrimitive.java b/src/main/java/nitin/PassByValuePrimitive.java index ec1ea12a..a5a7859d 100644 --- a/src/main/java/nitin/PassByValuePrimitive.java +++ b/src/main/java/nitin/PassByValuePrimitive.java @@ -6,7 +6,7 @@ public class PassByValuePrimitive { public static void main(String[] args) { - int a = 10;//All nums are primitive + int a = 10; // All nums are primitive modifyPrimitive(a); System.out.println(a); @@ -19,10 +19,13 @@ public static void main(String[] args) { modifyObject(b); System.out.println(b); - final Customer c = new Customer("John");//Final variable's reference can't be changed, the values inside the object can change - System.out.println(c);//Customer(name=John) + final Customer c = + new Customer( + "John"); // Final variable's reference can't be changed, the values inside + // the object can change + System.out.println(c); // Customer(name=John) modifyObject2(c); - System.out.println(c);//Customer(name=Jane) + System.out.println(c); // Customer(name=Jane) Faker.instance().name().fullName(); } @@ -33,7 +36,7 @@ private static void modifyObject2(Customer cust) { private static void modifyObject(Integer data) { Integer temp = data + 2; - data = temp * 2;// Creating a new Integer object and assigning it to data + data = temp * 2; // Creating a new Integer object and assigning it to data } private static void modifyPrimitive(int data) { diff --git a/src/main/java/nitin/Test.java b/src/main/java/nitin/Test.java index 5003e051..5d10ec5a 100644 --- a/src/main/java/nitin/Test.java +++ b/src/main/java/nitin/Test.java @@ -1,16 +1,7 @@ package nitin; -import com.google.common.collect.Lists; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.ToString; - -import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.stream.IntStream; public class Test { @@ -21,22 +12,27 @@ public static void main(String[] args) { } private static void runTest() { - CopyOnWriteArrayList list = new CopyOnWriteArrayList(Arrays.asList("A","b","C","d")); - - new Thread(() -> { - list.set(0,"A"); - list.set(1,"B"); - list.set(2,"C"); - list.set(3,"D"); - }).start(); - - new Thread(() -> { - list.set(0,"a"); - list.set(1,"b"); - list.set(2,"c"); - list.set(3,"d"); - }).start(); + CopyOnWriteArrayList list = + new CopyOnWriteArrayList(Arrays.asList("A", "b", "C", "d")); + + new Thread( + () -> { + list.set(0, "A"); + list.set(1, "B"); + list.set(2, "C"); + list.set(3, "D"); + }) + .start(); + + new Thread( + () -> { + list.set(0, "a"); + list.set(1, "b"); + list.set(2, "c"); + list.set(3, "d"); + }) + .start(); System.out.println(list); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/WalmartCodingTest.java b/src/main/java/nitin/WalmartCodingTest.java index 699f6481..19293cf3 100644 --- a/src/main/java/nitin/WalmartCodingTest.java +++ b/src/main/java/nitin/WalmartCodingTest.java @@ -39,7 +39,7 @@ public class WalmartCodingTest { public static void main(String[] argv) { - String[] words = new String[]{"cat", "baby", "dog", "bird", "car", "ax"}; + String[] words = new String[] {"cat", "baby", "dog", "bird", "car", "ax"}; String string1 = "tcabnihjs"; String string2 = "tbcanihjs"; String string3 = "baykkjl"; @@ -59,7 +59,7 @@ public static String find_embedded_word(String[] words, String str) { String ret = "None"; for (String word : words) { - boolean[] flag = new boolean[word.length()];//check syntax + boolean[] flag = new boolean[word.length()]; // check syntax Map map = getCharacterIntegerMap(str); for (int i = 0; i < word.length(); i++) { Character c = word.charAt(i); @@ -70,7 +70,7 @@ public static String find_embedded_word(String[] words, String str) { } if (allTrue(flag)) { - //ret = word; + // ret = word; return word; } } @@ -79,8 +79,7 @@ public static String find_embedded_word(String[] words, String str) { private static boolean allTrue(boolean[] flag) { for (int i = 0; i < flag.length; i++) { - if (!flag[i]) - return false; + if (!flag[i]) return false; } return true; } @@ -88,9 +87,9 @@ private static boolean allTrue(boolean[] flag) { private static Map getCharacterIntegerMap(String str) { Map map = new HashMap<>(); for (int i = 0; i < str.length(); i++) { - Character key = str.charAt(i);//Check for Autoboxing + Character key = str.charAt(i); // Check for Autoboxing map.put(key, map.getOrDefault(key, 0) + 1); } return map; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a1languageFundamentals/Car.java b/src/main/java/nitin/a1languageFundamentals/Car.java index 84c0f2e1..5bbe3a14 100644 --- a/src/main/java/nitin/a1languageFundamentals/Car.java +++ b/src/main/java/nitin/a1languageFundamentals/Car.java @@ -3,20 +3,16 @@ class LeftHandDrive { public static void m1() { System.out.println(" this is from static method of left hand drive class"); - } - public void horn() { - } + public void horn() {} - public void run() { - } + public void run() {} public void drivingMode() { System.out.println(" this left hand drive"); } - } class RightHandDrive extends LeftHandDrive { @@ -25,10 +21,10 @@ public static void m1() { System.out.println(" this is from static method of right hand drive class"); } -// public int drivingMode() { -// System.out.println(" this is right hand drive"); -// return 1; -// } + // public int drivingMode() { + // System.out.println(" this is right hand drive"); + // return 1; + // } } @@ -42,6 +38,5 @@ public static void main(String[] args) { ld1.drivingMode(); LeftHandDrive.m1(); LeftHandDrive.m1(); - } } diff --git a/src/main/java/nitin/a1languageFundamentals/IntelliJShortcuts.java b/src/main/java/nitin/a1languageFundamentals/IntelliJShortcuts.java index e4c076e5..076ba59d 100644 --- a/src/main/java/nitin/a1languageFundamentals/IntelliJShortcuts.java +++ b/src/main/java/nitin/a1languageFundamentals/IntelliJShortcuts.java @@ -10,12 +10,15 @@ public static void main(String[] args) throws IOException { FileReader in = new FileReader(new File(FILE)); BufferedReader bufferedReader = new BufferedReader(in); - bufferedReader.lines().forEach(str ->{ - String[] s = str.split(" "); - for (String string : s) { - System.out.println(string.toUpperCase()); - } - }); + bufferedReader + .lines() + .forEach( + str -> { + String[] s = str.split(" "); + for (String string : s) { + System.out.println(string.toUpperCase()); + } + }); bufferedReader.close(); } diff --git a/src/main/java/nitin/a1languageFundamentals/MainMethod.java b/src/main/java/nitin/a1languageFundamentals/MainMethod.java index 9cbd1140..21ee6a8f 100644 --- a/src/main/java/nitin/a1languageFundamentals/MainMethod.java +++ b/src/main/java/nitin/a1languageFundamentals/MainMethod.java @@ -1,15 +1,12 @@ package nitin.a1languageFundamentals; /** - * Created by Nitin Chaurasia on 12/28/16 at 1:19 AM. - * public : Call by JVM from anywhere - * static : JVM can call this even without existing Object - * void : main method can't return anything to JVM - * main : name of the method which is configured inside JVM (can be tweaked) - * String[] args : Array of command line String arguments - *

- * Can be declared with final, synchronized and strictfp - * Inheritance Concept is applicable + * Created by Nitin Chaurasia on 12/28/16 at 1:19 AM. public : Call by JVM from anywhere static : + * JVM can call this even without existing Object void : main method can't return anything to JVM + * main : name of the method which is configured inside JVM (can be tweaked) String[] args : Array + * of command line String arguments + * + *

Can be declared with final, synchronized and strictfp Inheritance Concept is applicable */ public class MainMethod { /*final*/ @@ -19,7 +16,7 @@ public class MainMethod { }*/ } -class ChildMain extends MainMethod {//method hiding +class ChildMain extends MainMethod { // method hiding /*static synchronized strictfp public void main(String[] args) { System.out.println("Child Testing"); diff --git a/src/main/java/nitin/a1languageFundamentals/MethodOverloading.java b/src/main/java/nitin/a1languageFundamentals/MethodOverloading.java index edf9e362..3f4529d5 100644 --- a/src/main/java/nitin/a1languageFundamentals/MethodOverloading.java +++ b/src/main/java/nitin/a1languageFundamentals/MethodOverloading.java @@ -19,5 +19,4 @@ public static void main(String[] args) { obj.music(); obj.music(2); } - } diff --git a/src/main/java/nitin/a1languageFundamentals/VarArg.java b/src/main/java/nitin/a1languageFundamentals/VarArg.java index 8ff5704a..5df4132f 100644 --- a/src/main/java/nitin/a1languageFundamentals/VarArg.java +++ b/src/main/java/nitin/a1languageFundamentals/VarArg.java @@ -1,17 +1,14 @@ package nitin.a1languageFundamentals; /** - * Created by Nitin Chaurasia on 12/28/16 at 1:04 AM. - * Declare a method with variable number of Arguments - * Since V1.5 - * m(int... x) & m(int x...) - ONLY TWO WAYS OF DECLARATION - * Only one Var-Arg parameter is allowed, also it should be last - m(String s, int... x) - * internally its implemented by 1D Array - * var-arg will get least priority. similar to default in Switch + * Created by Nitin Chaurasia on 12/28/16 at 1:04 AM. Declare a method with variable number of + * Arguments Since V1.5 m(int... x) & m(int x...) - ONLY TWO WAYS OF DECLARATION Only one + * Var-Arg parameter is allowed, also it should be last - m(String s, int... x) internally its + * implemented by 1D Array var-arg will get least priority. similar to default in Switch */ public class VarArg { public static void main(String[] args) { - varArgMethod(10);// non var agr gets priority + varArgMethod(10); // non var agr gets priority varArgMethod(10, 20); varArgMethod(10, 20, 30); varArgMultiple("Nitin", 10, 20); diff --git a/src/main/java/nitin/a1languageFundamentals/variables/PurposeNPositionOfDeclaration.java b/src/main/java/nitin/a1languageFundamentals/variables/PurposeNPositionOfDeclaration.java index 62c175cd..e63ea40f 100644 --- a/src/main/java/nitin/a1languageFundamentals/variables/PurposeNPositionOfDeclaration.java +++ b/src/main/java/nitin/a1languageFundamentals/variables/PurposeNPositionOfDeclaration.java @@ -1,27 +1,19 @@ package nitin.a1languageFundamentals.variables; /** - * Created by Nitin Chaurasia on 12/28/16 at 12:25 AM. - * 1. Instance Variable - * # Also known as Object level variables or attributes - * # For each a5object, a separate copy of variable is maintained - * # created at the time of a5object creation and destroyed at time of a5object destruction - * # declared within the class BUT outside any constructor, block or method - * # not required to perform initialization explicitly, JVM provides default values - * # scope: Same as Object - * 2. Static Variable - * # Stored in method area. Thus called class-level or fields - * # Values remains same between all objects. Single copy is created - * # Created at the time of Class Loading and destroyed at class unloading - * # since created at the time of loading, can access from both instance & static areas directly - * # declared with staticTest keyword, within the class BUT outside any constructor, block or method - * # not required to perform initialization explicitly, JVM provides default values - * # Scope : same as class - * 3. Local Variable - * # aka Stack variable or automatic variable - * # scope : Block level scope - * # need to initialize. Error: variable local might not have been initialized - * # Only applicable modifier is FINAL. private, public, protected, static Not allowed + * Created by Nitin Chaurasia on 12/28/16 at 12:25 AM. 1. Instance Variable # Also known as Object + * level variables or attributes # For each a5object, a separate copy of variable is maintained # + * created at the time of a5object creation and destroyed at time of a5object destruction # declared + * within the class BUT outside any constructor, block or method # not required to perform + * initialization explicitly, JVM provides default values # scope: Same as Object 2. Static Variable + * # Stored in method area. Thus called class-level or fields # Values remains same between all + * objects. Single copy is created # Created at the time of Class Loading and destroyed at class + * unloading # since created at the time of loading, can access from both instance & static + * areas directly # declared with staticTest keyword, within the class BUT outside any constructor, + * block or method # not required to perform initialization explicitly, JVM provides default values + * # Scope : same as class 3. Local Variable # aka Stack variable or automatic variable # scope : + * Block level scope # need to initialize. Error: variable local might not have been initialized # + * Only applicable modifier is FINAL. private, public, protected, static Not allowed */ public class PurposeNPositionOfDeclaration { /* Static Variables */ @@ -35,7 +27,8 @@ public class PurposeNPositionOfDeclaration { public static void main(String[] args) { PurposeNPositionOfDeclaration obj = new PurposeNPositionOfDeclaration(); - // since created at the time of loading, can access from both instance & static areas directly + // since created at the time of loading, can access from both instance & static areas + // directly System.out.println(s1); // Local Variable @@ -46,7 +39,8 @@ public static void main(String[] args) { } public void m() { - // since created at the time of loading, can access from both instance & static areas directly + // since created at the time of loading, can access from both instance & static areas + // directly System.out.println(s2); } } diff --git a/src/main/java/nitin/a1languageFundamentals/variables/ValRepresented.java b/src/main/java/nitin/a1languageFundamentals/variables/ValRepresented.java index b0a0bcdb..2196df05 100644 --- a/src/main/java/nitin/a1languageFundamentals/variables/ValRepresented.java +++ b/src/main/java/nitin/a1languageFundamentals/variables/ValRepresented.java @@ -1,15 +1,13 @@ package nitin.a1languageFundamentals.variables; /** - * Created by Nitin Chaurasia on 12/28/16 at 12:22 AM. - * Primitive Variables : used to represent primitive variables - * Reference Variables : used to refer Object + * Created by Nitin Chaurasia on 12/28/16 at 12:22 AM. Primitive Variables : used to represent + * primitive variables Reference Variables : used to refer Object */ public class ValRepresented { public static void main(String[] args) { int a = 10; // Primitive type Object obj = new Object(); // Reference Type - } } diff --git a/src/main/java/nitin/a2operators/O10AssignmentOperators.java b/src/main/java/nitin/a2operators/O10AssignmentOperators.java index 55f1546c..26eb920c 100644 --- a/src/main/java/nitin/a2operators/O10AssignmentOperators.java +++ b/src/main/java/nitin/a2operators/O10AssignmentOperators.java @@ -1,11 +1,8 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/28/16 at 11:10 PM. - * Three Types of Assignment Operators - * 1. Simple Assignment Operators - * 2. Chained Assignment Operators - * 3. Compound Assignment Operators + * Created by Nitin Chaurasia on 12/28/16 at 11:10 PM. Three Types of Assignment Operators 1. Simple + * Assignment Operators 2. Chained Assignment Operators 3. Compound Assignment Operators */ public class O10AssignmentOperators { public static void main(String[] args) { @@ -25,6 +22,5 @@ public static void main(String[] args) { // Required type casting is automatic. - } } diff --git a/src/main/java/nitin/a2operators/O11ConditionalTernaryOperator.java b/src/main/java/nitin/a2operators/O11ConditionalTernaryOperator.java index 80796759..2b898b62 100644 --- a/src/main/java/nitin/a2operators/O11ConditionalTernaryOperator.java +++ b/src/main/java/nitin/a2operators/O11ConditionalTernaryOperator.java @@ -1,9 +1,6 @@ package nitin.a2operators; -/** - * Created by Nitin Chaurasia on 12/28/16 at 11:18 PM. - * Only Ternary Operator in Java - */ +/** Created by Nitin Chaurasia on 12/28/16 at 11:18 PM. Only Ternary Operator in Java */ public class O11ConditionalTernaryOperator { public static void main(String[] args) { int a = 10, b = 20; @@ -20,7 +17,5 @@ public static void main(String[] args) { // Nesting of Conditional Operators x = (a > 50) ? 777 : ((b > 100) ? 888 : 999); System.out.println(x); - } - } diff --git a/src/main/java/nitin/a2operators/O12OperatorPrecedence.java b/src/main/java/nitin/a2operators/O12OperatorPrecedence.java index aecb4793..86c281d9 100644 --- a/src/main/java/nitin/a2operators/O12OperatorPrecedence.java +++ b/src/main/java/nitin/a2operators/O12OperatorPrecedence.java @@ -1,7 +1,4 @@ package nitin.a2operators; -/** - * Created by Nitin Chaurasia on 12/28/16 at 11:26 PM. - */ -public class O12OperatorPrecedence { -} +/** Created by Nitin Chaurasia on 12/28/16 at 11:26 PM. */ +public class O12OperatorPrecedence {} diff --git a/src/main/java/nitin/a2operators/O1UnaryIncrementDecrement.java b/src/main/java/nitin/a2operators/O1UnaryIncrementDecrement.java index 7acd9ba2..48820a59 100644 --- a/src/main/java/nitin/a2operators/O1UnaryIncrementDecrement.java +++ b/src/main/java/nitin/a2operators/O1UnaryIncrementDecrement.java @@ -1,36 +1,34 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/28/16 at 8:23 PM. - * Pre-Increment ++x - * Post-Increment x++ - * Pre-Decrement --x - * Post-Decrement x++ - *

- * Nesting not possible ++(--x) -> Compile time error - * Can be applied to all primitive type except boolean + * Created by Nitin Chaurasia on 12/28/16 at 8:23 PM. Pre-Increment ++x Post-Increment x++ + * Pre-Decrement --x Post-Decrement x++ + * + *

Nesting not possible ++(--x) -> Compile time error Can be applied to all primitive type except + * boolean */ public class O1UnaryIncrementDecrement { public static void main(String[] args) { int x = 5, y = -99999; y = x++; // First assign val of x to y, and then increment - System.out.println("x = " + x + " y = " + y);//x = 6 y = 5 + System.out.println("x = " + x + " y = " + y); // x = 6 y = 5 - x = 5; //reset the value of x - y = ++x;// First increment x, then assign it to y - System.out.println("x = " + x + " y = " + y);//x = 6 y = 6 + x = 5; // reset the value of x + y = ++x; // First increment x, then assign it to y + System.out.println("x = " + x + " y = " + y); // x = 6 y = 6 - x = 5; //reset the value of x - y = x--;// First assign x to y, then increment it - System.out.println("x = " + x + " y = " + y);//x = 4 y = 5 + x = 5; // reset the value of x + y = x--; // First assign x to y, then increment it + System.out.println("x = " + x + " y = " + y); // x = 4 y = 5 - x = 5; //reset the value of x - y = --x;// First decrement x, then assign it to y - System.out.println("x = " + x + " y = " + y);//x = 4 y = 4 + x = 5; // reset the value of x + y = --x; // First decrement x, then assign it to y + System.out.println("x = " + x + " y = " + y); // x = 4 y = 4 - // Can be applied to all primitive type except booleanCan be applied to all primitive type except boolean + // Can be applied to all primitive type except booleanCan be applied to all primitive type + // except boolean char ch = 'a'; - System.out.println(++ch);// b, Increment ch and then print + System.out.println(++ch); // b, Increment ch and then print System.out.println(0 / 0.0); // Not a Number int counter = 0; diff --git a/src/main/java/nitin/a2operators/O2ArithmaticOperators.java b/src/main/java/nitin/a2operators/O2ArithmaticOperators.java index bf5744f9..8804f494 100644 --- a/src/main/java/nitin/a2operators/O2ArithmaticOperators.java +++ b/src/main/java/nitin/a2operators/O2ArithmaticOperators.java @@ -1,8 +1,6 @@ package nitin.a2operators; -/** - * Created by Nitin Chaurasia on 12/27/16 at 1:01 AM. - */ +/** Created by Nitin Chaurasia on 12/27/16 at 1:01 AM. */ public class O2ArithmaticOperators { public static void main(String[] args) { System.out.println(9 / 3); // Outputs 3 diff --git a/src/main/java/nitin/a2operators/O3StringConcatenation.java b/src/main/java/nitin/a2operators/O3StringConcatenation.java index 6833e65c..c76b0069 100644 --- a/src/main/java/nitin/a2operators/O3StringConcatenation.java +++ b/src/main/java/nitin/a2operators/O3StringConcatenation.java @@ -1,8 +1,6 @@ package nitin.a2operators; -/** - * Created by Nitin Chaurasia on 12/28/16 at 9:46 PM. - */ +/** Created by Nitin Chaurasia on 12/28/16 at 9:46 PM. */ public class O3StringConcatenation { public static void main(String[] args) { String str = "Nitin"; @@ -10,9 +8,9 @@ public static void main(String[] args) { // Concatenation in action // Before the String, the arithmatic operations gets performed. - System.out.println(a + b + c + str);//60Nitin - System.out.println(a + str + b + c);//10Nitin2030 - System.out.println(a + b + str + c);//30Nitin30 - System.out.println(str + a + b + c);//Nitin102030 + System.out.println(a + b + c + str); // 60Nitin + System.out.println(a + str + b + c); // 10Nitin2030 + System.out.println(a + b + str + c); // 30Nitin30 + System.out.println(str + a + b + c); // Nitin102030 } } diff --git a/src/main/java/nitin/a2operators/O4RelationalOperators.java b/src/main/java/nitin/a2operators/O4RelationalOperators.java index 2aeafdcb..4d0ce56e 100644 --- a/src/main/java/nitin/a2operators/O4RelationalOperators.java +++ b/src/main/java/nitin/a2operators/O4RelationalOperators.java @@ -1,8 +1,6 @@ package nitin.a2operators; -/** - * Created by Nitin Chaurasia on 12/28/16 at 9:50 PM. - */ +/** Created by Nitin Chaurasia on 12/28/16 at 9:50 PM. */ public class O4RelationalOperators { public static void main(String[] args) { System.out.println(10 > 20); diff --git a/src/main/java/nitin/a2operators/O5EqualityOperators.java b/src/main/java/nitin/a2operators/O5EqualityOperators.java index 3c58b93e..5d943a26 100644 --- a/src/main/java/nitin/a2operators/O5EqualityOperators.java +++ b/src/main/java/nitin/a2operators/O5EqualityOperators.java @@ -1,17 +1,16 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/28/16 at 9:55 PM. - * == equal to (if two objects are same, then its true) - * != not equal to + * Created by Nitin Chaurasia on 12/28/16 at 9:55 PM. == equal to (if two objects are same, then its + * true) != not equal to */ public class O5EqualityOperators { public static void main(String[] args) { String s1 = "Nitin"; String s2 = "Nitin"; - //Reference Testing - System.out.println(s1 == s2);// False as the two objects are different - System.out.println(s1.equals(s2));// String equality testing + // Reference Testing + System.out.println(s1 == s2); // False as the two objects are different + System.out.println(s1.equals(s2)); // String equality testing Object o1 = new Object(); Thread t1 = new Thread(); @@ -22,8 +21,7 @@ public static void main(String[] args) { System.out.println(t1 == o1); System.out.println(o1 == t1); - System.out.println(t1 == null);// False always as an obj is pointing to a memory location. - System.out.println(null == null);// Always true; - + System.out.println(t1 == null); // False always as an obj is pointing to a memory location. + System.out.println(null == null); // Always true; } } diff --git a/src/main/java/nitin/a2operators/O6instanceof.java b/src/main/java/nitin/a2operators/O6instanceof.java index 2986399e..36419106 100644 --- a/src/main/java/nitin/a2operators/O6instanceof.java +++ b/src/main/java/nitin/a2operators/O6instanceof.java @@ -1,16 +1,15 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/28/16 at 10:03 PM. - * r instanceof c : reference is an instance of class.interface + * Created by Nitin Chaurasia on 12/28/16 at 10:03 PM. r instanceof c : reference is an instance of + * class.interface */ public class O6instanceof { public static void main(String[] args) { Short s = 15; - System.out.println(s instanceof Short);// true - System.out.println(s instanceof Number);// true - + System.out.println(s instanceof Short); // true + System.out.println(s instanceof Number); // true } } diff --git a/src/main/java/nitin/a2operators/O7BitwiseOperator.java b/src/main/java/nitin/a2operators/O7BitwiseOperator.java index 08b5e615..434cf45d 100644 --- a/src/main/java/nitin/a2operators/O7BitwiseOperator.java +++ b/src/main/java/nitin/a2operators/O7BitwiseOperator.java @@ -1,12 +1,10 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/28/16 at 10:18 PM. - * & -> AND : If both operands are true, result is True - * | -> OR : if atleast 1 operand is T, result is True - * ^ -> XOR : if both operands are different, result is True - * ~ -> Complement : can't be applied to boolean - * ! -> Boolean Complement + * Created by Nitin Chaurasia on 12/28/16 at 10:18 PM. & -> AND : If both operands are true, + * result is True | -> OR : if atleast 1 operand is T, result is True ^ -> XOR : if both operands + * are different, result is True ~ -> Complement : can't be applied to boolean ! -> Boolean + * Complement */ public class O7BitwiseOperator { @@ -16,12 +14,12 @@ public static void main(String[] args) { System.out.println(true); System.out.println(false); // System.out.println(~true);// cant be applied - System.out.println(false);// False + System.out.println(false); // False // Mathematical manipulations - System.out.println(4 & 5);//100 & 101 = 100 - System.out.println(4 | 5);//100 | 101 = 101 - System.out.println(4 ^ 5);//100 ^ 101 = 001 - System.out.println(~4);// minus 4 + System.out.println(4 & 5); // 100 & 101 = 100 + System.out.println(4 | 5); // 100 | 101 = 101 + System.out.println(4 ^ 5); // 100 ^ 101 = 001 + System.out.println(~4); // minus 4 } } diff --git a/src/main/java/nitin/a2operators/O8ShortCircuit.java b/src/main/java/nitin/a2operators/O8ShortCircuit.java index 84bfacbf..6bcf5d7b 100644 --- a/src/main/java/nitin/a2operators/O8ShortCircuit.java +++ b/src/main/java/nitin/a2operators/O8ShortCircuit.java @@ -1,30 +1,27 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/28/16 at 10:32 PM. - * && and || : just to improve the performance of the system. - * Applicable only for Boolean type. - * second operand evaluation is optional + * Created by Nitin Chaurasia on 12/28/16 at 10:32 PM. && and || : just to improve the + * performance of the system. Applicable only for Boolean type. second operand evaluation is + * optional */ public class O8ShortCircuit { public static void main(String[] args) { int[] a = {1, 2, 3, 4}; if (a[1] > a[0] | a[3] > a[2]) // both operands are checked - System.out.println("success"); + System.out.println("success"); if (a[1] > a[0] && a[3] > a[2]) // only necessary operands are checked - System.out.println("success"); + System.out.println("success"); int x = 10; if ((++x < 10) && (x / 0 > 10)) // the Arithmatic Exception is not even evaluated - System.out.println("inside If"); - else - System.out.println("Inside Else"); + System.out.println("inside If"); + else System.out.println("Inside Else"); if ((++x < 10) & (x / 0 > 10)) // the Arithmatic Exception is thrown as x/0 is checked - System.out.println("inside If"); - else - System.out.println("Inside Else"); + System.out.println("inside If"); + else System.out.println("Inside Else"); } } diff --git a/src/main/java/nitin/a2operators/O9TypeCastingNumericPromotion.java b/src/main/java/nitin/a2operators/O9TypeCastingNumericPromotion.java index de4739b9..620a8050 100644 --- a/src/main/java/nitin/a2operators/O9TypeCastingNumericPromotion.java +++ b/src/main/java/nitin/a2operators/O9TypeCastingNumericPromotion.java @@ -1,18 +1,12 @@ package nitin.a2operators; /** - * Created by Nitin Chaurasia on 12/27/16 at 1:03 AM. - * 2 Types of Numeric Type Casting - * Implicit Type Casting : - * Also known as WIDENING OR UP-CASTING - * Compiler is responsible for typecasting. - * Happens when assigning smaller data type value to a bigger data type variable - * No loss of information - * Explicit Type Casting - * Also known as NARROWING OR DOWN-CASTING - * Programmer is responsible - * Happens when assigning bigger data type value to a smaller data type variable - * Chance of loss of precision/info. + * Created by Nitin Chaurasia on 12/27/16 at 1:03 AM. 2 Types of Numeric Type Casting Implicit Type + * Casting : Also known as WIDENING OR UP-CASTING Compiler is responsible for typecasting. Happens + * when assigning smaller data type value to a bigger data type variable No loss of information + * Explicit Type Casting Also known as NARROWING OR DOWN-CASTING Programmer is responsible Happens + * when assigning bigger data type value to a smaller data type variable Chance of loss of + * precision/info. */ public class O9TypeCastingNumericPromotion { public static void main(String[] args) { @@ -20,11 +14,11 @@ public static void main(String[] args) { /***** Implicit Type Casting *****/ // byte(1B) -> short(2B) -> int(4B) -> long(4B) -> float(4B) -> double(8B) double d = 10; - System.out.println(d);//compiler converts int 10, to double automatically + System.out.println(d); // compiler converts int 10, to double automatically // char(2B) -> int(4B) -> long(4B) -> float(4B) -> double(8B) int i = 'a'; - System.out.println(i);//compiler converts char to int automatically + System.out.println(i); // compiler converts char to int automatically /***** explicit Type Casting *****/ // byte(1B) <- short(2B) <- int(4B) <- long(4B) <- float(4B) <- double(8B) @@ -33,15 +27,13 @@ public static void main(String[] args) { int j = 150; short s = (short) j; - System.out.println(s);//150 + System.out.println(s); // 150 // Double : digits after the decimal points are lost double x = 130.456; int y = (int) x; byte z = (byte) x; - System.out.println(y);//130 - System.out.println(z);//-126 - - + System.out.println(y); // 130 + System.out.println(z); // -126 } } diff --git a/src/main/java/nitin/a3accessModifiers/D0.java b/src/main/java/nitin/a3accessModifiers/D0.java index bb0c392c..6dc9978e 100644 --- a/src/main/java/nitin/a3accessModifiers/D0.java +++ b/src/main/java/nitin/a3accessModifiers/D0.java @@ -1,8 +1,6 @@ package nitin.a3accessModifiers; -/** - * Created by Nitin Chaurasia on 12/29/16 at 12:18 AM. - */ +/** Created by Nitin Chaurasia on 12/29/16 at 12:18 AM. */ class D1ClassFileNAme { // If nothing is specified than class is default ( // allowed: public ,, final, abstract, strictfp) diff --git a/src/main/java/nitin/a3accessModifiers/D1MultipleClassInaFile.java b/src/main/java/nitin/a3accessModifiers/D1MultipleClassInaFile.java index 2856621c..ee8e7043 100644 --- a/src/main/java/nitin/a3accessModifiers/D1MultipleClassInaFile.java +++ b/src/main/java/nitin/a3accessModifiers/D1MultipleClassInaFile.java @@ -1,11 +1,9 @@ package nitin.a3accessModifiers; /** - * Created by Nitin C on 11/25/2015. - * If there is no public class, then we can use any name as Java Source file name. - * Recommended is one class Filename per file + * Created by Nitin C on 11/25/2015. If there is no public class, then we can use any name as Java + * Source file name. Recommended is one class Filename per file */ - abstract class X { public abstract void check(); } @@ -13,9 +11,7 @@ abstract class X { class Y extends X { @Override - public void check() { - - } + public void check() {} } class MultipleClassInaFile { diff --git a/src/main/java/nitin/a3accessModifiers/D2ImportStatements.java b/src/main/java/nitin/a3accessModifiers/D2ImportStatements.java index f63ee2d9..ed368366 100644 --- a/src/main/java/nitin/a3accessModifiers/D2ImportStatements.java +++ b/src/main/java/nitin/a3accessModifiers/D2ImportStatements.java @@ -1,16 +1,15 @@ package nitin.a3accessModifiers; /** - * Created by Nitin Chaurasia on 12/29/16 at 12:24 AM. - * Explicit Class Import : all classes are written, highly recommended - * Implicit Class import : not recommended. (import java.util.*) - *

- * Dynamic Loading OR Load On Demand OR Load On Fly - *

- * Static Import : From Java 1.5, Static imports are also possible. But it reduces readability + * Created by Nitin Chaurasia on 12/29/16 at 12:24 AM. Explicit Class Import : all classes are + * written, highly recommended Implicit Class import : not recommended. (import java.util.*) + * + *

Dynamic Loading OR Load On Demand OR Load On Fly + * + *

Static Import : From Java 1.5, Static imports are also possible. But it reduces readability */ -//Static Import +// Static Import import static java.lang.Float.MAX_VALUE; import static java.lang.Math.*; @@ -18,13 +17,14 @@ public class D2ImportStatements { public static void main(String[] args) { - //Static Imports (not recommended ) + // Static Imports (not recommended ) System.out.println(sqrt(9)); System.out.println(random() * 10); System.out.println(max(10, 23)); // Ambiguity - System.out.println(MAX_VALUE); //Error: reference to MAX_VALUE is ambiguous - //both variable MAX_VALUE in java.lang.Float and variable MAX_VALUE in java.lang.Integer match + System.out.println(MAX_VALUE); // Error: reference to MAX_VALUE is ambiguous + // both variable MAX_VALUE in java.lang.Float and variable MAX_VALUE in java.lang.Integer + // match } } diff --git a/src/main/java/nitin/a3accessModifiers/D3ClassModifiers.java b/src/main/java/nitin/a3accessModifiers/D3ClassModifiers.java index 19e340ee..0a395358 100644 --- a/src/main/java/nitin/a3accessModifiers/D3ClassModifiers.java +++ b/src/main/java/nitin/a3accessModifiers/D3ClassModifiers.java @@ -7,7 +7,7 @@ * Applicable modifier for Inner class * public ,"", final, abstract, strictfp, private, protected, static */ -//private class D3ClassModifiers { //Error: modifier private not allowed here +// private class D3ClassModifiers { //Error: modifier private not allowed here public class D3ClassModifiers { public static void main(String[] args) { diff --git a/src/main/java/nitin/a3accessModifiers/M1Final.java b/src/main/java/nitin/a3accessModifiers/M1Final.java index f08f0254..2fe2f40d 100644 --- a/src/main/java/nitin/a3accessModifiers/M1Final.java +++ b/src/main/java/nitin/a3accessModifiers/M1Final.java @@ -1,8 +1,8 @@ package nitin.a3accessModifiers; /** - * Created by Nitin Chaurasia on 12/29/16 at 12:51 AM. - * Final is applicable for classes, methods and variables + * Created by Nitin Chaurasia on 12/29/16 at 12:51 AM. Final is applicable for classes, methods and + * variables */ public class M1Final { @@ -34,5 +34,4 @@ public String getM1Final() { public void setM1Final(String s) { finalString = s; } - } diff --git a/src/main/java/nitin/a3accessModifiers/M2Abstract.java b/src/main/java/nitin/a3accessModifiers/M2Abstract.java index a8059081..252d47b9 100644 --- a/src/main/java/nitin/a3accessModifiers/M2Abstract.java +++ b/src/main/java/nitin/a3accessModifiers/M2Abstract.java @@ -1,8 +1,6 @@ package nitin.a3accessModifiers; -/** - * Created by Nitin Chaurasia on 12/29/16 at 12:55 AM. - */ +/** Created by Nitin Chaurasia on 12/29/16 at 12:55 AM. */ public abstract class M2Abstract { // Allowed only on Classes and Methods, not on variables @@ -10,11 +8,13 @@ public abstract class M2Abstract { // Abstract method just has declaraton, thus ends in ; // Any class extending abstract class, has to provide the implementation. - // abstract call cannot be instantiated. Thus if we don't want a class to be instantiated, declare it as abstract. + // abstract call cannot be instantiated. Thus if we don't want a class to be instantiated, + // declare it as abstract. // If a class has at least one abstract method, The class has to be declared as abstract. - // even if there are no abstract methods in a class, we can still declare it as abstract. eg. HTTPServlet + // even if there are no abstract methods in a class, we can still declare it as abstract. eg. + // HTTPServlet // Final class cant have abstract method public abstract void method(); diff --git a/src/main/java/nitin/a3accessModifiers/M3Strictfp.java b/src/main/java/nitin/a3accessModifiers/M3Strictfp.java index b389262f..858f5638 100644 --- a/src/main/java/nitin/a3accessModifiers/M3Strictfp.java +++ b/src/main/java/nitin/a3accessModifiers/M3Strictfp.java @@ -1,13 +1,12 @@ package nitin.a3accessModifiers; -/** - * Created by Nitin Chaurasia on 12/29/16 at 1:04 AM. - */ +/** Created by Nitin Chaurasia on 12/29/16 at 1:04 AM. */ public class M3Strictfp { // Applicable for Class and Method, but not for the Variables - // Method as strictfp : all floating point calculations in that method has to follow IEEE 754 Standard so that + // Method as strictfp : all floating point calculations in that method has to follow IEEE 754 + // Standard so that // we get platform independent results. // Class as strictfp : every concrete method in that class follow IEEE 754 standards. diff --git a/src/main/java/nitin/a3accessModifiers/staticTest/StaticInitializationBlocks.java b/src/main/java/nitin/a3accessModifiers/staticTest/StaticInitializationBlocks.java index 9955f59d..8730982d 100644 --- a/src/main/java/nitin/a3accessModifiers/staticTest/StaticInitializationBlocks.java +++ b/src/main/java/nitin/a3accessModifiers/staticTest/StaticInitializationBlocks.java @@ -1,9 +1,6 @@ package nitin.a3accessModifiers.staticTest; -/** - * Created by Nitin C on 11/25/2015. - */ - +/** Created by Nitin C on 11/25/2015. */ class Car1 { static int numberofobjects; @@ -33,11 +30,10 @@ public Car1() { numberofobjects++; System.out.println("this is from default constructor of class car"); - } public void x() { -// System.out.println(numberofobjects); + // System.out.println(numberofobjects); } } @@ -47,19 +43,17 @@ public class StaticInitializationBlocks { public static void main(String[] args) { Car1 c1 = new Car1(); Car1 c2 = new Car1(); - //System.out.println(c1.numberofobjects); + // System.out.println(c1.numberofobjects); Car1 c3 = new Car1(); - System.out.println("************************************ PROGRAM STARTS HERE *******************************************"); + System.out.println( + "************************************ PROGRAM STARTS HERE *******************************************"); Car1.numberofwheels = 4; - c1.enginecapacity = 1500;//non static var, related to each a5object + c1.enginecapacity = 1500; // non static var, related to each a5object System.out.println(Car1.numberofwheels); System.out.println(Car1.numberofwheels); System.out.println(c2.enginecapacity); System.out.println(c3.enginecapacity); System.out.println(c1.enginecapacity); - - } - } diff --git a/src/main/java/nitin/a4flowControl/F1Break.java b/src/main/java/nitin/a4flowControl/F1Break.java index fe32f562..b80be4af 100644 --- a/src/main/java/nitin/a4flowControl/F1Break.java +++ b/src/main/java/nitin/a4flowControl/F1Break.java @@ -3,22 +3,19 @@ import java.util.Arrays; import java.util.List; -/** - * Created by Nitin Chaurasia on 12/27/16 at 1:13 AM. - */ +/** Created by Nitin Chaurasia on 12/27/16 at 1:13 AM. */ public class F1Break { public static void main(String[] args) { List a = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); for (int i = 0; i < a.size(); i++) { - /* for (int j = 0; j < i; j++) { + /* for (int j = 0; j < i; j++) { System.out.println("Inside j loop : " + j); }*/ System.out.print(i + "\t"); - //Breaking out of the loop and performing prints - if (i == 5) - break; + // Breaking out of the loop and performing prints + if (i == 5) break; System.out.println("After Break : " + i); } System.out.println("After for loop"); diff --git a/src/main/java/nitin/a4flowControl/F1Continue.java b/src/main/java/nitin/a4flowControl/F1Continue.java index 988a4837..f1239c9d 100644 --- a/src/main/java/nitin/a4flowControl/F1Continue.java +++ b/src/main/java/nitin/a4flowControl/F1Continue.java @@ -1,7 +1,4 @@ package nitin.a4flowControl; -/** - * Created by Nitin Chaurasia on 12/27/16 at 1:13 AM. - */ -public class F1Continue { -} +/** Created by Nitin Chaurasia on 12/27/16 at 1:13 AM. */ +public class F1Continue {} diff --git a/src/main/java/nitin/a4flowControl/F1switch.java b/src/main/java/nitin/a4flowControl/F1switch.java index c89677bd..f26acc65 100644 --- a/src/main/java/nitin/a4flowControl/F1switch.java +++ b/src/main/java/nitin/a4flowControl/F1switch.java @@ -3,11 +3,9 @@ import java.util.Scanner; /** - * Created by Nitin Chaurasia on 12/27/16 at 1:13 AM. - * Allowed Dataypes - * Until Java 1.4 : byte, short, int, char - * From Java 1.5 : Corresponding Wrapper Classes & Enum are also allowed - * From Java 1.7 : String is also allowed + * Created by Nitin Chaurasia on 12/27/16 at 1:13 AM. Allowed Dataypes Until Java 1.4 : byte, short, + * int, char From Java 1.5 : Corresponding Wrapper Classes & Enum are also allowed From Java 1.7 + * : String is also allowed */ public class F1switch { public static void main(String[] args) { @@ -41,6 +39,6 @@ public static void main(String[] args) { System.out.println("Invalid choice = " + choice); } } - //System.out.println("Out of loop"); + // System.out.println("Out of loop"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a4flowControl/SwitchExpressions.java b/src/main/java/nitin/a4flowControl/SwitchExpressions.java index 0b377220..90a562c8 100644 --- a/src/main/java/nitin/a4flowControl/SwitchExpressions.java +++ b/src/main/java/nitin/a4flowControl/SwitchExpressions.java @@ -3,25 +3,24 @@ import java.util.Arrays; import java.util.List; -/** - * Created by Nitin Chaurasia on Friday, June/05/2020 at 2:52 AM - */ - +/** Created by Nitin Chaurasia on Friday, June/05/2020 at 2:52 AM */ public class SwitchExpressions { - final static List ANEMIA_LABS = Arrays.asList( - "HEMOGLOBIN",//Sort Order based on Array Index. 0 = lowest, array.size()-1 = biggest - "IRON SATURATION", - "FERRITIN", - "IRON", - "MCV", - "RETIC COUNT", - "ABSOLUTE RETIC COUNT", - "WBC"); + static final List ANEMIA_LABS = + Arrays.asList( + "HEMOGLOBIN", // Sort Order based on Array Index. 0 = lowest, array.size()-1 = + // biggest + "IRON SATURATION", + "FERRITIN", + "IRON", + "MCV", + "RETIC COUNT", + "ABSOLUTE RETIC COUNT", + "WBC"); public static void main(String[] args) { String day = "sun"; - //System.out.println(getString(day)); + // System.out.println(getString(day)); for (String lab : ANEMIA_LABS) { System.out.println(getString2(lab)); @@ -29,31 +28,29 @@ public static void main(String[] args) { } private static String getString(String day) { - String result = switch (day) { - case "M", "W", "F" -> "Monday Wednesday Friday"; - case "Tuesday", "TH", "Sat" -> "Tuesday Thursday Saturday"; - default -> { - if (day.isEmpty()) - yield "Please insert a valid day"; - else - yield "Sunday"; - } - }; + String result = + switch (day) { + case "M", "W", "F" -> "Monday Wednesday Friday"; + case "Tuesday", "TH", "Sat" -> "Tuesday Thursday Saturday"; + default -> { + if (day.isEmpty()) yield "Please insert a valid day"; + else yield "Sunday"; + } + }; return result; } private static String getString2(String str) { - String result = switch (str) { - case "IRON" -> "Iron Lab"; - case "FERRITIN" -> "FERRITIN Lab"; - default -> { - if (ANEMIA_LABS.isEmpty()) - yield "Please insert a valid day"; - else - yield "Invalid Labs"; - } - }; + String result = + switch (str) { + case "IRON" -> "Iron Lab"; + case "FERRITIN" -> "FERRITIN Lab"; + default -> { + if (ANEMIA_LABS.isEmpty()) yield "Please insert a valid day"; + else yield "Invalid Labs"; + } + }; return result; } } diff --git a/src/main/java/nitin/a4flowControl/TernaryOperator.java b/src/main/java/nitin/a4flowControl/TernaryOperator.java index fa94ff16..5caa0f30 100644 --- a/src/main/java/nitin/a4flowControl/TernaryOperator.java +++ b/src/main/java/nitin/a4flowControl/TernaryOperator.java @@ -1,8 +1,6 @@ package nitin.a4flowControl; -/** - * Created by nitin.chaurasia on 10/14/2017. - */ +/** Created by nitin.chaurasia on 10/14/2017. */ public class TernaryOperator { public static void main(String[] args) { diff --git a/src/main/java/nitin/a5object/AnimalDoctor.java b/src/main/java/nitin/a5object/AnimalDoctor.java index dd108172..f27bc193 100644 --- a/src/main/java/nitin/a5object/AnimalDoctor.java +++ b/src/main/java/nitin/a5object/AnimalDoctor.java @@ -39,5 +39,4 @@ public void checkAnimals(Animal[] animals) { a.checkup(); } } - } diff --git a/src/main/java/nitin/a5object/HashCode/HashCodeTest.java b/src/main/java/nitin/a5object/HashCode/HashCodeTest.java index ce5e3a3b..abcf0afc 100644 --- a/src/main/java/nitin/a5object/HashCode/HashCodeTest.java +++ b/src/main/java/nitin/a5object/HashCode/HashCodeTest.java @@ -2,18 +2,18 @@ /** * Created by Nitin Chaurasia on 3/4/16 at 11:51 PM. - *

- * 1. Within a same program, the result of hashCode must not change. DO NOT INCLUDE VARIABLES THAT CHANGE during - * program execution (for example currentTimestamp for hashCode to calculate hashcode) - *

- * 2. If equals on two a5object return true, their hashCode must be Same. => to be two objects to be equal, - * their hasCode must match. Like 2 String with same text refer to the same memory location - *

- * 3. if equals returns false, hashCode need not be different. Hashcode results do not need to be unique when called on - * unequal objects + * + *

1. Within a same program, the result of hashCode must not change. DO NOT INCLUDE VARIABLES + * THAT CHANGE during program execution (for example currentTimestamp for hashCode to calculate + * hashcode) + * + *

2. If equals on two a5object return true, their hashCode must be Same. => to be two objects to + * be equal, their hasCode must match. Like 2 String with same text refer to the same memory + * location + * + *

3. if equals returns false, hashCode need not be different. Hashcode results do not need to be + * unique when called on unequal objects */ public class HashCodeTest { - public static void main(String[] args) { - - } + public static void main(String[] args) {} } diff --git a/src/main/java/nitin/a5object/O1UsingNew.java b/src/main/java/nitin/a5object/O1UsingNew.java index 71209197..c7d33d27 100644 --- a/src/main/java/nitin/a5object/O1UsingNew.java +++ b/src/main/java/nitin/a5object/O1UsingNew.java @@ -1,8 +1,6 @@ package nitin.a5object; -/** - * Created by nitin.chaurasia on 3/3/2017. - */ +/** Created by nitin.chaurasia on 3/3/2017. */ public class O1UsingNew { public static void main(String[] args) { @@ -26,6 +24,5 @@ class Employee { public void display() { System.out.println(id + " " + name); - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a5object/O2UsingClone.java b/src/main/java/nitin/a5object/O2UsingClone.java index a45a23df..db7050c2 100644 --- a/src/main/java/nitin/a5object/O2UsingClone.java +++ b/src/main/java/nitin/a5object/O2UsingClone.java @@ -1,8 +1,6 @@ package nitin.a5object; -/** - * Created by nitin.chaurasia on 3/3/2017. - */ +/** Created by nitin.chaurasia on 3/3/2017. */ public class O2UsingClone { public static void main(String[] args) { @@ -24,7 +22,6 @@ class Empcloneable implements Cloneable { int a; String name; - Empcloneable(int a, String name) { this.a = a; this.name = name; diff --git a/src/main/java/nitin/a5object/O3UsingClass4Name.java b/src/main/java/nitin/a5object/O3UsingClass4Name.java index 6e13c34e..5ca99d13 100644 --- a/src/main/java/nitin/a5object/O3UsingClass4Name.java +++ b/src/main/java/nitin/a5object/O3UsingClass4Name.java @@ -1,8 +1,6 @@ package nitin.a5object; -/** - * Created by nitin.chaurasia on 3/3/2017. - */ +/** Created by nitin.chaurasia on 3/3/2017. */ public class O3UsingClass4Name { public static void main(String[] args) { @@ -15,7 +13,6 @@ public static void main(String[] args) { } catch (Exception e) { e.printStackTrace(); - } } } diff --git a/src/main/java/nitin/a5object/O4UsingDeserialization.java b/src/main/java/nitin/a5object/O4UsingDeserialization.java index 0ce078bf..c5c4d680 100644 --- a/src/main/java/nitin/a5object/O4UsingDeserialization.java +++ b/src/main/java/nitin/a5object/O4UsingDeserialization.java @@ -5,16 +5,15 @@ import java.io.IOException; import java.io.ObjectInputStream; -/** - * Created by nitin.chaurasia on 3/3/2017. - */ +/** Created by nitin.chaurasia on 3/3/2017. */ public class O4UsingDeserialization { public static void main(String[] args) throws FileNotFoundException { Employee e = null; try { - FileInputStream fileIn = new FileInputStream("src/com/nitin/a21serialization/serialObject.txt"); + FileInputStream fileIn = + new FileInputStream("src/com/nitin/a21serialization/serialObject.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); @@ -32,4 +31,4 @@ public static void main(String[] args) throws FileNotFoundException { System.out.println("Deserialized Employee..."); // System.out.println("Name: " + e.name); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a5object/Sample.java b/src/main/java/nitin/a5object/Sample.java index e0063a70..862c3ff8 100644 --- a/src/main/java/nitin/a5object/Sample.java +++ b/src/main/java/nitin/a5object/Sample.java @@ -1,11 +1,8 @@ package nitin.a5object; -/** - * Created by nitin.chaurasia on 3/3/2017. - */ +/** Created by nitin.chaurasia on 3/3/2017. */ public class Sample { - public int hashcode() { return this.hashCode(); } diff --git a/src/main/java/nitin/a5object/equals/EqualsFailedTest.java b/src/main/java/nitin/a5object/equals/EqualsFailedTest.java index 7ea1aa41..4b22dbdf 100644 --- a/src/main/java/nitin/a5object/equals/EqualsFailedTest.java +++ b/src/main/java/nitin/a5object/equals/EqualsFailedTest.java @@ -1,17 +1,15 @@ package nitin.a5object.equals; -/** - * Created by Nitin Chaurasia on 3/4/16 at 11:28 PM. - */ +/** Created by Nitin Chaurasia on 3/4/16 at 11:28 PM. */ public class EqualsFailedTest { public static void main(String[] args) { String str1 = "Nitin"; String str2 = "Nitin"; - System.out.println(str1.equals(str2));//true + System.out.println(str1.equals(str2)); // true StringBuilder sb1 = new StringBuilder("Nitin"); StringBuilder sb2 = new StringBuilder("Nitin"); /* SB uses implementation of equals provided by Object which just checks reference equality */ - System.out.println(sb1.equals(sb2));//false + System.out.println(sb1.equals(sb2)); // false } } diff --git a/src/main/java/nitin/a5object/toString/Hippo.java b/src/main/java/nitin/a5object/toString/Hippo.java index ffa6656d..b59d2a64 100644 --- a/src/main/java/nitin/a5object/toString/Hippo.java +++ b/src/main/java/nitin/a5object/toString/Hippo.java @@ -1,8 +1,6 @@ package nitin.a5object.toString; -/** - * Created by Nitin Chaurasia on 3/4/16 at 11:01 PM. - */ +/** Created by Nitin Chaurasia on 3/4/16 at 11:01 PM. */ public class Hippo { private final String name; private final double weight; @@ -12,12 +10,9 @@ public Hippo(String name, double weight) { this.weight = weight; } - //Explicit to String Example + // Explicit to String Example @Override public String toString() { - return "Hippo{" + - "name='" + name + '\'' + - ", weight=" + weight + - '}'; + return "Hippo{" + "name='" + name + '\'' + ", weight=" + weight + '}'; } } diff --git a/src/main/java/nitin/a5object/toString/ToString.java b/src/main/java/nitin/a5object/toString/ToString.java index 8b850588..e76e7b0c 100644 --- a/src/main/java/nitin/a5object/toString/ToString.java +++ b/src/main/java/nitin/a5object/toString/ToString.java @@ -1,14 +1,12 @@ package nitin.a5object.toString; /** - * Created by Nitin Chaurasia on 3/4/16 at 10:59 PM. - * All the Classes in Java inherit from Object Class + * Created by Nitin Chaurasia on 3/4/16 at 10:59 PM. All the Classes in Java inherit from Object + * Class */ public class ToString { public static void main(String[] args) { Hippo hippo = new Hippo("Danger hippo", 400.23); System.out.println(hippo); - - } } diff --git a/src/main/java/nitin/a6oops/E1EncapsulationConcept.java b/src/main/java/nitin/a6oops/E1EncapsulationConcept.java index bb1b658e..3918e94a 100644 --- a/src/main/java/nitin/a6oops/E1EncapsulationConcept.java +++ b/src/main/java/nitin/a6oops/E1EncapsulationConcept.java @@ -1,8 +1,6 @@ package nitin.a6oops; -/** - * Created by Nitin C on 11/26/2015. - */ +/** Created by Nitin C on 11/26/2015. */ public class E1EncapsulationConcept { public static void main(String[] args) { /* diff --git a/src/main/java/nitin/a6oops/abstraction/Animal.java b/src/main/java/nitin/a6oops/abstraction/Animal.java index 19b44588..50540def 100644 --- a/src/main/java/nitin/a6oops/abstraction/Animal.java +++ b/src/main/java/nitin/a6oops/abstraction/Animal.java @@ -1,8 +1,6 @@ package nitin.a6oops.abstraction; -/** - * Created by Nitin Chaurasia on 3/6/16 at 11:48 PM. - */ +/** Created by Nitin Chaurasia on 3/6/16 at 11:48 PM. */ public abstract class Animal { protected int age; diff --git a/src/main/java/nitin/a6oops/abstraction/Car.java b/src/main/java/nitin/a6oops/abstraction/Car.java index 63598911..78b449e2 100644 --- a/src/main/java/nitin/a6oops/abstraction/Car.java +++ b/src/main/java/nitin/a6oops/abstraction/Car.java @@ -1,8 +1,6 @@ package nitin.a6oops.abstraction; -/** - * Created by nitin on Sat, 1/14/17 at 9:06 PM. - */ +/** Created by nitin on Sat, 1/14/17 at 9:06 PM. */ public abstract class Car { public abstract void engine(); @@ -11,4 +9,3 @@ public void blowHorn() { System.out.println("Honk - Honk"); } } - diff --git a/src/main/java/nitin/a6oops/abstraction/Polo.java b/src/main/java/nitin/a6oops/abstraction/Polo.java index 4b3ee69b..4675806e 100644 --- a/src/main/java/nitin/a6oops/abstraction/Polo.java +++ b/src/main/java/nitin/a6oops/abstraction/Polo.java @@ -1,8 +1,6 @@ package nitin.a6oops.abstraction; -/** - * Created by nitin on Sat, 1/14/17 at 9:11 PM. - */ +/** Created by nitin on Sat, 1/14/17 at 9:11 PM. */ public class Polo extends Car { public void engine() { System.out.println("Polo's Engine"); diff --git a/src/main/java/nitin/a6oops/abstraction/Runner.java b/src/main/java/nitin/a6oops/abstraction/Runner.java index 2df126a7..1c6b1a9d 100644 --- a/src/main/java/nitin/a6oops/abstraction/Runner.java +++ b/src/main/java/nitin/a6oops/abstraction/Runner.java @@ -1,8 +1,6 @@ package nitin.a6oops.abstraction; -/** - * Created by nitin on Sat, 1/14/17 at 9:10 PM. - */ +/** Created by nitin on Sat, 1/14/17 at 9:10 PM. */ public class Runner { public static void main(String[] args) { Car p1 = new Swift(); diff --git a/src/main/java/nitin/a6oops/abstraction/Swift.java b/src/main/java/nitin/a6oops/abstraction/Swift.java index 1bb5af8a..d7e59e2d 100644 --- a/src/main/java/nitin/a6oops/abstraction/Swift.java +++ b/src/main/java/nitin/a6oops/abstraction/Swift.java @@ -1,11 +1,8 @@ package nitin.a6oops.abstraction; -/** - * Created by nitin on Sat, 1/14/17 at 9:09 PM. - */ +/** Created by nitin on Sat, 1/14/17 at 9:09 PM. */ public class Swift extends Car { public void engine() { System.out.println("Swift's Engine"); } } - diff --git a/src/main/java/nitin/a6oops/inheritance/Animal.java b/src/main/java/nitin/a6oops/inheritance/Animal.java index c5b56626..88d8f48d 100644 --- a/src/main/java/nitin/a6oops/inheritance/Animal.java +++ b/src/main/java/nitin/a6oops/inheritance/Animal.java @@ -1,14 +1,10 @@ package nitin.a6oops.inheritance; -/** - * Created by Nitin Chaurasia on 3/6/16 at 11:37 PM. - */ +/** Created by Nitin Chaurasia on 3/6/16 at 11:37 PM. */ public class Animal { private int age; - public Animal(int age) { - - } + public Animal(int age) {} public int getAge() { return age; @@ -17,8 +13,6 @@ public int getAge() { public void setAge(int age) { this.age = age; } - - } class Lion extends Animal { diff --git a/src/main/java/nitin/a6oops/interfaces/I1InterfaceMethod.java b/src/main/java/nitin/a6oops/interfaces/I1InterfaceMethod.java index c49efde2..2976727e 100644 --- a/src/main/java/nitin/a6oops/interfaces/I1InterfaceMethod.java +++ b/src/main/java/nitin/a6oops/interfaces/I1InterfaceMethod.java @@ -2,8 +2,8 @@ /** * Created by nitin on 12/29/16. - *

- * BasicConnection Class can extend only one class but can implement multiple interfaces + * + *

BasicConnection Class can extend only one class but can implement multiple interfaces */ interface Interface { void m1(); @@ -34,8 +34,8 @@ class AnotherServiceProvider extends ServiceProvider implements Interface, Anoth public static void main(String[] args) { AnotherServiceProvider a = new AnotherServiceProvider(); a.m1(); - } + // m1 exists in both interfaces. Naming conflict // Error: reference to m1() is ambiguous @@ -45,12 +45,8 @@ public void m2() { } @Override - public void m3() { - - } + public void m3() {} @Override - public void m4() { - - } -} \ No newline at end of file + public void m4() {} +} diff --git a/src/main/java/nitin/a6oops/interfaces/I2InterfaceVariables.java b/src/main/java/nitin/a6oops/interfaces/I2InterfaceVariables.java index 746ea9e6..c984a1c4 100644 --- a/src/main/java/nitin/a6oops/interfaces/I2InterfaceVariables.java +++ b/src/main/java/nitin/a6oops/interfaces/I2InterfaceVariables.java @@ -9,17 +9,13 @@ interface Right { int x = 666; } -/** - * Created by nitin on 12/29/16. - */ +/** Created by nitin on 12/29/16. */ public class I2InterfaceVariables implements Left, Right { public static void main(String[] args) { - //System.out.println(x);// Error: reference to x is ambiguous + // System.out.println(x);// Error: reference to x is ambiguous // Resolve Naming Conflict System.out.println(Left.x); System.out.println(Right.x); - - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/I3MarkerInterface.java b/src/main/java/nitin/a6oops/interfaces/I3MarkerInterface.java index 7c32159b..a26e3705 100644 --- a/src/main/java/nitin/a6oops/interfaces/I3MarkerInterface.java +++ b/src/main/java/nitin/a6oops/interfaces/I3MarkerInterface.java @@ -2,11 +2,9 @@ /** * Created by nitin on 12/29/16. - *

- * Marker Interface : Interface contains no methods - * ex: Serializable, Cloneable - * JVM is responsible for providing required ability in marker interfaces - * we can create our own marker interface, but customization of JVM is required. + * + *

Marker Interface : Interface contains no methods ex: Serializable, Cloneable JVM is + * responsible for providing required ability in marker interfaces we can create our own marker + * interface, but customization of JVM is required. */ -public class I3MarkerInterface { -} +public class I3MarkerInterface {} diff --git a/src/main/java/nitin/a6oops/interfaces/I4AdapterClass.java b/src/main/java/nitin/a6oops/interfaces/I4AdapterClass.java index 09f782bc..9394960a 100644 --- a/src/main/java/nitin/a6oops/interfaces/I4AdapterClass.java +++ b/src/main/java/nitin/a6oops/interfaces/I4AdapterClass.java @@ -12,9 +12,7 @@ interface X { void m5(); } -/** - * Created by nitin on 12/29/16. - */ +/** Created by nitin on 12/29/16. */ public class I4AdapterClass extends AdapterX { public static void main(String[] args) { @@ -25,9 +23,9 @@ public static void main(String[] args) { @Override public void m3() { - System.out.println("Providing Implementation of only M3, even though we have access to all the methods, " + - "we can choose to implement what we like in Adapter pattern"); - + System.out.println( + "Providing Implementation of only M3, even though we have access to all the methods, " + + "we can choose to implement what we like in Adapter pattern"); } @Override @@ -40,27 +38,17 @@ public void m2() { abstract class AdapterX implements X { @Override - public void m1() { - - } + public void m1() {} @Override - public void m2() { - - } + public void m2() {} @Override - public void m3() { - - } + public void m3() {} @Override - public void m4() { - - } + public void m4() {} @Override - public void m5() { - - } -} \ No newline at end of file + public void m5() {} +} diff --git a/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D1Example1.java b/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D1Example1.java index 9ad2f73b..947d6ca0 100644 --- a/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D1Example1.java +++ b/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D1Example1.java @@ -2,7 +2,7 @@ interface DefaultMethodInInterface { - //Default method with implementation, in an Interface + // Default method with implementation, in an Interface default void m1() { System.out.println("From Default method"); } @@ -11,8 +11,8 @@ default void m1() { } /** - * Created by Nitin Chaurasia on 1/30/18 at 5:20 PM. - * Since Java 8 onwards, Interface can have concrete implementation in Default method + * Created by Nitin Chaurasia on 1/30/18 at 5:20 PM. Since Java 8 onwards, Interface can have + * concrete implementation in Default method */ public class D1Example1 implements DefaultMethodInInterface { public static void main(String[] args) { diff --git a/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D2LeftRight.java b/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D2LeftRight.java index a4e5cce0..a261766f 100644 --- a/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D2LeftRight.java +++ b/src/main/java/nitin/a6oops/interfaces/a10interfaces/DefaultMethodsInJava8/D2LeftRight.java @@ -13,23 +13,21 @@ default void m1() { } } -/** - * Created by Nitin Chaurasia on 1/31/18 at 5:50 PM. - */ +/** Created by Nitin Chaurasia on 1/31/18 at 5:50 PM. */ -//CE : inherits unrelated defaults for m1() from types Left and DefaultMethodsInJava8.Right -public class D2LeftRight implements Left, Right {//Compulsory give implementation +// CE : inherits unrelated defaults for m1() from types Left and DefaultMethodsInJava8.Right +public class D2LeftRight implements Left, Right { // Compulsory give implementation public static void main(String[] args) { D2LeftRight d = new D2LeftRight(); d.m1(); } - //Without this method override, CE will be there. + // Without this method override, CE will be there. @Override public void m1() { Left.super.m1(); Right.super.m1(); System.out.println("Over ridden"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/CodeReusabilityInInterf.java b/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/CodeReusabilityInInterf.java index 2436d003..9f801b73 100644 --- a/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/CodeReusabilityInInterf.java +++ b/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/CodeReusabilityInInterf.java @@ -11,7 +11,7 @@ static void m2() { // m3(); } - //private methods + // private methods // java: private interface methods are not supported in -source 8 /*private static void m3(){ System.out.println("m3 for code reusability"); @@ -20,12 +20,9 @@ static void m2() { default void m4() { System.out.println("m4 Default method"); } - } -/** - * Created by Nitin Chaurasia on 1/31/18 at 9:24 PM. - */ +/** Created by Nitin Chaurasia on 1/31/18 at 9:24 PM. */ public class CodeReusabilityInInterf implements Interf1 { public static void main(String[] args) { @@ -33,4 +30,4 @@ public static void main(String[] args) { Interf1.m1(); Interf1.m2(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/S1Example1.java b/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/S1Example1.java index 0ed440f1..54ca337a 100644 --- a/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/S1Example1.java +++ b/src/main/java/nitin/a6oops/interfaces/a10interfaces/StaticMethodsInsideInterfacesFromJava8/S1Example1.java @@ -5,27 +5,24 @@ static void m1() { System.out.println("Static method as a utility method in an interface"); } - // Static methods are allowed, this method could be run directly from command prompt static void main() { System.out.println("MAin method from Interface Interf"); } } -/** - * Created by Nitin Chaurasia on 1/30/18 at 5:30 PM. - */ +/** Created by Nitin Chaurasia on 1/30/18 at 5:30 PM. */ public class S1Example1 implements Interf { public static void main(String[] args) { // the only way to call Interface static method is via the interface name. Interf.m1(); - //INVALID : via a5object reference now allowed + // INVALID : via a5object reference now allowed S1Example1 s = new S1Example1(); - //s.m1(); - //Not available to Implementation class - //S1Example1.m1(); + // s.m1(); + // Not available to Implementation class + // S1Example1.m1(); } } diff --git a/src/main/java/nitin/a6oops/interfaces/a10interfaces/privateMethodsInInterfaceJava9/CodeReusabilityInInterf.java b/src/main/java/nitin/a6oops/interfaces/a10interfaces/privateMethodsInInterfaceJava9/CodeReusabilityInInterf.java index ba4fe44f..b28bba28 100644 --- a/src/main/java/nitin/a6oops/interfaces/a10interfaces/privateMethodsInInterfaceJava9/CodeReusabilityInInterf.java +++ b/src/main/java/nitin/a6oops/interfaces/a10interfaces/privateMethodsInInterfaceJava9/CodeReusabilityInInterf.java @@ -3,12 +3,12 @@ interface Interf { default void m1() { System.out.println("From m1"); - //m3(); + // m3(); } default void m2() { System.out.println("From m2"); - //m3(); + // m3(); } /*private void m3(){ @@ -18,9 +18,8 @@ default void m2() { } /** - * Created by Nitin Chaurasia on 1/31/18 at 9:24 PM. - * private methods in Interfaces can be used, with implementation, - * to be used within Default methods. + * Created by Nitin Chaurasia on 1/31/18 at 9:24 PM. private methods in Interfaces can be used, with + * implementation, to be used within Default methods. */ public class CodeReusabilityInInterf implements Interf { public static void main(String[] args) { @@ -28,4 +27,4 @@ public static void main(String[] args) { t.m1(); t.m2(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/Car.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/Car.java index 35f755a1..0a2ccf53 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/Car.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/Car.java @@ -6,14 +6,15 @@ class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods - //Declaring the constructor private for the factories to be enabled. + // there is a functional programming style that we will be using which will lead us to using + // factory methods + // Declaring the constructor private for the factories to be enabled. private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -21,20 +22,24 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY // using a named static factory for this, able to convey the meaning of the arguments. - //It's interesting to note that with the release of Java 8, virtually all of the new APIs made exclusive use of static + // It's interesting to note that with the release of Java 8, virtually all of the new APIs made + // exclusive use of static // factories instead of having public constructors, with the exception of Exceptions. public static Car withGasColorPassengers(int gas, String color, String... passengers) { - // And one of the things that functional programming likes to do is to use immutable data whenever possible. - //t's generally considered to be preferable to create a new version of something rather than to change an existing something + // And one of the things that functional programming likes to do is to use immutable data + // whenever possible. + // t's generally considered to be preferable to create a new version of something rather + // than to change an existing something List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); return self; } - //Notice the list of arguments. This would not have been possible with public constructors as this would not + // Notice the list of arguments. This would not have been possible with public constructors as + // this would not // have been a valid overload public static Car withGasColorPassengersAndTrunk(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); @@ -63,15 +68,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO of Optional + // This could return null; DELIBERATELY WRITTEN FOR DEMO of Optional public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - //Check for the null trunkContents. - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + // Check for the null trunkContents. + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/CarRunner.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/CarRunner.java index b027ef30..80ee0d27 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/CarRunner.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r0TheProblem/CarRunner.java @@ -3,26 +3,27 @@ import java.util.Arrays; import java.util.List; -//Package-private class +// Package-private class class CarRunner { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); - //Calling Utility Method + // Calling Utility Method showAll(cars); } public static void showAll(List lc) { for (Car c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/Car.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/Car.java index b3c9e8e5..08f8450b 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/Car.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/Car.java @@ -6,13 +6,14 @@ class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -20,20 +21,24 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY // using a named static factory for this, able to convey the meaning of the arguments. - //It's interesting to note that with the release of Java 8, virtually all of the new APIs made exclusive use of static + // It's interesting to note that with the release of Java 8, virtually all of the new APIs made + // exclusive use of static // factories instead of having public constructors, with the exception of Exceptions. public static Car withGasColorPassengers(int gas, String color, String... passengers) { - // And one of the things that functional programming likes to do is to use immutable data whenever possible. - //t's generally considered to be preferable to create a new version of something rather than to change an existing something + // And one of the things that functional programming likes to do is to use immutable data + // whenever possible. + // t's generally considered to be preferable to create a new version of something rather + // than to change an existing something List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); return self; } - //Notice the list of arguments. This would not have been possible with public constructors as this would not + // Notice the list of arguments. This would not have been possible with public constructors as + // this would not // have been a valid overload public static Car withGasColorPassengersAndTrunk(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); @@ -62,15 +67,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - //Check for the null trunkContents. - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + // Check for the null trunkContents. + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/CarRunner.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/CarRunner.java index 49bbe38f..20362f5b 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/CarRunner.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r1FindCarsWithColor/CarRunner.java @@ -7,37 +7,39 @@ class CarRunner { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); - //Showing Red Cars... But how abotu Blue. Make the method General insteaqd of copy pasting the red and change blue. + // Showing Red Cars... But how abotu Blue. Make the method General insteaqd of copy pasting + // the red and change blue. System.out.println("************ getRedCar ************"); showAll(getRedCar(cars)); - //A little better + // A little better System.out.println("************ getColoredCar ************"); showAll(getColoredCar(cars, "Black")); System.out.println("************ getColoredCarIterable ************"); showAll(getColoredCarIterable(cars, "Black")); - //Original List doesn't change + // Original List doesn't change showAll(cars); } public static void showAll(List lc) { for (Car c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); @@ -45,7 +47,7 @@ public static void showAll(List lc) { // Too specific method to be reusable public static List getRedCar(List car) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : car) { @@ -58,7 +60,7 @@ public static List getRedCar(List car) { // General method || Slightly reusable public static List getColoredCar(List car, String color) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : car) { @@ -69,12 +71,12 @@ public static List getColoredCar(List car, String color) { return returnCars; } - //Generalizing the arguments || The more general the argument, the better is its usability. + // Generalizing the arguments || The more general the argument, the better is its usability. // In the method, only the iterable feature of the list is being used. - //ONLY THE ARGUMENT IS CHANGED. NO OTHER CODE CHANGE + // ONLY THE ARGUMENT IS CHANGED. NO OTHER CODE CHANGE public static List getColoredCarIterable(Iterable iter, String color) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : iter) { @@ -84,5 +86,4 @@ public static List getColoredCarIterable(Iterable iter, String color) } return returnCars; } - } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/Car.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/Car.java index 1f112800..18f64840 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/Car.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/Car.java @@ -6,13 +6,14 @@ class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -20,20 +21,24 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY // using a named static factory for this, able to convey the meaning of the arguments. - //It's interesting to note that with the release of Java 8, virtually all of the new APIs made exclusive use of static + // It's interesting to note that with the release of Java 8, virtually all of the new APIs made + // exclusive use of static // factories instead of having public constructors, with the exception of Exceptions. public static Car withGasColorPassengers(int gas, String color, String... passengers) { - // And one of the things that functional programming likes to do is to use immutable data whenever possible. - //t's generally considered to be preferable to create a new version of something rather than to change an existing something + // And one of the things that functional programming likes to do is to use immutable data + // whenever possible. + // t's generally considered to be preferable to create a new version of something rather + // than to change an existing something List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); return self; } - //Notice the list of arguments. This would not have been possible with public constructors as this would not + // Notice the list of arguments. This would not have been possible with public constructors as + // this would not // have been a valid overload public static Car withGasColorPassengersAndTrunk(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); @@ -62,15 +67,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - //Check for the null trunkContents. - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + // Check for the null trunkContents. + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/CarRunner.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/CarRunner.java index ff8952d1..dba69754 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/CarRunner.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r2FindCarsWithMultipleCriteria/CarRunner.java @@ -8,54 +8,55 @@ class CarRunner { public static void main(String[] args) { - /* - One is how to make a sublist and the other is what to put in the sublist. - - What we would like to be able to do is not simply to specify a value that we want to match or exceed, - like a red color or a gas level. What we would like to be able to do is to say, - here is the behavior that will select or identify the kind of vehicle that we want in this output list. - - And we tend, as a5object oriented programmers, not to think in terms of behavior as arguments to functions. - But it turns out that an a5object is the amalgamation of both state, things like gas levels, and behavior, - the methods that we apply to that a5object, all in one place. And if we pass an a5object as an argument, - we pass the behavior that that a5object contains. That means that we could pass the selection behavior by - passing an a5object, primarily for the purpose of behavior rather than just for the purpose of its state. - - So what we would like to be able to do is to **pass an argument** in here that tells us how to - select something and call a behavior on it in here. - - So, hopefully the idea that we can pass an a5object as a function argument, or as a method argument, - and it takes with it the behavior that is built into that a5object, is starting to make a little bit of sense. - */ - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + /* + One is how to make a sublist and the other is what to put in the sublist. + + What we would like to be able to do is not simply to specify a value that we want to match or exceed, + like a red color or a gas level. What we would like to be able to do is to say, + here is the behavior that will select or identify the kind of vehicle that we want in this output list. + + And we tend, as a5object oriented programmers, not to think in terms of behavior as arguments to functions. + But it turns out that an a5object is the amalgamation of both state, things like gas levels, and behavior, + the methods that we apply to that a5object, all in one place. And if we pass an a5object as an argument, + we pass the behavior that that a5object contains. That means that we could pass the selection behavior by + passing an a5object, primarily for the purpose of behavior rather than just for the purpose of its state. + + So what we would like to be able to do is to **pass an argument** in here that tells us how to + select something and call a behavior on it in here. + + So, hopefully the idea that we can pass an a5object as a function argument, or as a method argument, + and it takes with it the behavior that is built into that a5object, is starting to make a little bit of sense. + */ + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getColoredCarIterable ************"); showAll(getColoredCarIterable(cars, "Octarine")); - /* - getColoredCarIterable() and getColoredCarByMinGasLevel() has code duplication. Except for the argument and the if - statement, everything else is a copy-paste - */ + /* + getColoredCarIterable() and getColoredCarByMinGasLevel() has code duplication. Except for the argument and the if + statement, everything else is a copy-paste + */ System.out.println("************ getColoredCarByMinGasLevel ************"); showAll(getColoredCarByMinGasLevel(cars, 7)); - //Original List doesn't change + // Original List doesn't change showAll(cars); } private static List getColoredCarIterable(Iterable iter, String color) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : iter) { @@ -67,7 +68,7 @@ private static List getColoredCarIterable(Iterable iter, String color) } private static List getColoredCarByMinGasLevel(Iterable iter, int minGasLevel) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : iter) { @@ -80,10 +81,9 @@ private static List getColoredCarByMinGasLevel(Iterable iter, int minG public static void showAll(List lc) { for (Car c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } - } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/Car.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/Car.java index 4a40abbc..ff99b715 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/Car.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/Car.java @@ -6,13 +6,14 @@ class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -20,20 +21,24 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY // using a named static factory for this, able to convey the meaning of the arguments. - //It's interesting to note that with the release of Java 8, virtually all of the new APIs made exclusive use of static + // It's interesting to note that with the release of Java 8, virtually all of the new APIs made + // exclusive use of static // factories instead of having public constructors, with the exception of Exceptions. public static Car withGasColorPassengers(int gas, String color, String... passengers) { - // And one of the things that functional programming likes to do is to use immutable data whenever possible. - //t's generally considered to be preferable to create a new version of something rather than to change an existing something + // And one of the things that functional programming likes to do is to use immutable data + // whenever possible. + // t's generally considered to be preferable to create a new version of something rather + // than to change an existing something List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); return self; } - //Notice the list of arguments. This would not have been possible with public constructors as this would not + // Notice the list of arguments. This would not have been possible with public constructors as + // this would not // have been a valid overload public static Car withGasColorPassengersAndTrunk(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); @@ -62,15 +67,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - //Check for the null trunkContents. - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + // Check for the null trunkContents. + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/CarRunner.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/CarRunner.java index eef83f59..f36038ac 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/CarRunner.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r3SortCarsPreJava8/CarRunner.java @@ -8,38 +8,39 @@ class CarRunner { public static void main(String[] args) { - /* - That was the version of ordering things for lists prior to Java eight but the essential thing that's going on here - is that we've created an a5object, implementing the comparator interface such that, the sort method could use the - behavior defined in that a5object to decide, are these two objects in the right order, or the wrong order and that - was the basis on which it could then proceed to sort objects of a type it had never seen before based on an - ordering criterion that did not come to anybody's head at the time when the sort method was written. - */ - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); + /* + That was the version of ordering things for lists prior to Java eight but the essential thing that's going on here + is that we've created an a5object, implementing the comparator interface such that, the sort method could use the + behavior defined in that a5object to decide, are these two objects in the right order, or the wrong order and that + was the basis on which it could then proceed to sort objects of a type it had never seen before based on an + ordering criterion that did not come to anybody's head at the time when the sort method was written. + */ + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); - //Calling Utility Method + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getColoredCarIterable ************"); showAll(getColoredCarIterable(cars, "Octarine")); - //PassengerCountOrder doesnt have any state to it, Only behaviour (compare method) + // PassengerCountOrder doesnt have any state to it, Only behaviour (compare method) cars.sort(new PassengerCountOrder()); - //Original List got changed + // Original List got changed showAll(cars); } private static List getColoredCarIterable(Iterable iter, String color) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : iter) { @@ -51,7 +52,7 @@ private static List getColoredCarIterable(Iterable iter, String color) } private static List getColoredCarByMinGasLevel(Iterable iter, int minGasLevel) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : iter) { @@ -64,10 +65,9 @@ private static List getColoredCarByMinGasLevel(Iterable iter, int minG public static void showAll(List lc) { for (Car c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } - } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/Car.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/Car.java index 899a92d5..5ff2e2a7 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/Car.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/Car.java @@ -6,13 +6,14 @@ class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -20,20 +21,24 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY // using a named static factory for this, able to convey the meaning of the arguments. - //It's interesting to note that with the release of Java 8, virtually all of the new APIs made exclusive use of static + // It's interesting to note that with the release of Java 8, virtually all of the new APIs made + // exclusive use of static // factories instead of having public constructors, with the exception of Exceptions. public static Car withGasColorPassengers(int gas, String color, String... passengers) { - // And one of the things that functional programming likes to do is to use immutable data whenever possible. - //t's generally considered to be preferable to create a new version of something rather than to change an existing something + // And one of the things that functional programming likes to do is to use immutable data + // whenever possible. + // t's generally considered to be preferable to create a new version of something rather + // than to change an existing something List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); return self; } - //Notice the list of arguments. This would not have been possible with public constructors as this would not + // Notice the list of arguments. This would not have been possible with public constructors as + // this would not // have been a valid overload public static Car withGasColorPassengersAndTrunk(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); @@ -62,15 +67,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - //Check for the null trunkContents. - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + // Check for the null trunkContents. + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } } diff --git a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/CarRunner.java b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/CarRunner.java index 6442e486..106641cc 100755 --- a/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/CarRunner.java +++ b/src/main/java/nitin/a6oops/interfaces/f1functionalFoundation/r4CommandPatternSelection/CarRunner.java @@ -8,45 +8,46 @@ class CarRunner { public static void main(String[] args) { - /* - So a key piece of what we have to do now is to build an interface that we can use to pass this question of - do we like this one, wrapped up as an a5object, as an argument into our selection mechanism. + /* + So a key piece of what we have to do now is to build an interface that we can use to pass this question of + do we like this one, wrapped up as an a5object, as an argument into our selection mechanism. - the command Pattern. Turns out, that not only is the command pattern, a well-known Pattern, - although not perhaps as well used as it should have been in a5object orientation, it's also key way of doing things - in functional programming. - */ - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); + the command Pattern. Turns out, that not only is the command pattern, a well-known Pattern, + although not perhaps as well used as it should have been in a5object orientation, it's also key way of doing things + in functional programming. + */ + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); - //Calling Utility Method + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - //The behaviour of decision making is passed as an argument. + // The behaviour of decision making is passed as an argument. showAll(getCarsByCriteria(cars, new RedCarCriterion())); System.out.println("************ GasLevelCarCriterion ************"); showAll(getCarsByCriteria(cars, new GasLevelCarCriterion(7))); - //Original List is not changed + // Original List is not changed showAll(cars); } private static List getCarsByCriteria(Iterable iter, CarCriteria criteria) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -56,10 +57,9 @@ private static List getCarsByCriteria(Iterable iter, CarCriteria crite public static void showAll(List lc) { for (Car c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } - } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/AnonymousInnerClass.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/AnonymousInnerClass.java index b1812cb2..a8539d52 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/AnonymousInnerClass.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/AnonymousInnerClass.java @@ -1,23 +1,23 @@ package nitin.a6oops.interfaces.functionalInterface.AnonymousInnerClassVSLambda; /** - * Created by Nitin Chaurasia on 1/30/18 at 5:04 PM. - * Anonymous inner class can be replaced with Lambda in some conditions + * Created by Nitin Chaurasia on 1/30/18 at 5:04 PM. Anonymous inner class can be replaced with + * Lambda in some conditions */ public class AnonymousInnerClass { public static void main(String[] args) { Runnable r = new Runnable() { // Anonymous Inner Class - @Override - public void run() { - for (int i = 0; i < 5; i++) { - System.out.println("Child Class"); - } - } - }; + @Override + public void run() { + for (int i = 0; i < 5; i++) { + System.out.println("Child Class"); + } + } + }; Thread t = new Thread(r); t.start(); - //Main thread continues + // Main thread continues for (int i = 0; i < 5; i++) { System.out.println("Main Class"); } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/F5LambdaThreads.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/F5LambdaThreads.java index 786f2494..9789a2a1 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/F5LambdaThreads.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/F5LambdaThreads.java @@ -1,15 +1,14 @@ package nitin.a6oops.interfaces.functionalInterface.AnonymousInnerClassVSLambda; -/** - * Created by Nitin Chaurasia on 1/30/18 at 4:31 PM. - */ +/** Created by Nitin Chaurasia on 1/30/18 at 4:31 PM. */ public class F5LambdaThreads { public static void main(String[] args) { - Runnable r = () -> { - for (int i = 0; i < 10; i++) { - System.out.println("Child thread"); - } - }; + Runnable r = + () -> { + for (int i = 0; i < 10; i++) { + System.out.println("Child thread"); + } + }; Thread t = new Thread(r); t.start(); diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/WithLamdaExp.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/WithLamdaExp.java index 062f1d2d..d02e6c1c 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/WithLamdaExp.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/AnonymousInnerClassVSLambda/WithLamdaExp.java @@ -1,26 +1,26 @@ package nitin.a6oops.interfaces.functionalInterface.AnonymousInnerClassVSLambda; -/** - * Created by Nitin Chaurasia on 1/30/18 at 5:08 PM. - */ +/** Created by Nitin Chaurasia on 1/30/18 at 5:08 PM. */ public class WithLamdaExp { public static void main(String[] args) { - //Lambda Expression -// Runnable r = () -> { -// for (int i = 0; i < 5; i++) { -// System.out.println("Child Thread"); -// } -// }; -// -// Thread t = new Thread(r);// instead of passing r, pass the lambda directly + // Lambda Expression + // Runnable r = () -> { + // for (int i = 0; i < 5; i++) { + // System.out.println("Child Thread"); + // } + // }; + // + // Thread t = new Thread(r);// instead of passing r, pass the lambda directly - //Passing Lambda as Argument - Thread t = new Thread(() -> { - for (int i = 0; i < 5; i++) { - System.out.println("Child Thread"); - } - }); + // Passing Lambda as Argument + Thread t = + new Thread( + () -> { + for (int i = 0; i < 5; i++) { + System.out.println("Child Thread"); + } + }); t.start(); for (int i = 0; i < 5; i++) { diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/F1FuncInterfaceWRTInheritence.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/F1FuncInterfaceWRTInheritence.java index 9448ba23..1bd5dcaf 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/F1FuncInterfaceWRTInheritence.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/F1FuncInterfaceWRTInheritence.java @@ -1,33 +1,33 @@ package nitin.a6oops.interfaces.functionalInterface; -/** - * Created by Nitin Chaurasia on 1/30/18 at 10:46 AM. - */ +/** Created by Nitin Chaurasia on 1/30/18 at 10:46 AM. */ // SAM -> Single Abstract Method & Default and Static methods can be declared @FunctionalInterface interface FuncInterfaceWRTInheritence { static void m3() { - System.out.println("Can declare any number of default and static methods in a Functional Interface"); + System.out.println( + "Can declare any number of default and static methods in a Functional Interface"); } void m1(); - //Can declare any number of default and static methods in a Functional Interface + // Can declare any number of default and static methods in a Functional Interface default int m2() { return 2; } } - // In the child interface we can define exactly same parent interface abstract method. @FunctionalInterface interface ChildFuncInterfaceWRTInheritence extends FuncInterfaceWRTInheritence { - //No Compile Time Error + // No Compile Time Error void m1(); - // In the child interface we can’t define any new abstract methods otherwise child interface won’t be Functional - // Interface and if we are trying to use @Functional Interface annotation then compiler gives an error message. + // In the child interface we can’t define any new abstract methods otherwise child interface + // won’t be Functional + // Interface and if we are trying to use @Functional Interface annotation then compiler gives an + // error message. /* public void m2(); */ // ChildFuncInterfaceWRTInheritence is not a functional interface // multiple non-overriding abstract methods found in interface diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF1Predicate.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF1Predicate.java index ca439514..afe66434 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF1Predicate.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF1Predicate.java @@ -7,28 +7,26 @@ import java.util.function.Predicate; /** - * Created by Nitin Chaurasia on 1/30/18 at 5:41 PM. - * A predicate is a function with a single argument and returns boolean value. - * Predicate interface is present in Java.util.function package - *

- * It’s a functional interface and it contains only one method i.e., test() + * Created by Nitin Chaurasia on 1/30/18 at 5:41 PM. A predicate is a function with a single + * argument and returns boolean value. Predicate interface is present in Java.util.function package + * + *

It’s a functional interface and it contains only one method i.e., test() */ public class PDF1Predicate { public static void main(String[] args) { // Predicate to test if an int is Greater than 10 - //Predicate p = i -> {return i>10;}; + // Predicate p = i -> {return i>10;}; Predicate p1 = i -> i > 10; System.out.println(p1.test(10)); - System.out.println(p1.test(6));//false + System.out.println(p1.test(6)); // false - - //Predicate to check length of the String is less than 5 + // Predicate to check length of the String is less than 5 Predicate p2 = str -> (str.length() < 6); System.out.println(p2.test("Nitin")); System.out.println(p2.test("Chaurasia")); - //Predicate to test of a Collection is Empty + // Predicate to test of a Collection is Empty Predicate p3 = c -> c.isEmpty(); ArrayList l1 = new ArrayList(); l1.add(23); @@ -36,18 +34,16 @@ public static void main(String[] args) { System.out.println(p3.test(l1)); System.out.println(p3.test(l2)); - List list = Arrays.asList("first", "second", "third", "testString"); // Static reference as there are no parameter Predicate p4 = String::isEmpty; Predicate p5 = (s -> s.contains("testString")); - System.out.println(p4.test(""));//true - System.out.println(p5.test("TestString"));//false + System.out.println(p4.test("")); // true + System.out.println(p5.test("TestString")); // false - //How to use this predicate in the List?? + // How to use this predicate in the List?? Predicate testIsEmpty = String::isEmpty; - } } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF2PredicateJoining.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF2PredicateJoining.java index d09c9d6f..e4f183ee 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF2PredicateJoining.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF2PredicateJoining.java @@ -1,20 +1,14 @@ package nitin.a6oops.interfaces.functionalInterface.PredefinedFunctionalInterfaces; -import java.util.Arrays; import java.util.List; import java.util.function.Predicate; /** - * Created by Nitin Chaurasia on 1/30/18 at 8:37 PM.The file name should be application-datasource-h2.properties - * P1 -> if number is > 10 - * P2 -> is even - *

- * P1.negate() - * P1.and(P2) - * P1.or(P2) + * Created by Nitin Chaurasia on 1/30/18 at 8:37 PM.The file name should be + * application-datasource-h2.properties P1 -> if number is > 10 P2 -> is even + * + *

P1.negate() P1.and(P2) P1.or(P2) */ - - public class PDF2PredicateJoining { public static void main(String[] args) { int[] x = {0, 5, 10, 15, 20, 25, 30}; @@ -35,24 +29,18 @@ public static void main(String[] args) { System.out.println("Number Greater than 10 or Even"); m1(p1.or(p2), x); - Predicate egg = (s -> s.contains("egg")); Predicate brownEgg = (s -> s.contains("brown")); - //Predicate if both egg and brownEgg exists + // Predicate if both egg and brownEgg exists Predicate doublePredicate = egg.and(brownEgg); Predicate doublePredicateNegate = egg.and(brownEgg.negate()); - - } private static void m1(Predicate p, int[] arr) { for (int x : arr) { - if (p.test(x)) - System.out.print(x + "\t"); + if (p.test(x)) System.out.print(x + "\t"); } System.out.println(); } - - } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF3Function.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF3Function.java index 8c3a33f7..edd5ca19 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF3Function.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF3Function.java @@ -3,24 +3,22 @@ import java.util.function.Function; /** - * Created by Nitin C on 3/3/2016. - * A function is responsible for turning one parameter into a value of a potentially different type and returning it. - * has a method apply + * Created by Nitin C on 3/3/2016. A function is responsible for turning one parameter into a value + * of a potentially different type and returning it. has a method apply */ public class PDF3Function { public static void main(String[] args) { - //Takes String as input and and return an Integer as output - //Function T input type, R return type + // Takes String as input and and return an Integer as output + // Function T input type, R return type Function f1 = String::length; Function f2 = x -> x.toUpperCase(); System.out.println(f1.apply("Nitin")); System.out.println(f2.apply("chaurasia")); - //Implement a function to return square of an integer + // Implement a function to return square of an integer Function f3 = x -> x * x; System.out.println(f3.apply(3)); - } } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF4Consumer.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF4Consumer.java index 975f70d9..6c5bdfc6 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF4Consumer.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF4Consumer.java @@ -6,15 +6,11 @@ import java.util.function.Consumer; /** - * Created by Nitin Chaurasia on 1/30/18 at 10:09 PM. - * Created by Nitin C on 3/3/2016. - * Consumer and BiConsumer (Bi means 2 variables) - * HAs a method accept - * Use Consumer when you want to do something with the parameter - * Ex: we use Consumer with forEach - * a_list.forEach(System.out :: print); - * OR - */ /*Consumer c1 = System.out::println; + * Created by Nitin Chaurasia on 1/30/18 at 10:09 PM. Created by Nitin C on 3/3/2016. Consumer and + * BiConsumer (Bi means 2 variables) HAs a method accept Use Consumer when you want to do something + * with the parameter Ex: we use Consumer with forEach a_list.forEach(System.out :: print); OR + */ +/*Consumer c1 = System.out::println; * a_list.forEach(c1); * Consumer c2 = x -> System.out.println(x); */ diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF5Supplier.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF5Supplier.java index 763c182a..3cf05e25 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF5Supplier.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/PDF5Supplier.java @@ -4,29 +4,28 @@ import java.util.function.Supplier; /** - * Created by Nitin Chaurasia on 1/30/18 at 10:13 PM. - * Created by Nitin C on 3/3/2016. - * To generate or Supply values without taking any input - * has a method get. - * The Supplier interface is used when you want to generate or supply values without taking any input. + * Created by Nitin Chaurasia on 1/30/18 at 10:13 PM. Created by Nitin C on 3/3/2016. To generate or + * Supply values without taking any input has a method get. The Supplier interface is used when you + * want to generate or supply values without taking any input. */ public class PDF5Supplier { public static void main(String[] args) { - Supplier s = () -> { - String[] str = {"Nitin", "Kirti", "Chaurasia", "Love"}; - int x = (int) (Math.random() * 3 + 1); - return str[x]; - }; + Supplier s = + () -> { + String[] str = {"Nitin", "Kirti", "Chaurasia", "Love"}; + int x = (int) (Math.random() * 3 + 1); + return str[x]; + }; System.out.println(s.get()); /* Creating date using factory */ - //Static method Reference + // Static method Reference Supplier s1 = LocalDate::now; - //Lambda Expression + // Lambda Expression Supplier s2 = () -> LocalDate.now(); LocalDate d1 = s1.get(); @@ -36,10 +35,8 @@ public static void main(String[] args) { /* A supplier is often used when constructing new a5object */ - //Constructor Reference + // Constructor Reference Supplier myString = StringBuilder::new; Supplier myNewString = () -> new StringBuilder(); - - } } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/consumerUsage/ConsumerUsage.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/consumerUsage/ConsumerUsage.java index 6168639d..ec669f5a 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/consumerUsage/ConsumerUsage.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/consumerUsage/ConsumerUsage.java @@ -6,32 +6,31 @@ import java.util.TreeMap; import java.util.function.Consumer; -/** - * Created by nitin on Tuesday, October/08/2019 at 10:00 PM - */ +/** Created by nitin on Tuesday, October/08/2019 at 10:00 PM */ public class ConsumerUsage { public static void main(String[] args) { - List strList = Arrays.asList("test", "this", "is", "a", "test", "this", "test", "is", "not", "complex"); + List strList = + Arrays.asList( + "test", "this", "is", "a", "test", "this", "test", "is", "not", "complex"); - //Consumer c = s -> System.out.print(s + " ,"); - //Consumer c = System.out::println; + // Consumer c = s -> System.out.print(s + " ,"); + // Consumer c = System.out::println; - strList.stream() - .filter(s -> s.length() < 6) - .forEach(s -> System.out.print(s + " ,")); + strList.stream().filter(s -> s.length() < 6).forEach(s -> System.out.print(s + " ,")); System.out.println(); Map map = new TreeMap<>(); - //BiConsumer b1 = map::put; - Consumer b2 = (k) -> { - if (map.containsKey(k)) { - map.put(k, map.get(k) + 1); - } else { - map.put(k, 1); - } - }; + // BiConsumer b1 = map::put; + Consumer b2 = + (k) -> { + if (map.containsKey(k)) { + map.put(k, map.get(k) + 1); + } else { + map.put(k, 1); + } + }; - //Passing 0 as the default key, it actually gets calculated while evaluated in biConsumer + // Passing 0 as the default key, it actually gets calculated while evaluated in biConsumer strList.forEach(y -> b2.accept(y)); System.out.println(map); diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/FunctionUsage.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/FunctionUsage.java index 35066e2d..2bbbaf81 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/FunctionUsage.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/FunctionUsage.java @@ -1,20 +1,19 @@ package nitin.a6oops.interfaces.functionalInterface.PredefinedFunctionalInterfaces.functionUsage; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.RequiredArgsConstructor; -import lombok.Setter; -import org.apache.commons.lang3.math.NumberUtils; - import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import org.apache.commons.lang3.math.NumberUtils; /** - * Created by nitin on Tuesday, October/08/2019 at 9:01 PM - * Converting the Strings into integers using a function + * Created by nitin on Tuesday, October/08/2019 at 9:01 PM Converting the Strings into integers + * using a function */ public class FunctionUsage { public static final int DEFAULT_VALUE = Integer.MAX_VALUE; @@ -25,17 +24,17 @@ public static void main(String[] args) { Function function = x -> NumberUtils.toInt(x, DEFAULT_VALUE); Predicate predicate = (Integer x) -> (x == DEFAULT_VALUE); - //MAP is used to apply a function - List intList = lists.stream() - .map(list -> function.apply(list)) - .collect(Collectors.toList()); + // MAP is used to apply a function + List intList = + lists.stream().map(list -> function.apply(list)).collect(Collectors.toList()); intList.forEach(System.out::println); - //all the numbers except for the default replacement number - List intList2 = lists.stream() - .map(function) - .filter(predicate.negate()) - .collect(Collectors.toList()); + // all the numbers except for the default replacement number + List intList2 = + lists.stream() + .map(function) + .filter(predicate.negate()) + .collect(Collectors.toList()); intList2.forEach(System.out::println); System.out.println("#######################################################"); @@ -46,22 +45,22 @@ public static void main(String[] args) { Student student5 = new Student("Justin", 24); Student student6 = new Student("James", 25); - List students = Arrays.asList(student1, student2, student3, student4, student5, student6); + List students = + Arrays.asList(student1, student2, student3, student4, student5, student6); // TransformExecutor transformExecutor2 = new TransformExecutor(); - Function transformer = (stud) -> { - String sb = stud.getName() + - " is of age " + - stud.getAge(); - - return sb; - }; + Function transformer = + (stud) -> { + String sb = stud.getName() + " is of age " + stud.getAge(); - List finalList = students.stream() - .map(stud -> transformer.apply(stud)) - //.map(transformer) - .collect(Collectors.toList()); + return sb; + }; + List finalList = + students.stream() + .map(stud -> transformer.apply(stud)) + // .map(transformer) + .collect(Collectors.toList()); finalList.forEach(System.out::println); } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/TransformExecutor.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/TransformExecutor.java index 2bd1d7c0..f0974bac 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/TransformExecutor.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/functionUsage/TransformExecutor.java @@ -11,6 +11,3 @@ public R transform(T t, Function transformer) { return transformer.apply(t); } } - - - diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/Student.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/Student.java index 21245771..e2208adf 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/Student.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/Student.java @@ -2,9 +2,7 @@ import java.util.List; -/** - * Created by synergisticit on 2/25/2016. - */ +/** Created by synergisticit on 2/25/2016. */ public class Student { int id; String fName; @@ -14,7 +12,14 @@ public class Student { short sem; List subjects; - public Student(int id, String fName, String lName, String fathersFullName, String deptCode, short sem, List subjects) { + public Student( + int id, + String fName, + String lName, + String fathersFullName, + String deptCode, + short sem, + List subjects) { this.id = id; this.fName = fName; this.lName = lName; @@ -26,15 +31,26 @@ public Student(int id, String fName, String lName, String fathersFullName, Strin @Override public String toString() { - return "Student{" + - "id=" + id + - ", fName='" + fName + '\'' + - ", lName='" + lName + '\'' + - ", fathersFullName='" + fathersFullName + '\'' + - ", deptCode='" + deptCode + '\'' + - ", sem=" + sem + - ", subjects=" + subjects + - '}'; + return "Student{" + + "id=" + + id + + ", fName='" + + fName + + '\'' + + ", lName='" + + lName + + '\'' + + ", fathersFullName='" + + fathersFullName + + '\'' + + ", deptCode='" + + deptCode + + '\'' + + ", sem=" + + sem + + ", subjects=" + + subjects + + '}'; } public int getId() { @@ -92,4 +108,4 @@ public List getSubjects() { public void setSubjects(List subjects) { this.subjects = subjects; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/multipleIfs.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/multipleIfs.java index e4c4a133..8d476d5c 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/multipleIfs.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/predicateUsage/multipleIfs.java @@ -5,20 +5,46 @@ import java.util.List; import java.util.function.Predicate; -/** - * Created by nitin on Tuesday, October/08/2019 at 12:51 AM - */ +/** Created by nitin on Tuesday, October/08/2019 at 12:51 AM */ public class multipleIfs { public static void main(String[] args) { - Student s1 = new Student(1, "ducy", "Taylor", "Jenkov Taylor", - "MEC", (short) 1, Arrays.asList("MEC1001", "MEC1002", "MEC1003")); + Student s1 = + new Student( + 1, + "ducy", + "Taylor", + "Jenkov Taylor", + "MEC", + (short) 1, + Arrays.asList("MEC1001", "MEC1002", "MEC1003")); - Student s2 = new Student(2, "Tracy", "Rajaei", "Bill Taylor", "CSE", - (short) 1, Arrays.asList("CS1001", "CS1002", "CS1003")); - Student s3 = new Student(3, "Joe", "Kresman", "Andrew Taylor", "CSE", - (short) 2, Arrays.asList("CS2001", "CS2002", "CS2003")); - Student s4 = new Student(4, "lucy", "Green", "Taylor Zimmarman", "CSE", - (short) 3, Arrays.asList("CS3001", "CS3002", "CS3003")); + Student s2 = + new Student( + 2, + "Tracy", + "Rajaei", + "Bill Taylor", + "CSE", + (short) 1, + Arrays.asList("CS1001", "CS1002", "CS1003")); + Student s3 = + new Student( + 3, + "Joe", + "Kresman", + "Andrew Taylor", + "CSE", + (short) 2, + Arrays.asList("CS2001", "CS2002", "CS2003")); + Student s4 = + new Student( + 4, + "lucy", + "Green", + "Taylor Zimmarman", + "CSE", + (short) 3, + Arrays.asList("CS3001", "CS3002", "CS3003")); List studentList = new ArrayList(); studentList.add(s1); @@ -28,32 +54,25 @@ public static void main(String[] args) { Predicate firstNameLength = Student -> (Student.getfName().length() <= 3); Predicate semPredicate = Student -> (Student.getSem() == 1); - Predicate deptPredicate = Student -> (Student.getDeptCode().equalsIgnoreCase("mec")); + Predicate deptPredicate = + Student -> (Student.getDeptCode().equalsIgnoreCase("mec")); - //Find out all the students based on firstNameLength predicate + // Find out all the students based on firstNameLength predicate System.out.println("Find out all the students based on firstNameLength predicate"); - studentList - .stream() - .filter(firstNameLength) - .forEach(System.out::println); + studentList.stream().filter(firstNameLength).forEach(System.out::println); - //Find all students from 1st Sem + // Find all students from 1st Sem System.out.println("Find all students from 1st Sem"); - studentList - .stream() - .filter(semPredicate) - .forEach(System.out::println); + studentList.stream().filter(semPredicate).forEach(System.out::println); - //Composite Predicate : All Students from CSE of First sem + // Composite Predicate : All Students from CSE of First sem System.out.println("Composite Predicate : All Students from CSE of First sem"); - studentList - .stream() + studentList.stream() .filter(semPredicate.or(deptPredicate.negate())) .forEach(System.out::println); - //Same as above - studentList - .stream() + // Same as above + studentList.stream() .filter(semPredicate) .filter(deptPredicate.negate()) .forEach(System.out::println); diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/F6ComparatorAsLambda.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/F6ComparatorAsLambda.java index 43daf529..1d710480 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/F6ComparatorAsLambda.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/F6ComparatorAsLambda.java @@ -1,22 +1,21 @@ package nitin.a6oops.interfaces.functionalInterface.PredefinedFunctionalInterfaces.sorting; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; -import java.util.Comparator; -import java.util.Set; -import java.util.TreeSet; - public class F6ComparatorAsLambda { public static void main(String[] args) { - Set students = new TreeSet(Comparator - .comparing(Student::getName) - .thenComparing(Student::getAge) - .thenComparing((Student s1) -> s1.getName().length()) - ); + Set students = + new TreeSet( + Comparator.comparing(Student::getName) + .thenComparing(Student::getAge) + .thenComparing((Student s1) -> s1.getName().length())); addElements(students); students.forEach(System.out::println); diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/SortingCollectionsJava8Way.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/SortingCollectionsJava8Way.java index 22b1a7a5..e289925a 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/SortingCollectionsJava8Way.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/PredefinedFunctionalInterfaces/sorting/SortingCollectionsJava8Way.java @@ -7,13 +7,18 @@ public class SortingCollectionsJava8Way { public static void main(String[] args) { - List list = Arrays.asList("I-5", "I-15", "I-25", "I-35", "I-45", - "I-55", "I-65", "I-75", "I-85", "I-95", "I-11", "I-22", "I-33"); + List list = + Arrays.asList( + "I-5", "I-15", "I-25", "I-35", "I-45", "I-55", "I-65", "I-75", "I-85", + "I-95", "I-11", "I-22", "I-33"); // Single Line Implementation - //Collections.sort(list, ((String a, String b) -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); + // Collections.sort(list, ((String a, String b) -> Integer.parseInt(a.substring(2)) - + // Integer.parseInt(b.substring(2)))); - Comparator comparator = (String a, String b) -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)); + Comparator comparator = + (String a, String b) -> + Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)); // Sorting in Natural Order Collections.sort(list, comparator); // Sorting in reversed order @@ -21,10 +26,10 @@ public static void main(String[] args) { // Sorting the list as a list of String. I-45 < I-5 < I-55 list.sort(Comparator.comparing(String::toString)); // Sorting in - //list.sort(Comparator.comparing(String::toString, (String a, String b) -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); + // list.sort(Comparator.comparing(String::toString, (String a, String b) -> + // Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); list.sort(Comparator.comparing(String::toString, comparator.reversed())); list.forEach(System.out::println); - } } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Animal.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Animal.java index 923d3d43..4f9e1cc6 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Animal.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Animal.java @@ -1,8 +1,6 @@ package nitin.a6oops.interfaces.functionalInterface.functionaInterfaceWithLambda; -/** - * Created by Nitin Chaurasia on 5/9/16 at 10:45 PM. - */ +/** Created by Nitin Chaurasia on 5/9/16 at 10:45 PM. */ public class Animal { private final String species; private final boolean canHop; @@ -24,8 +22,6 @@ public boolean isCanSwim() { @Override public String toString() { - return "Animal{" + - "species='" + species + '\'' + - '}'; + return "Animal{" + "species='" + species + '\'' + '}'; } } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/CheckTrait.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/CheckTrait.java index 43075dec..1b25d5b4 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/CheckTrait.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/CheckTrait.java @@ -1,14 +1,14 @@ package nitin.a6oops.interfaces.functionalInterface.functionaInterfaceWithLambda; /** - * Created by Nitin Chaurasia on 3/3/16 at 12:23 AM. - * If an interface contain only one abstract method, such type of interfaces are called functional - * interfaces and the method is called functional method or single abstract method (SAM). - *

- * Inside functional interface in addition to single Abstract method (SAM) we can write any number of - * default and static methods - *

- * Java 8 introduced @Functional Interface annotation + * Created by Nitin Chaurasia on 3/3/16 at 12:23 AM. If an interface contain only one abstract + * method, such type of interfaces are called functional interfaces and the method is called + * functional method or single abstract method (SAM). + * + *

Inside functional interface in addition to single Abstract method (SAM) we can write any + * number of default and static methods + * + *

Java 8 introduced @Functional Interface annotation */ @FunctionalInterface public interface CheckTrait { diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/FindMatchingAnimals.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/FindMatchingAnimals.java index 838d6ccf..ee22f836 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/FindMatchingAnimals.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/FindMatchingAnimals.java @@ -1,8 +1,6 @@ package nitin.a6oops.interfaces.functionalInterface.functionaInterfaceWithLambda; -/** - * Created by Nitin Chaurasia on 5/9/16 at 10:49 PM. - */ +/** Created by Nitin Chaurasia on 5/9/16 at 10:49 PM. */ public class FindMatchingAnimals { public static void main(String[] args) { @@ -12,7 +10,7 @@ public static void main(String[] args) { private static void print(Animal animal, CheckTrait trait) { if (trait.test(animal)) { - System.out.println(animal);//toString of Animal gets Printed + System.out.println(animal); // toString of Animal gets Printed } } } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Sprint.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Sprint.java index 4f67ec4b..1ff69c22 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Sprint.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/functionaInterfaceWithLambda/Sprint.java @@ -2,12 +2,11 @@ /** * Created by Nitin C on 3/5/2016. - *

- * Java compiler implicitly assumes any interface that contains exactly one abstract method as functional Interface + * + *

Java compiler implicitly assumes any interface that contains exactly one abstract method as + * functional Interface */ - @FunctionalInterface public interface Sprint { void sprint(Animal animal); - } diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO1MethodReference.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO1MethodReference.java index d9824527..6bb3ce9b 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO1MethodReference.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO1MethodReference.java @@ -5,13 +5,11 @@ interface Interf { void m1(); } -/** - * Created by Nitin Chaurasia on 1/30/18 at 10:30 PM. - */ +/** Created by Nitin Chaurasia on 1/30/18 at 10:30 PM. */ public class DCO1MethodReference { public static void main(String[] args) { Interf i = Test::m2; - i.m1();//Invokes m2 of Test Class + i.m1(); // Invokes m2 of Test Class } } @@ -20,4 +18,3 @@ public static void m2() { System.out.println("Method m2 from class Test"); } } - diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO2MethodReferenceRunnable.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO2MethodReferenceRunnable.java index 3b78c55c..e8f9b845 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO2MethodReferenceRunnable.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO2MethodReferenceRunnable.java @@ -1,8 +1,6 @@ package nitin.a6oops.interfaces.functionalInterface.methodNconstructorReference; -/** - * Created by Nitin Chaurasia on 1/30/18 at 10:43 PM. - */ +/** Created by Nitin Chaurasia on 1/30/18 at 10:43 PM. */ public class DCO2MethodReferenceRunnable { public static void main(String[] args) { @@ -26,7 +24,7 @@ public static void main(String[] args) { } } -//method m1 is like run method of Runnable class, in terms of arguments and return types +// method m1 is like run method of Runnable class, in terms of arguments and return types // This is non static method or instance Method class RunTest { public void m1() { @@ -34,4 +32,4 @@ public void m1() { System.out.println("Child thread"); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO3ConstructorReference.java b/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO3ConstructorReference.java index 49b3a4a7..a8a4deb0 100644 --- a/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO3ConstructorReference.java +++ b/src/main/java/nitin/a6oops/interfaces/functionalInterface/methodNconstructorReference/DCO3ConstructorReference.java @@ -1,8 +1,4 @@ package nitin.a6oops.interfaces.functionalInterface.methodNconstructorReference; -/** - * Created by Nitin Chaurasia on 1/30/18 at 10:51 PM. - */ -public class DCO3ConstructorReference { - -} +/** Created by Nitin Chaurasia on 1/30/18 at 10:51 PM. */ +public class DCO3ConstructorReference {} diff --git a/src/main/java/nitin/a6oops/polymorphism/ObjectComposition.java b/src/main/java/nitin/a6oops/polymorphism/ObjectComposition.java index 37168ad7..9210b1d6 100644 --- a/src/main/java/nitin/a6oops/polymorphism/ObjectComposition.java +++ b/src/main/java/nitin/a6oops/polymorphism/ObjectComposition.java @@ -1,14 +1,13 @@ package nitin.a6oops.polymorphism; /** - * Created by Nitin C on 3/5/2016. - * Object Composition is a property of constructing a class using references to other classes in order to reuse - * the functionality of other classes. - *

- * Object Composition is used to SIMULATE the polymorphic behaviour that cannot be achieved via single inheritance + * Created by Nitin C on 3/5/2016. Object Composition is a property of constructing a class using + * references to other classes in order to reuse the functionality of other classes. + * + *

Object Composition is used to SIMULATE the polymorphic behaviour that cannot be achieved via + * single inheritance */ -public class ObjectComposition { -} +public class ObjectComposition {} /* Composing a class Penguin that contains both of these objects and delegates its methods to them * One of the advantage of OC over Inheritance is greater code reuse. By using OC you gain access to other classes @@ -42,4 +41,4 @@ class WeddedFeet { public void kick() { System.out.println("The Wedded Feet kick to and fro"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/polymorphism/P1Basics.java b/src/main/java/nitin/a6oops/polymorphism/P1Basics.java index 26af6985..8492f26a 100644 --- a/src/main/java/nitin/a6oops/polymorphism/P1Basics.java +++ b/src/main/java/nitin/a6oops/polymorphism/P1Basics.java @@ -4,9 +4,7 @@ import java.util.LinkedList; import java.util.List; -/** - * Created by nitin on Sat, 1/14/17 at 6:36 PM. - */ +/** Created by nitin on Sat, 1/14/17 at 6:36 PM. */ public class P1Basics { public static void main(String[] args) { @@ -15,11 +13,12 @@ public static void main(String[] args) { List arrayList = new ArrayList(); // Always occurs with Inheritance with a special case - //child behaviour is changed hiding parent + // child behaviour is changed hiding parent // Treat an object of any subclass as if it were an object of parent class - // Dynamic binding makes polymorphism possible. Compiler is not able to resolve the call. Binding + // Dynamic binding makes polymorphism possible. Compiler is not able to resolve the call. + // Binding // id done at runtime // Binding : Relating a method call to a method diff --git a/src/main/java/nitin/a6oops/polymorphism/P3DynamicBinding.java b/src/main/java/nitin/a6oops/polymorphism/P3DynamicBinding.java index 200462af..8b9f0cb9 100644 --- a/src/main/java/nitin/a6oops/polymorphism/P3DynamicBinding.java +++ b/src/main/java/nitin/a6oops/polymorphism/P3DynamicBinding.java @@ -2,17 +2,17 @@ /** * Created by nitin.chaurasia on 3/4/2017. - *

- * Dynamic polymorphism in Java is achieved by method overriding - * As the method to call is determined at runtime, this is called dynamic binding or late binding. + * + *

Dynamic polymorphism in Java is achieved by method overriding As the method to call is + * determined at runtime, this is called dynamic binding or late binding. */ public class P3DynamicBinding { public static void main(String[] args) { Vehicle vh = new MotorBike(); - vh.move(); // prints MotorBike can move and accelerate too!! + vh.move(); // prints MotorBike can move and accelerate too!! vh = new Vehicle(); - vh.move(); // prints Vehicles can move!! + vh.move(); // prints Vehicles can move!! } } @@ -26,4 +26,4 @@ class MotorBike extends Vehicle { public void move() { System.out.println("MotorBike can move and accelerate too!!"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/polymorphism/overloading/P2StaticBinding.java b/src/main/java/nitin/a6oops/polymorphism/overloading/P2StaticBinding.java index afa7c485..9d263f68 100644 --- a/src/main/java/nitin/a6oops/polymorphism/overloading/P2StaticBinding.java +++ b/src/main/java/nitin/a6oops/polymorphism/overloading/P2StaticBinding.java @@ -2,56 +2,49 @@ /** * Created by nitin.chaurasia on 3/4/2017. - *

- * Static polymorphism in Java is achieved by method overloading - * compile time polymorphism or static binding - * uses type information (class in Java) for binding - * private, static, final, static variables } methods, not participation in polymorphism + * + *

Static polymorphism in Java is achieved by method overloading compile time polymorphism or + * static binding uses type information (class in Java) for binding private, static, final, static + * variables } methods, not participation in polymorphism */ public class P2StaticBinding { public static void main(String[] args) { DemoOverload demo = new DemoOverload(); - System.out.println(demo.add(2, 3)); //method 1 called + System.out.println(demo.add(2, 3)); // method 1 called - System.out.println(demo.add(2, 3, 4)); //method 2 called + System.out.println(demo.add(2, 3, 4)); // method 2 called - System.out.println(demo.add(2, 3.4)); //method 4 called + System.out.println(demo.add(2, 3.4)); // method 4 called - System.out.println(demo.add(2.5, 3)); //method 3 called + System.out.println(demo.add(2.5, 3)); // method 3 called // Detected during Complier time. CE: No suitable method found for add(String) - //System.out.print(demo.add("Nitin")); + // System.out.print(demo.add("Nitin")); } } class DemoOverload { - public int add(int x, int y) { //method 1 + public int add(int x, int y) { // method 1 return x + y; - } - public int add(int x, int y, int z) { //method 2 + public int add(int x, int y, int z) { // method 2 return x + y + z; - } - public int add(double x, int y) { //method 3 + public int add(double x, int y) { // method 3 return (int) x + y; - } - public int add(int x, double y) { //method 4 + public int add(int x, double y) { // method 4 return x + (int) y; - } - } - diff --git a/src/main/java/nitin/a6oops/polymorphism/overriding/P3DynamicBinding.java b/src/main/java/nitin/a6oops/polymorphism/overriding/P3DynamicBinding.java index 802535d7..3f5ec493 100644 --- a/src/main/java/nitin/a6oops/polymorphism/overriding/P3DynamicBinding.java +++ b/src/main/java/nitin/a6oops/polymorphism/overriding/P3DynamicBinding.java @@ -1,13 +1,11 @@ package nitin.a6oops.polymorphism.overriding; -/** - * Created by Nitin Chaurasia on 2/1/18 at 4:45 PM. - */ +/** Created by Nitin Chaurasia on 2/1/18 at 4:45 PM. */ public class P3DynamicBinding { public static void main(String[] args) { Parent p = new Child(); - p.m1();// dynamic binding, at run time, it invokes childs m1() + p.m1(); // dynamic binding, at run time, it invokes childs m1() } } @@ -21,4 +19,4 @@ class Child extends Parent { public void m1() { System.out.println("From Child"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/a6oops/polymorphism/overriding/P4CovariantReturn.java b/src/main/java/nitin/a6oops/polymorphism/overriding/P4CovariantReturn.java index 93d1901d..f3d36019 100644 --- a/src/main/java/nitin/a6oops/polymorphism/overriding/P4CovariantReturn.java +++ b/src/main/java/nitin/a6oops/polymorphism/overriding/P4CovariantReturn.java @@ -1,13 +1,10 @@ package nitin.a6oops.polymorphism.overriding; -/** - * Created by Nitin Chaurasia on 2/1/18 at 4:57 PM. - * From 1.5 Covariant Return type is Valid - */ +/** Created by Nitin Chaurasia on 2/1/18 at 4:57 PM. From 1.5 Covariant Return type is Valid */ public class P4CovariantReturn { public static void main(String[] args) { P p = new C(); - p.m1();// m1 of C to be called due to late binding + p.m1(); // m1 of C to be called due to late binding System.out.println("Testing Covariant return type"); } } @@ -19,8 +16,8 @@ public Object m1() { } class C extends P { - //Covariant return type (String is child of Object) + // Covariant return type (String is child of Object) public String m1() { return null; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/annotations/MoveToCommonLibrary.java b/src/main/java/nitin/annotations/MoveToCommonLibrary.java index 1a301cba..2101f53a 100644 --- a/src/main/java/nitin/annotations/MoveToCommonLibrary.java +++ b/src/main/java/nitin/annotations/MoveToCommonLibrary.java @@ -5,11 +5,9 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * Annotation to mark classes or methods that can be moved to a common library. - */ -@Retention(RetentionPolicy.SOURCE)//discarded by the compiler. +/** Annotation to mark classes or methods that can be moved to a common library. */ +@Retention(RetentionPolicy.SOURCE) // discarded by the compiler. @Target({ElementType.TYPE, ElementType.METHOD}) public @interface MoveToCommonLibrary { String description() default ""; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/annotations/MyCustomAnnotation.java b/src/main/java/nitin/annotations/MyCustomAnnotation.java index e8e6aa50..47a81e4d 100644 --- a/src/main/java/nitin/annotations/MyCustomAnnotation.java +++ b/src/main/java/nitin/annotations/MyCustomAnnotation.java @@ -1,6 +1,5 @@ package nitin.annotations; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -10,6 +9,8 @@ @Target(ElementType.FIELD) public @interface MyCustomAnnotation { String name(); + int value(); - String[] tags() default {}; // Default empty array -} \ No newline at end of file + + String[] tags() default {}; // Default empty array +} diff --git a/src/main/java/nitin/annotations/ReviewNeeded.java b/src/main/java/nitin/annotations/ReviewNeeded.java index 67c97174..253478ed 100644 --- a/src/main/java/nitin/annotations/ReviewNeeded.java +++ b/src/main/java/nitin/annotations/ReviewNeeded.java @@ -5,17 +5,22 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * This annotation marks classes or methods that need to be reviewed. - */ -@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD,ElementType.TYPE, ElementType.METHOD, ElementType.PACKAGE}) -@Retention(RetentionPolicy.SOURCE) //discarded by the compiler. +/** This annotation marks classes or methods that need to be reviewed. */ +@Target({ + ElementType.LOCAL_VARIABLE, + ElementType.FIELD, + ElementType.TYPE, + ElementType.METHOD, + ElementType.PACKAGE +}) +@Retention(RetentionPolicy.SOURCE) // discarded by the compiler. public @interface ReviewNeeded { String description() default ""; /** * The reviewers assigned to this class/method. + * * @return the list of reviewers */ String[] reviewers() default {"Nitin"}; // Using an array for compatibility diff --git a/src/main/java/nitin/annotations/run/AnnotationPrinter.java b/src/main/java/nitin/annotations/run/AnnotationPrinter.java index 4d856f59..53114e6f 100644 --- a/src/main/java/nitin/annotations/run/AnnotationPrinter.java +++ b/src/main/java/nitin/annotations/run/AnnotationPrinter.java @@ -2,7 +2,7 @@ public class AnnotationPrinter { public static void main(String[] args) { - //Via reflection, Class under test + // Via reflection, Class under test Class clazz = DocumentationAnnotationTest.class; // Check if the class is annotated with @ClassWriter diff --git a/src/main/java/nitin/annotations/run/Documentation.java b/src/main/java/nitin/annotations/run/Documentation.java index 4cdde444..8f5752e0 100644 --- a/src/main/java/nitin/annotations/run/Documentation.java +++ b/src/main/java/nitin/annotations/run/Documentation.java @@ -2,17 +2,20 @@ import java.lang.annotation.*; -/** - * Created by nitin on Monday, March/30/2020 at 11:51 PM - */ +/** Created by nitin on Monday, March/30/2020 at 11:51 PM */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Documentation { String author() default "Nitin K C"; + String date(); + int currentRevision() default 1; + String lastModified() default "N/A"; + String lastModifiedBy() default "N/A"; - String[] reviewers();// Note use of array + + String[] reviewers(); // Note use of array } diff --git a/src/main/java/nitin/annotations/run/DocumentationAnnotationTest.java b/src/main/java/nitin/annotations/run/DocumentationAnnotationTest.java index 9b1284f1..3c304a49 100644 --- a/src/main/java/nitin/annotations/run/DocumentationAnnotationTest.java +++ b/src/main/java/nitin/annotations/run/DocumentationAnnotationTest.java @@ -6,8 +6,7 @@ date = "Jan 02 2022", lastModified = "2024-08-22", lastModifiedBy = "John Doe", - reviewers = {"Alice", "Bob"} -) + reviewers = {"Alice", "Bob"}) @ToString public class DocumentationAnnotationTest { diff --git a/src/main/java/nitin/arrays/ArrayAsList.java b/src/main/java/nitin/arrays/ArrayAsList.java index 33004166..5fd5757d 100644 --- a/src/main/java/nitin/arrays/ArrayAsList.java +++ b/src/main/java/nitin/arrays/ArrayAsList.java @@ -3,17 +3,16 @@ import java.util.Arrays; import java.util.List; - public class ArrayAsList { public static void main(String[] nitin) { String[] a = {"one", "two", "three", "four"}; - String[] b = new String[]{"one", "two", "three", "four"};//another way of declaration + String[] b = new String[] {"one", "two", "three", "four"}; // another way of declaration - //String Array does not behave like regular arrays. contains method won't work - //a.contains("one");// cannot resolve method 'contains (java.lang.String)' + // String Array does not behave like regular arrays. contains method won't work + // a.contains("one");// cannot resolve method 'contains (java.lang.String)' - System.out.println(Arrays.asList(a).contains("two"));//true - System.out.println(Arrays.asList(a).contains("Nitin"));//false + System.out.println(Arrays.asList(a).contains("two")); // true + System.out.println(Arrays.asList(a).contains("Nitin")); // false // Arrays Class has method asList that converts Array into a List (or Arraylist) System.out.println(Arrays.asList(a)); diff --git a/src/main/java/nitin/arrays/L1Array1DDeclarationCreationInit.java b/src/main/java/nitin/arrays/L1Array1DDeclarationCreationInit.java index da7cab48..dc7ea1ee 100644 --- a/src/main/java/nitin/arrays/L1Array1DDeclarationCreationInit.java +++ b/src/main/java/nitin/arrays/L1Array1DDeclarationCreationInit.java @@ -1,8 +1,6 @@ package nitin.arrays; -/** - * Created by Nitin Chaurasia on 12/27/16 at 1:19 AM. - */ +/** Created by Nitin Chaurasia on 12/27/16 at 1:19 AM. */ public class L1Array1DDeclarationCreationInit { public static void main(String[] args) { // Three ways of Declaring @@ -10,13 +8,13 @@ public static void main(String[] args) { float[] b; int[] c; - //Allocation + // Allocation b = new float[3]; c = new int[2]; // Allocations & Assigmnment // a = {1,2,3,4,5};// Array initializer not allowed here - a = new int[]{1, 2, 3, 4, 5}; + a = new int[] {1, 2, 3, 4, 5}; // Assignment type 1 c[0] = 9; @@ -38,15 +36,13 @@ public static void main(String[] args) { System.out.println(); // Iteration using for each - for (int i : - d) { + for (int i : d) { System.out.print(i); System.out.print("\t"); } System.out.println(); - for (float i : - b) { + for (float i : b) { System.out.print(i); System.out.print("\t"); } diff --git a/src/main/java/nitin/arrays/L2Arrays2DRectangular.java b/src/main/java/nitin/arrays/L2Arrays2DRectangular.java index 6978bc93..c0d7bd2b 100644 --- a/src/main/java/nitin/arrays/L2Arrays2DRectangular.java +++ b/src/main/java/nitin/arrays/L2Arrays2DRectangular.java @@ -1,12 +1,10 @@ package nitin.arrays; -/** - * Created by nitin.chaurasia on 12/27/2016. - */ +/** Created by nitin.chaurasia on 12/27/2016. */ public class L2Arrays2DRectangular { public static void main(String[] args) { String[][] arr = new String[3][3]; - int row = arr.length;// Row = 6 + int row = arr.length; // Row = 6 int col = arr[0].length; // Columns = 7 for (int i = 0; i < row; i = i + 1) { for (int j = 0; j < col; j = j + 1) { diff --git a/src/main/java/nitin/arrays/L3Arrays2DSkewed.java b/src/main/java/nitin/arrays/L3Arrays2DSkewed.java index 428e168a..4b71dedb 100644 --- a/src/main/java/nitin/arrays/L3Arrays2DSkewed.java +++ b/src/main/java/nitin/arrays/L3Arrays2DSkewed.java @@ -1,21 +1,19 @@ package nitin.arrays; -/** - * Created by nitin.chaurasia on 12/27/2016. - */ +/** Created by nitin.chaurasia on 12/27/2016. */ public class L3Arrays2DSkewed { public static void main(String[] args) { String[][] arr = new String[3][]; - arr[0] = new String[3];//3 columns - arr[1] = new String[2];//2 columns - arr[2] = new String[5];//5 columns + arr[0] = new String[3]; // 3 columns + arr[1] = new String[2]; // 2 columns + arr[2] = new String[5]; // 5 columns int[][] a = {{1, 23, 3}, {1, 2}}; for (int i = 0; i < arr.length; i = i + 1) { - //each row has a diff column + // each row has a diff column for (int j = 0; j < arr[i].length; j = j + 1) { - //NOTICE: arr[i].length + // NOTICE: arr[i].length arr[i][j] = i + "" + j + " "; System.out.print(arr[i][j]); } @@ -24,9 +22,9 @@ public static void main(String[] args) { System.out.println("Printing 2D skewed declared and initialized together"); for (int i = 0; i < a.length; i = i + 1) { - //each row has a diff column + // each row has a diff column for (int j = 0; j < a[i].length; j = j + 1) { - //NOTICE: arr[i].length + // NOTICE: arr[i].length System.out.print(a[i][j]); System.out.print("\t"); } diff --git a/src/main/java/nitin/arrays/L4AnonymousArrays.java b/src/main/java/nitin/arrays/L4AnonymousArrays.java index f04e2b78..f549d66d 100644 --- a/src/main/java/nitin/arrays/L4AnonymousArrays.java +++ b/src/main/java/nitin/arrays/L4AnonymousArrays.java @@ -1,14 +1,14 @@ package nitin.arrays; /** - * Created by nitin.chaurasia on 12/27/2016. - * // Anonymous Array new[]{1,2,3}. We cant declare size as it will give CT error + * Created by nitin.chaurasia on 12/27/2016. // Anonymous Array new[]{1,2,3}. We cant declare size + * as it will give CT error */ public class L4AnonymousArrays { public static void main(String[] args) { - //passing anonymous array in sum method - sum(new int[]{3, 4, 5, 6, 7, 8, 9, 12}); + // passing anonymous array in sum method + sum(new int[] {3, 4, 5, 6, 7, 8, 9, 12}); } private static void sum(int[] arr) { diff --git a/src/main/java/nitin/arrays/L5ArrayElementAssignment.java b/src/main/java/nitin/arrays/L5ArrayElementAssignment.java index 2b4f5574..54120cd2 100644 --- a/src/main/java/nitin/arrays/L5ArrayElementAssignment.java +++ b/src/main/java/nitin/arrays/L5ArrayElementAssignment.java @@ -1,12 +1,10 @@ package nitin.arrays; /** - * Created by nitin.chaurasia on 12/27/2016. - * Array Type | Allowed elements - * 1. Primitive Type Arrays | Any type which can be implicitly promoted to declared type - * 2. Object Type Arrays | Either declared type objects or its child class objects - * 3. Abstract Class Type | Child class objects are allowed - * 4. Interface Type Arrays | Implementation class objects are allowed + * Created by nitin.chaurasia on 12/27/2016. Array Type | Allowed elements 1. Primitive Type Arrays + * | Any type which can be implicitly promoted to declared type 2. Object Type Arrays | Either + * declared type objects or its child class objects 3. Abstract Class Type | Child class objects are + * allowed 4. Interface Type Arrays | Implementation class objects are allowed */ public class L5ArrayElementAssignment { public static void main(String[] args) { @@ -25,7 +23,7 @@ public static void main(String[] args) { // Case 3 : Abstract Class Type Arrays. Elements can be of Child objects Number[] d = new Number[2]; - //d[0] = new Number();// abstract cannot be instantiated + // d[0] = new Number();// abstract cannot be instantiated d[0] = Integer.valueOf(10); d[1] = Double.valueOf(6.32); diff --git a/src/main/java/nitin/arrays/S3CharArrayToString.java b/src/main/java/nitin/arrays/S3CharArrayToString.java index e102d01c..08e03779 100644 --- a/src/main/java/nitin/arrays/S3CharArrayToString.java +++ b/src/main/java/nitin/arrays/S3CharArrayToString.java @@ -1,13 +1,11 @@ package nitin.arrays; -/** - * Created by Nitin C on 11/26/2015. - */ +/** Created by Nitin C on 11/26/2015. */ public class S3CharArrayToString { public static void main(String[] args) { char[] a = {'a', 'b', 'c'}; - //String constructor that takes charArray + // String constructor that takes charArray String data = new String(a); System.out.print(data); } diff --git a/src/main/java/nitin/arrays/SearchArrayTest.java b/src/main/java/nitin/arrays/SearchArrayTest.java index 792e1301..1b09de66 100644 --- a/src/main/java/nitin/arrays/SearchArrayTest.java +++ b/src/main/java/nitin/arrays/SearchArrayTest.java @@ -7,23 +7,26 @@ public class SearchArrayTest { public static void main(String[] args) { String[] list = {"zz", "ab", "cd", "ef", "gh", "ij", "kl", "mn", "op", "qr"}; - //BINARY SEARCH --> BINARY SEARCH WORKS ON SORTED ARRAYS,HERE IS BasicConnection TEST OF THAT + // BINARY SEARCH --> BINARY SEARCH WORKS ON SORTED ARRAYS,HERE IS BasicConnection TEST OF + // THAT System.out.println("Position of zz in Array = " + Arrays.binarySearch(list, "zz")); System.out.println("Position of ab in Array = " + Arrays.binarySearch(list, "ab")); - //SORTING ARRAY + // SORTING ARRAY Arrays.sort(list); - //BINARY SEARCH --> BINARY SEARCH WORKS ON SORTED ARRAYS + // BINARY SEARCH --> BINARY SEARCH WORKS ON SORTED ARRAYS System.out.println("zz = " + Arrays.binarySearch(list, "zz")); System.out.println("ab = " + Arrays.binarySearch(list, "ab")); - //REVERSE SORT + // REVERSE SORT Arrays.sort(list, new RevSortThruComparator()); -/* for (String i : friends) - System.out.print(i + " ");*/ + /* for (String i : friends) + System.out.print(i + " ");*/ - System.out.println("\nkl in rev Sort = " + Arrays.binarySearch(list, "kl", new RevSortThruComparator())); + System.out.println( + "\nkl in rev Sort = " + + Arrays.binarySearch(list, "kl", new RevSortThruComparator())); } } @@ -32,4 +35,3 @@ public int compare(String a, String b) { return b.compareTo(a); } } - diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/ConvertGSTtoEST.java b/src/main/java/nitin/calandarDateTime/java8Calandar/ConvertGSTtoEST.java index 2cb5632a..440bd2ff 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/ConvertGSTtoEST.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/ConvertGSTtoEST.java @@ -8,33 +8,42 @@ public class ConvertGSTtoEST { public static void main(String[] args) throws ParseException { - String inputDateTimePattern = "yyyy-MM-dd HH:mm:ssX"; //"yyyy-MM-dd HH:mm:ss.SSSSSSX"; + String inputDateTimePattern = "yyyy-MM-dd HH:mm:ssX"; // "yyyy-MM-dd HH:mm:ss.SSSSSSX"; String outputDateTimeFormat = "MM/dd/yyyy HH:mm z"; String toTimeZone = "America/New_York"; String startTime = "2024-03-10 04:00:00+00"; // Start time in GMT - String endTime = "2024-03-10 07:00:00+00"; // End time in GMT + String endTime = "2024-03-10 07:00:00+00"; // End time in GMT - //03/09/2024 23:00 EST - System.out.println(getFormattedOutputDateTimeString - (startTime, inputDateTimePattern, outputDateTimeFormat, toTimeZone)); - //03/10/2024 03:00 EDT - System.out.println(getFormattedOutputDateTimeString - (endTime, inputDateTimePattern, outputDateTimeFormat, toTimeZone)); + // 03/09/2024 23:00 EST + System.out.println( + getFormattedOutputDateTimeString( + startTime, inputDateTimePattern, outputDateTimeFormat, toTimeZone)); + // 03/10/2024 03:00 EDT + System.out.println( + getFormattedOutputDateTimeString( + endTime, inputDateTimePattern, outputDateTimeFormat, toTimeZone)); } - private static String getFormattedOutputDateTimeString(String dateTime, String inputDateTimePattern, String outputDateTimeFormat, String toTimeZone) { - //For the INPUT STRING (from DB or other service) - DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputDateTimePattern) - .withZone(ZoneOffset.UTC);//redundant if the input date-time string already contains the offset information (+00) - // useful when the String doesn't have Zone Id like mentioned "2024-03-10 07:00:00" and is assumed to be from UTC + private static String getFormattedOutputDateTimeString( + String dateTime, + String inputDateTimePattern, + String outputDateTimeFormat, + String toTimeZone) { + // For the INPUT STRING (from DB or other service) + DateTimeFormatter inputFormatter = + DateTimeFormatter.ofPattern(inputDateTimePattern) + .withZone( + ZoneOffset.UTC); // redundant if the input date-time string already + // contains the offset information (+00) + // useful when the String doesn't have Zone Id like mentioned "2024-03-10 07:00:00" and is + // assumed to be from UTC - //Output Formatter + // Output Formatter DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputDateTimeFormat); - return ZonedDateTime - .parse(dateTime, inputFormatter)//Returns ZonedDateTime - .withZoneSameInstant(ZoneId.of(toTimeZone))//return converted ZonedDateTime - .format(outputFormatter);// returns formatted String + return ZonedDateTime.parse(dateTime, inputFormatter) // Returns ZonedDateTime + .withZoneSameInstant(ZoneId.of(toTimeZone)) // return converted ZonedDateTime + .format(outputFormatter); // returns formatted String } } diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversion.java b/src/main/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversion.java index 4b7cf5cc..3210de0d 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversion.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversion.java @@ -1,23 +1,18 @@ package nitin.calandarDateTime.java8Calandar; -import com.utilities.ZonedDateTimeUtility; - -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.zone.ZoneRulesException; - import static com.utilities.ZonedDateTimeUtility.getFormattedTimezoneString; import static com.utilities.ZonedDateTimeUtility.getZonedDateTime; + +import com.utilities.ZonedDateTimeUtility; import com.utilities.ZonedDateTimeUtility.Result; +import java.time.format.DateTimeFormatter; + public class GmtToEstFormattedConversion { static String outputSameDateFormat = "HH:mm zzz"; static String outputDiffDateFormat = "MM/dd/yyyy HH:mm zzz"; static String inputDateTimePattern = "yyyy-MM-dd HH:mm:ssX"; - - //CHECK THE TEST CASES + // CHECK THE TEST CASES public static void main(String[] args) { String startDateTime = "2024-03-22 03:04:44.512320+00"; String endDateTime = "2024-03-22 04:44:44.512320+00"; @@ -26,7 +21,8 @@ public static void main(String[] args) { run(startDateTime, endDateTime, timeZoneIso); } - public static ZonedDateTimeUtility.Result run(String startDateTime, String endDateTime, String timeZoneIso) { + public static ZonedDateTimeUtility.Result run( + String startDateTime, String endDateTime, String timeZoneIso) { if (null == startDateTime) { startDateTime = ""; } @@ -41,12 +37,19 @@ public static ZonedDateTimeUtility.Result run(String startDateTime, String endDa } if (!startDateTime.isEmpty() && endDateTime.isEmpty()) { - result = new ZonedDateTimeUtility.Result(getReturnDateTimeFormat(startDateTime, timeZoneIso, outputDiffDateFormat) - , endDateTime); + result = + new ZonedDateTimeUtility.Result( + getReturnDateTimeFormat( + startDateTime, timeZoneIso, outputDiffDateFormat), + endDateTime); } if (startDateTime.isEmpty() && !endDateTime.isEmpty()) { - result = new Result(startDateTime, getReturnDateTimeFormat(endDateTime, timeZoneIso, outputDiffDateFormat)); + result = + new Result( + startDateTime, + getReturnDateTimeFormat( + endDateTime, timeZoneIso, outputDiffDateFormat)); } if (!startDateTime.isEmpty() && !endDateTime.isEmpty()) { @@ -56,8 +59,10 @@ public static ZonedDateTimeUtility.Result run(String startDateTime, String endDa return result; } - private static String getReturnDateTimeFormat(String dateTime, String timeZoneIso, String dateformat) { - //Outgoing DateTime format - return getZonedDateTime(dateTime, timeZoneIso).format(DateTimeFormatter.ofPattern(dateformat)); + private static String getReturnDateTimeFormat( + String dateTime, String timeZoneIso, String dateformat) { + // Outgoing DateTime format + return getZonedDateTime(dateTime, timeZoneIso) + .format(DateTimeFormatter.ofPattern(dateformat)); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/L1LocalDateTime.java b/src/main/java/nitin/calandarDateTime/java8Calandar/L1LocalDateTime.java index 0248324e..5add6f85 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/L1LocalDateTime.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/L1LocalDateTime.java @@ -5,10 +5,7 @@ import java.time.Month; import java.time.format.DateTimeFormatter; -/** - * Created by nichaurasia on Saturday, April/25/2020 at 9:57 PM - */ - +/** Created by nichaurasia on Saturday, April/25/2020 at 9:57 PM */ public class L1LocalDateTime { public static void main(String[] args) { LocalDateTime d = LocalDateTime.now(); @@ -22,13 +19,13 @@ public static void main(String[] args) { int min = d.getMinute(); int sec = d.getSecond(); int nanoSec = d.getNano(); - System.out.println(dayOfWeek + ", " + date + "/" + mon + "(" + mm + ")/" - + year + " T " + hour + ":" + min + ":" + sec + "." + nanoSec); + System.out.println( + dayOfWeek + ", " + date + "/" + mon + "(" + mm + ")/" + year + " T " + hour + ":" + + min + ":" + sec + "." + nanoSec); LocalDateTime now = LocalDateTime.now(); - String formattedDateTime = now - .format(DateTimeFormatter.ofPattern("EEEE, dd/MMM(yyyy) HH:mm:ss.n")); + String formattedDateTime = + now.format(DateTimeFormatter.ofPattern("EEEE, dd/MMM(yyyy) HH:mm:ss.n")); System.out.println(formattedDateTime); - } } diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/L2LocalDateTimeAdd.java b/src/main/java/nitin/calandarDateTime/java8Calandar/L2LocalDateTimeAdd.java index bcd0dfbe..fd00a8e8 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/L2LocalDateTimeAdd.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/L2LocalDateTimeAdd.java @@ -3,10 +3,7 @@ import java.time.LocalDateTime; import java.time.Month; -/** - * Created by nichaurasia on Saturday, April/25/2020 at 10:29 PM - */ - +/** Created by nichaurasia on Saturday, April/25/2020 at 10:29 PM */ public class L2LocalDateTimeAdd { public static void main(String[] args) { LocalDateTime dt = LocalDateTime.of(1985, Month.JUNE, 11, 0, 0, 0); diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/L3Period.java b/src/main/java/nitin/calandarDateTime/java8Calandar/L3Period.java index 24d3ecd4..369501b4 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/L3Period.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/L3Period.java @@ -4,10 +4,7 @@ import java.time.Month; import java.time.Period; -/** - * Created by nichaurasia on Saturday, April/25/2020 at 10:37 PM - */ - +/** Created by nichaurasia on Saturday, April/25/2020 at 10:37 PM */ public class L3Period { public static void main(String[] args) { LocalDate birthday = LocalDate.of(1985, Month.JUNE, 11); @@ -15,7 +12,8 @@ public static void main(String[] args) { Period p = Period.between(birthday, now); System.out.println("Number of days"); - System.out.println(p.getYears() + " Years " + p.getMonths() + " Months " + p.getDays() + " Days"); + System.out.println( + p.getYears() + " Years " + p.getMonths() + " Months " + p.getDays() + " Days"); System.out.println(p); } } diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/L4Year.java b/src/main/java/nitin/calandarDateTime/java8Calandar/L4Year.java index 0cc5c115..65522a5a 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/L4Year.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/L4Year.java @@ -4,9 +4,7 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by nitin on Saturday, April/25/2020 at 11:51 PM - */ +/** Created by nitin on Saturday, April/25/2020 at 11:51 PM */ public class L4Year { public static void main(String[] args) { diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/L5ZonedDateTime.java b/src/main/java/nitin/calandarDateTime/java8Calandar/L5ZonedDateTime.java index bfab1d24..f507bb57 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/L5ZonedDateTime.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/L5ZonedDateTime.java @@ -4,13 +4,11 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -/** - * Created by nitin on Sunday, April/26/2020 at 12:04 AM - */ +/** Created by nitin on Sunday, April/26/2020 at 12:04 AM */ public class L5ZonedDateTime { public static void main(String[] args) { String myDateTimePattern = "E dd.MM.yyyy HH:MM:SSS a z v"; - //myDateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + // myDateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; ZoneId zone = ZoneId.systemDefault(); ZoneId india = ZoneId.of("Asia/Kolkata"); @@ -19,20 +17,26 @@ public static void main(String[] args) { ZonedDateTime timeInIndia = ZonedDateTime.now(india); System.out.print("Time in " + zone + " : "); - System.out.println(timeInTheCityWhereCodeIsExecuted.format(DateTimeFormatter.ofPattern(myDateTimePattern))); + System.out.println( + timeInTheCityWhereCodeIsExecuted.format( + DateTimeFormatter.ofPattern(myDateTimePattern))); System.out.print("Time in India : "); System.out.println(timeInIndia.format(DateTimeFormatter.ofPattern(myDateTimePattern))); - if (null != timeInTheCityWhereCodeIsExecuted && timeInTheCityWhereCodeIsExecuted.isAfter(timeInIndia)) { + if (null != timeInTheCityWhereCodeIsExecuted + && timeInTheCityWhereCodeIsExecuted.isAfter(timeInIndia)) { System.out.println("...1...EXCEPTION Start date should not less than Stop date"); } - if (timeInTheCityWhereCodeIsExecuted.toLocalDate().isBefore(timeInIndia.toLocalDate())) {//Considering the Date part only + if (timeInTheCityWhereCodeIsExecuted + .toLocalDate() + .isBefore(timeInIndia.toLocalDate())) { // Considering the Date part only System.out.println("...2...Start date IS BEFORE Stop date"); } - if (timeInTheCityWhereCodeIsExecuted.toLocalDate().isEqual(timeInIndia.toLocalDate())) {//Considering the Date part only + if (timeInTheCityWhereCodeIsExecuted + .toLocalDate() + .isEqual(timeInIndia.toLocalDate())) { // Considering the Date part only System.out.println("...3...Start date IS EQUAL Stop date"); } - } } diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/StringToTimeStamp.java b/src/main/java/nitin/calandarDateTime/java8Calandar/StringToTimeStamp.java index dad8b2b5..32be491d 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/StringToTimeStamp.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/StringToTimeStamp.java @@ -1,7 +1,5 @@ package nitin.calandarDateTime.java8Calandar; -import org.apache.commons.lang3.StringUtils; - import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -10,6 +8,7 @@ import java.util.Date; import java.util.Optional; import java.util.TimeZone; +import org.apache.commons.lang3.StringUtils; public class StringToTimeStamp { public static void main(String[] args) { @@ -35,8 +34,7 @@ private static Timestamp extractDate(String date) { private static Timestamp extractDateOld(String date) { final String dateFormat = "dd-MM-yyyy"; - if (StringUtils.isBlank(date)) - return null; + if (StringUtils.isBlank(date)) return null; try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/TestingProcessors.java b/src/main/java/nitin/calandarDateTime/java8Calandar/TestingProcessors.java index f6b7f578..ef984fd6 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/TestingProcessors.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/TestingProcessors.java @@ -13,25 +13,26 @@ public static void main(String[] args) { ZonedDateTime time = ZonedDateTime.now(); System.out.println(getTimesBasedOnCity(time, time.getOffset().getId())); - String standardTimeFormat = "2024-03-10T04:00:00+00"; ZonedDateTime zonedDateTime = ZonedDateTime.parse(standardTimeFormat); System.out.println(getTimesBasedOnCity(zonedDateTime, zonedDateTime.getOffset().getId())); - //If time is in any other format + // If time is in any other format String inputDateTimePattern = "yyyy-MM-dd HH:mm:ssZ"; String timeInUserDefinedFormat = "2024-03-10 04:00:00+0530"; - ZonedDateTime zonedDateTimeUserFormatted = ZonedDateTime - .parse(timeInUserDefinedFormat, DateTimeFormatter.ofPattern(inputDateTimePattern)); - - System.out.println(getTimesBasedOnCity(zonedDateTimeUserFormatted, - zonedDateTimeUserFormatted.getOffset().getId())); + ZonedDateTime zonedDateTimeUserFormatted = + ZonedDateTime.parse( + timeInUserDefinedFormat, DateTimeFormatter.ofPattern(inputDateTimePattern)); + + System.out.println( + getTimesBasedOnCity( + zonedDateTimeUserFormatted, + zonedDateTimeUserFormatted.getOffset().getId())); } public static ZonedDateTime getTimesBasedOnCity(ZonedDateTime dateTime, String cityTimeZone) { - return dateTime - .with(LocalTime.MAX) + return dateTime.with(LocalTime.MAX) .withZoneSameInstant(ZoneId.of(cityTimeZone)) .truncatedTo(ChronoUnit.MILLIS); } diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/ZDCTests.java b/src/main/java/nitin/calandarDateTime/java8Calandar/ZDCTests.java index 63550271..3402774d 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/ZDCTests.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/ZDCTests.java @@ -1,25 +1,25 @@ package nitin.calandarDateTime.java8Calandar; +import static com.utilities.ZonedDateTimeUtility.zonedDateTimeStr; + import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; -import static com.utilities.ZonedDateTimeUtility.zonedDateTimeStr; - public class ZDCTests { public static void main(String[] args) { - //TimeZone - ZoneId zone = ZoneId.systemDefault();//Uses Z for UTC - ZoneId india = ZoneId.of("Asia/Kolkata");//UTC+05:30 + // TimeZone + ZoneId zone = ZoneId.systemDefault(); // Uses Z for UTC + ZoneId india = ZoneId.of("Asia/Kolkata"); // UTC+05:30 ZoneId chicago = ZoneId.of("US/Central"); ZoneId ny = ZoneId.of("UTC-05:00"); - System.out.println(ZoneOffset.SHORT_IDS.get("IST"));//ZoneOffset doesn't count Daylight savings - //ZoneId.getAvailableZoneIds().stream().forEach(x -> System.out.println(x)); + System.out.println( + ZoneOffset.SHORT_IDS.get("IST")); // ZoneOffset doesn't count Daylight savings + // ZoneId.getAvailableZoneIds().stream().forEach(x -> System.out.println(x)); ZonedDateTime timeChicago = ZonedDateTime.now(chicago); System.out.println("Time in Chicago : " + timeChicago); @@ -30,11 +30,10 @@ public static void main(String[] args) { ZonedDateTime timeIndia = ZonedDateTime.now(india); System.out.println("Time in India : " + timeIndia); - //ZoneOffset.SHORT_IDS.forEach((key, value) -> System.out.println(key + " : "+ value)); + // ZoneOffset.SHORT_IDS.forEach((key, value) -> System.out.println(key + " : "+ value)); System.out.println("============================================"); System.out.println(zonedDateTimeStr(timeUTC)); System.out.println(zonedDateTimeStr(null)); - } public static ZonedDateTime getFacilityTime(String pdInactiveDate, String facilityZone) { diff --git a/src/main/java/nitin/calandarDateTime/java8Calandar/ZonedDateTimeTest.java b/src/main/java/nitin/calandarDateTime/java8Calandar/ZonedDateTimeTest.java index 1a97e98f..3ee9dbef 100644 --- a/src/main/java/nitin/calandarDateTime/java8Calandar/ZonedDateTimeTest.java +++ b/src/main/java/nitin/calandarDateTime/java8Calandar/ZonedDateTimeTest.java @@ -1,7 +1,6 @@ package nitin.calandarDateTime.java8Calandar; import java.sql.Timestamp; -import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Optional; @@ -12,21 +11,30 @@ public static void main(String[] args) { ZonedDateTime startDate = ZonedDateTime.parse("2021-05-05T23:55:19.413Z"); ZonedDateTime stopDate = ZonedDateTime.parse("2021-05-05T23:55:19.413Z"); - - System.out.println(enterDate.toLocalDate());//Taking only the date part + System.out.println(enterDate.toLocalDate()); // Taking only the date part if (null != stopDate && startDate.isAfter(stopDate)) { System.out.println("...1...EXCEPTION Start date should not less than Stop date"); } - if (startDate.toLocalDate().isBefore(enterDate.toLocalDate())) {//Considering the Date part only + if (startDate + .toLocalDate() + .isBefore(enterDate.toLocalDate())) { // Considering the Date part only System.out.println("...2...Start date IS BEFORE Stop date"); } - if (startDate.toLocalDate().isEqual(enterDate.toLocalDate())) {//Considering the Date part only + if (startDate + .toLocalDate() + .isEqual(enterDate.toLocalDate())) { // Considering the Date part only System.out.println("...3...Start date IS EQUAL Stop date"); } - ZonedDateTime start = ZonedDateTime.parse("2022-03-08T11:20:48.854+0530", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - ZonedDateTime stop = ZonedDateTime.parse("2022-03-07T23:50:48.854-0600", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + ZonedDateTime start = + ZonedDateTime.parse( + "2022-03-08T11:20:48.854+0530", + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + ZonedDateTime stop = + ZonedDateTime.parse( + "2022-03-07T23:50:48.854-0600", + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); if (startDate.toLocalDate().isEqual(enterDate.toLocalDate())) { System.out.println("...1...EXCEPTION Start date should not less than Stop date"); @@ -37,11 +45,20 @@ public static void main(String[] args) { } System.out.println("###################################################"); - ZonedDateTime approvalStartDate = ZonedDateTime.parse("2022-03-01T23:00:00.000-0530", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));//2022-03-31 22:59:59.999, 2022-02-28 23:00:00.000 + ZonedDateTime approvalStartDate = + ZonedDateTime.parse( + "2022-03-01T23:00:00.000-0530", + DateTimeFormatter.ofPattern( + "yyyy-MM-dd'T'HH:mm:ss.SSSZ")); // 2022-03-31 22:59:59.999, + // 2022-02-28 23:00:00.000 ZonedDateTime approvalEndDate = ZonedDateTime.parse("2022-04-01T03:59:59.999Z"); - System.out.println("Approval Start Date: " + approvalStartDate.toLocalDate().toString().replace("-", "/")); - System.out.println("Approval Start Date: " + approvalStartDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))); + System.out.println( + "Approval Start Date: " + + approvalStartDate.toLocalDate().toString().replace("-", "/")); + System.out.println( + "Approval Start Date: " + + approvalStartDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))); System.out.println("###################################################"); diff --git a/src/main/java/nitin/calandarDateTime/jodaTime/NFridays.java b/src/main/java/nitin/calandarDateTime/jodaTime/NFridays.java index 15cbbae7..ed3063b5 100644 --- a/src/main/java/nitin/calandarDateTime/jodaTime/NFridays.java +++ b/src/main/java/nitin/calandarDateTime/jodaTime/NFridays.java @@ -1,26 +1,22 @@ package nitin.calandarDateTime.jodaTime; import com.utilities.OldDateUtilities; +import java.util.List; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; -import java.util.List; - -/** - * Created by nichaurasia on Wednesday, May/06/2020 at 5:54 PM - */ - +/** Created by nichaurasia on Wednesday, May/06/2020 at 5:54 PM */ public class NFridays { public static void main(String[] args) { DateTimeFormatter dateFormat = DateTimeFormat.forPattern("E,d Y"); - //.forPattern("G,C,Y,x,w,e,E,Y,D,M,d,a,K,h,H,k,m,s,S,z,Z"); + // .forPattern("G,C,Y,x,w,e,E,Y,D,M,d,a,K,h,H,k,m,s,S,z,Z"); List list = OldDateUtilities.findLastNFridaysJodaTime(5); if (list != null) { for (DateTime d : list) { - //System.out.println(dateFormat.print(d)); + // System.out.println(dateFormat.print(d)); System.out.println(d.toString(DateTimeFormat.fullDateTime())); } } diff --git a/src/main/java/nitin/calandarDateTime/old/DateFormatting.java b/src/main/java/nitin/calandarDateTime/old/DateFormatting.java index ea422c8c..47728ac2 100644 --- a/src/main/java/nitin/calandarDateTime/old/DateFormatting.java +++ b/src/main/java/nitin/calandarDateTime/old/DateFormatting.java @@ -3,9 +3,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; -/** - * Created by nichaurasia on Friday, March/27/2020 at 1:13 AM - */ +/** Created by nichaurasia on Friday, March/27/2020 at 1:13 AM */ /* G Era designator Text AD @@ -39,8 +37,7 @@ public static void main(String[] args) { formatter = new SimpleDateFormat("MMddyyyy_HHmm"); System.out.println(formatter.format(System.currentTimeMillis())); - formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.Z"); System.out.println(formatter.format(System.currentTimeMillis())); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/calandarDateTime/old/DateFormattingNew.java b/src/main/java/nitin/calandarDateTime/old/DateFormattingNew.java index 6c4fc0e0..e9731f6f 100644 --- a/src/main/java/nitin/calandarDateTime/old/DateFormattingNew.java +++ b/src/main/java/nitin/calandarDateTime/old/DateFormattingNew.java @@ -1,7 +1,6 @@ package nitin.calandarDateTime.old; import com.fasterxml.jackson.annotation.JsonFormat; - import java.sql.Timestamp; public class DateFormattingNew { diff --git a/src/main/java/nitin/calandarDateTime/old/GetAge.java b/src/main/java/nitin/calandarDateTime/old/GetAge.java index ffba16a6..d5e29077 100644 --- a/src/main/java/nitin/calandarDateTime/old/GetAge.java +++ b/src/main/java/nitin/calandarDateTime/old/GetAge.java @@ -2,13 +2,9 @@ import com.utilities.OldDateUtilities; import com.utilities.TimeStampUtilities; - import java.sql.Date; -/** - * Created by nichaurasia on Saturday, April/25/2020 at 4:15 AM - */ - +/** Created by nichaurasia on Saturday, April/25/2020 at 4:15 AM */ public class GetAge { public static void main(String[] args) { int age = TimeStampUtilities.getAgeFromBrithDate("1985-06-11"); @@ -16,8 +12,8 @@ public static void main(String[] args) { Date d1 = new Date(2020, 04, 25); Date d2 = new Date(1985, 06, 11); - //Timestamp d1 = DateUtilities.getDate("04252020"); - //Timestamp d2 = DateUtilities.getDate("06111985");\ + // Timestamp d1 = DateUtilities.getDate("04252020"); + // Timestamp d2 = DateUtilities.getDate("06111985");\ long days = OldDateUtilities.daysBetween(d2, d1); System.out.println(days); } diff --git a/src/main/java/nitin/calandarDateTime/old/GetAllWeekendsOfYear.java b/src/main/java/nitin/calandarDateTime/old/GetAllWeekendsOfYear.java index f450c982..b4036c93 100644 --- a/src/main/java/nitin/calandarDateTime/old/GetAllWeekendsOfYear.java +++ b/src/main/java/nitin/calandarDateTime/old/GetAllWeekendsOfYear.java @@ -1,16 +1,12 @@ package nitin.calandarDateTime.old; import com.utilities.OldDateUtilities; - import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; -/** - * Created by nichaurasia on Saturday, April/25/2020 at 2:48 AM - */ - +/** Created by nichaurasia on Saturday, April/25/2020 at 2:48 AM */ public class GetAllWeekendsOfYear { public static void main(String[] args) throws ParseException { List list = OldDateUtilities.getWeekendsInAYear(2008); @@ -18,10 +14,8 @@ public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(datePattern); Date tempDate = null; for (Date date : list) { - //tempDate = sdf.format(date); + // tempDate = sdf.format(date); System.out.println(sdf.format(date)); } } } - - diff --git a/src/main/java/nitin/calandarDateTime/old/GetFirstNLastDayOfMonth.java b/src/main/java/nitin/calandarDateTime/old/GetFirstNLastDayOfMonth.java index c6778594..672075f4 100644 --- a/src/main/java/nitin/calandarDateTime/old/GetFirstNLastDayOfMonth.java +++ b/src/main/java/nitin/calandarDateTime/old/GetFirstNLastDayOfMonth.java @@ -18,10 +18,10 @@ public static Date getFirstDateOfMonth(int beginMonth) { Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime(); - //Find out the First day of the begin month + // Find out the First day of the begin month calendar.set(Calendar.YEAR, beginMonth - 1, 1); - //calendar.setTime(date); + // calendar.setTime(date); int day = calendar.getActualMinimum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); @@ -34,12 +34,12 @@ private static Date getLastDateOfMonth(int endMonth) { calendar.set(Calendar.YEAR, endMonth - 1, 1); - //calendar.setTime(date); + // calendar.setTime(date); int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day); - //calendar.set(Calendar.YEAR, year); + // calendar.set(Calendar.YEAR, year); - //return SimpleDateFormat("MM/dd/yyyy").format(calendar.getTime()); + // return SimpleDateFormat("MM/dd/yyyy").format(calendar.getTime()); return calendar.getTime(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/calandarDateTime/old/GetFutureDates.java b/src/main/java/nitin/calandarDateTime/old/GetFutureDates.java index 3f329a3b..e101d810 100644 --- a/src/main/java/nitin/calandarDateTime/old/GetFutureDates.java +++ b/src/main/java/nitin/calandarDateTime/old/GetFutureDates.java @@ -1,15 +1,12 @@ package nitin.calandarDateTime.old; import com.utilities.OldDateUtilities; - import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; -/** - * Created by nitin on Wednesday, May/06/2020 at 5:33 PM - */ +/** Created by nitin on Wednesday, May/06/2020 at 5:33 PM */ public class GetFutureDates { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); @@ -23,11 +20,11 @@ public static void main(String[] args) { System.out.println("Current Time : "); System.out.println(sdf.format(authTimestamp)); - //Find a date 30 days from Now and then 365 days from that day + // Find a date 30 days from Now and then 365 days from that day calendar.add(Calendar.DATE, 30); Date poiBeginDate = calendar.getTime(); poiBeginDate = OldDateUtilities.nullifyTime(poiBeginDate); - //Add 12 months from one month of the current Date + // Add 12 months from one month of the current Date calendar.add(Calendar.DATE, 365); Date poiEndDate = calendar.getTime(); poiEndDate = OldDateUtilities.nullifyTime(poiEndDate); diff --git a/src/main/java/nitin/calandarDateTime/old/GetNextMonthsNYearDates.java b/src/main/java/nitin/calandarDateTime/old/GetNextMonthsNYearDates.java index 28e32d05..4d4b4d50 100644 --- a/src/main/java/nitin/calandarDateTime/old/GetNextMonthsNYearDates.java +++ b/src/main/java/nitin/calandarDateTime/old/GetNextMonthsNYearDates.java @@ -1,15 +1,11 @@ package nitin.calandarDateTime.old; import com.utilities.OldDateUtilities; - import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; -/** - * Created by nichaurasia on Thursday, April/23/2020 at 10:57 AM - */ - +/** Created by nichaurasia on Thursday, April/23/2020 at 10:57 AM */ public class GetNextMonthsNYearDates { public static void main(String[] args) { @@ -24,11 +20,11 @@ public static void main(String[] args) { If Current Date Dt: 04/17/2020 POI -> 05/17/2020 to 05/16/2021. */ - //Add one month to the current Date + // Add one month to the current Date calendar.add(Calendar.MONTH, 1); Date poiBeginDate = calendar.getTime(); poiBeginDate = OldDateUtilities.nullifyTime(poiBeginDate); - //Add 12 months from one month of the current Date + // Add 12 months from one month of the current Date calendar.add(Calendar.MONTH, 12); calendar.add(Calendar.DATE, -1); Date poiEndDate = calendar.getTime(); diff --git a/src/main/java/nitin/calandarDateTime/old/GetPreviousNFridays.java b/src/main/java/nitin/calandarDateTime/old/GetPreviousNFridays.java index 6ccf3c58..30852545 100644 --- a/src/main/java/nitin/calandarDateTime/old/GetPreviousNFridays.java +++ b/src/main/java/nitin/calandarDateTime/old/GetPreviousNFridays.java @@ -1,15 +1,12 @@ package nitin.calandarDateTime.old; import com.utilities.OldDateUtilities; - import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; -/** - * Created by nitin on Monday, April/27/2020 at 2:45 PM - */ +/** Created by nitin on Monday, April/27/2020 at 2:45 PM */ public class GetPreviousNFridays { public static void main(String[] args) throws ParseException { List list = OldDateUtilities.getLastNFridays(3); @@ -17,7 +14,7 @@ public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(datePattern); Date tempDate = null; for (Date date : list) { - //tempDate = sdf.format(date); + // tempDate = sdf.format(date); System.out.println(sdf.format(date)); } } diff --git a/src/main/java/nitin/calandarDateTime/old/TimeTest.java b/src/main/java/nitin/calandarDateTime/old/TimeTest.java index cafc6708..463a16f4 100644 --- a/src/main/java/nitin/calandarDateTime/old/TimeTest.java +++ b/src/main/java/nitin/calandarDateTime/old/TimeTest.java @@ -14,10 +14,9 @@ public static void main(String[] args) throws ParseException { map.put("END_DATE", "2019-11-21"); Timestamp endDate; -// Optional.ofNullable((String) map.get(("END_DATE"))) -// .map(obj -> String.valueOf(obj)) -// .ifPresent(obj -> System.out.println(Timestamp.valueOf(obj))); - + // Optional.ofNullable((String) map.get(("END_DATE"))) + // .map(obj -> String.valueOf(obj)) + // .ifPresent(obj -> System.out.println(Timestamp.valueOf(obj))); DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd"); // you can change format of date diff --git a/src/main/java/nitin/classLoadingJVM/ClassLoading.java b/src/main/java/nitin/classLoadingJVM/ClassLoading.java index 1f5c3631..798884db 100644 --- a/src/main/java/nitin/classLoadingJVM/ClassLoading.java +++ b/src/main/java/nitin/classLoadingJVM/ClassLoading.java @@ -1,6 +1,5 @@ package nitin.classLoadingJVM; - class Car { static Integer numberofwheels = 4; @@ -10,7 +9,7 @@ class Car { static { // Static block 1 System.out.println("********** Static Block 1 **********************"); System.out.println(numberofwheels++); - //enginecapacity++;//Not Accessible here + // enginecapacity++;//Not Accessible here } static { // Static Block 2 @@ -18,7 +17,7 @@ class Car { System.out.println(numberofwheels++); } - private Integer enginecapacity = 0;//If not initiazlized, then constructor gived NPE + private Integer enginecapacity = 0; // If not initiazlized, then constructor gived NPE public Car() { System.out.println("********** Default Constructor of class **********************"); @@ -29,4 +28,4 @@ public Car() { public static void main(String[] args) { Car c = new Car(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/AllObjectsCreatedInTheHeap.java b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/AllObjectsCreatedInTheHeap.java index faf07335..ab1c1ce1 100644 --- a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/AllObjectsCreatedInTheHeap.java +++ b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/AllObjectsCreatedInTheHeap.java @@ -4,8 +4,7 @@ public class AllObjectsCreatedInTheHeap { public static void main(String[] args) { int a = 0; // All local variables Created in the Stack - //Objects are Stored in the Heap Area. The reference to the variable is stored in the stack + // Objects are Stored in the Heap Area. The reference to the variable is stored in the stack String str = "Nitin"; - } } diff --git a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/ChangeFinal.java b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/ChangeFinal.java index ec2dc686..e16f57da 100644 --- a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/ChangeFinal.java +++ b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/ChangeFinal.java @@ -1,8 +1,8 @@ package nitin.classLoadingJVM.javaMemoryModel; /** - * Created by Nitin Chaurasia on 12/29/16 at 12:51 AM. - * Final is applicable for classes, methods and variables + * Created by Nitin Chaurasia on 12/29/16 at 12:51 AM. Final is applicable for classes, methods and + * variables */ public class ChangeFinal { public static void main(String[] args) { @@ -10,7 +10,8 @@ public static void main(String[] args) { final Customer c = new Customer("Mahatma Gandhi"); System.out.println("Final String is : " + c); - // CHANGING THE FINAL variable, as the String lies in the Heap area. The c variable on the Stack is Final not + // CHANGING THE FINAL variable, as the String lies in the Heap area. The c variable on the + // Stack is Final not // not the String on the heap; c.setName("Modi"); System.out.println("Final String is reset to : " + c); @@ -36,5 +37,4 @@ public String toString() { return this.getName(); } } - } diff --git a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/JVM.java b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/JVM.java index 848b85c9..dc802bc8 100644 --- a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/JVM.java +++ b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/JVM.java @@ -1,15 +1,13 @@ package nitin.classLoadingJVM.javaMemoryModel; -/** - * Created by nitin on Saturday, October/05/2019 at 11:40 PM - */ +/** Created by nitin on Saturday, October/05/2019 at 11:40 PM */ public class JVM { public static void main(String... args) { - System.out.println("Hello, world!");//prints: Hello, world! + System.out.println("Hello, world!"); // prints: Hello, world! for (String arg : args) { - System.out.print(arg + " ");//prints all program arguments + System.out.print(arg + " "); // prints all program arguments } String p = System.getProperty("someParameter"); - System.out.println("\n" + p); //prints value of VM option someParameter + System.out.println("\n" + p); // prints value of VM option someParameter } } diff --git a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingObjects.java b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingObjects.java index 00b7916b..85cdfe10 100644 --- a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingObjects.java +++ b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingObjects.java @@ -1,8 +1,8 @@ package nitin.classLoadingJVM.javaMemoryModel; /** - * Created by nitin.chaurasia on 2/16/2017. - * For objects passed into methods, the REFERENCE to the a5object as passed BY VALUE + * Created by nitin.chaurasia on 2/16/2017. For objects passed into methods, the REFERENCE to the + * a5object as passed BY VALUE */ public class PassingObjects { public static void main(String[] args) { @@ -12,7 +12,6 @@ public static void main(String[] args) { renameCustomer(c); System.out.println(c.getName()); - } // Reference to the a5object c is passed bu value here, both pointing to the same string diff --git a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingValues.java b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingValues.java index 4e3d8bcf..5b01c6ba 100644 --- a/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingValues.java +++ b/src/main/java/nitin/classLoadingJVM/javaMemoryModel/PassingValues.java @@ -2,8 +2,8 @@ /** * Created by nitin.chaurasia on 2/16/2017. - *

- * In Java Pass by reference is not possible for Primitive Types + * + *

In Java Pass by reference is not possible for Primitive Types */ public class PassingValues { diff --git a/src/main/java/nitin/cloning/C1CloningDemo.java b/src/main/java/nitin/cloning/C1CloningDemo.java index 9664e746..75937110 100644 --- a/src/main/java/nitin/cloning/C1CloningDemo.java +++ b/src/main/java/nitin/cloning/C1CloningDemo.java @@ -1,8 +1,6 @@ package nitin.cloning; -/** - * Created by Nitin Chaurasia on 12/4/15 at 1:49 AM. - */ +/** Created by Nitin Chaurasia on 12/4/15 at 1:49 AM. */ public class C1CloningDemo { public static void main(String[] args) throws CloneNotSupportedException { @@ -13,19 +11,15 @@ public static void main(String[] args) throws CloneNotSupportedException { Stock s = (Stock) obj.clone(); System.out.println(obj.name + " " + obj.price); System.out.println(s.name + " " + s.price); - } } -/** - * If the Cloneable Interface is not implemented it throws CloneNotSupportedException - */ - +/** If the Cloneable Interface is not implemented it throws CloneNotSupportedException */ class Stock implements Cloneable { int price; String name; - //Constructor + // Constructor public Stock(int price, String name) { super(); this.price = price; @@ -51,7 +45,5 @@ public void setName(String name) { // Compulsory Implemrntation protected Object clone() throws CloneNotSupportedException { return super.clone(); - } - -} \ No newline at end of file +} diff --git a/src/main/java/nitin/cloning/C2ShallowCloning.java b/src/main/java/nitin/cloning/C2ShallowCloning.java index c767effe..c1499903 100644 --- a/src/main/java/nitin/cloning/C2ShallowCloning.java +++ b/src/main/java/nitin/cloning/C2ShallowCloning.java @@ -2,19 +2,18 @@ /** * Created by Nitin Chaurasia on 12/4/15 at 9:16 PM. - *

- * Shallow copy is a bit-wise copy of an a5object. - * A new a5object is created that has an exact copy of the values in the original a5object. - * If any of the fields of the a5object are references to other objects, - * just the reference addresses are copied i.e., only the memory address is copied. - *

- * FOR MUTABLE OBJECTS - * any changes made to a5object in main will reflect in clone. - *

- * FOR IMMUTABLE OBJECTS like String Integer - * Since the state cannot be changed, it doesnt need be deeply cloned - *

- * Sharing the reference + * + *

Shallow copy is a bit-wise copy of an a5object. A new a5object is created that has an exact + * copy of the values in the original a5object. If any of the fields of the a5object are references + * to other objects, just the reference addresses are copied i.e., only the memory address is + * copied. + * + *

FOR MUTABLE OBJECTS any changes made to a5object in main will reflect in clone. + * + *

FOR IMMUTABLE OBJECTS like String Integer Since the state cannot be changed, it doesnt need be + * deeply cloned + * + *

Sharing the reference */ public class C2ShallowCloning { public static void main(String[] args) throws CloneNotSupportedException { @@ -46,10 +45,10 @@ public static void main(String[] args) throws CloneNotSupportedException { class X implements Cloneable { private int a; private String b; - //For Shallow Cloning + // For Shallow Cloning private Y y; - //Constructor + // Constructor X(int a, String b) { this.a = a; this.b = b; @@ -90,7 +89,7 @@ public void setY(Y y) { protected Object clone() throws CloneNotSupportedException { X x = (X) super.clone(); x.setY(new Y(16)); - //return super.clone(); + // return super.clone(); return x; } } @@ -101,4 +100,4 @@ class Y { Y(int y) { var = y; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/cloning/C3DeepCloning.java b/src/main/java/nitin/cloning/C3DeepCloning.java index 8ce13482..ec1cfbf5 100644 --- a/src/main/java/nitin/cloning/C3DeepCloning.java +++ b/src/main/java/nitin/cloning/C3DeepCloning.java @@ -1,7 +1,4 @@ package nitin.cloning; -/** - * Created by Nitin Chaurasia on 12/7/15 at 11:56 AM. - */ -public class C3DeepCloning { -} +/** Created by Nitin Chaurasia on 12/7/15 at 11:56 AM. */ +public class C3DeepCloning {} diff --git a/src/main/java/nitin/collections/BakedCollection.java b/src/main/java/nitin/collections/BakedCollection.java index f93e2881..311e821e 100644 --- a/src/main/java/nitin/collections/BakedCollection.java +++ b/src/main/java/nitin/collections/BakedCollection.java @@ -18,7 +18,8 @@ public static void main(String[] args) { submap.put("f", "fish"); // #4 add to copy, baked collection map.put("r", "raccoon"); // #5 add to original - out of range - submap.put("p", "pig"); // #6 add to copy - out of range exception will be thrown, IllegalArgumentException: key out of range + submap.put("p", "pig"); // #6 add to copy - out of range exception will be thrown, + // IllegalArgumentException: key out of range System.out.println(map + " " + submap); // #7 show final contents } } diff --git a/src/main/java/nitin/collections/EqualsTest.java b/src/main/java/nitin/collections/EqualsTest.java index 5983bf87..de7288a7 100644 --- a/src/main/java/nitin/collections/EqualsTest.java +++ b/src/main/java/nitin/collections/EqualsTest.java @@ -6,14 +6,12 @@ public static void main(String[] arg) { Integer i = Integer.valueOf(3); Integer j = Integer.valueOf(3); - if (i == j) //2 different objects - System.out.println("true"); - else - System.out.println("false"); + if (i == j) // 2 different objects + System.out.println("true"); + else System.out.println("false"); - if (i.equals(j)) //2 different objects - System.out.println("true"); - else - System.out.println("false"); + if (i.equals(j)) // 2 different objects + System.out.println("true"); + else System.out.println("false"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/EqualsTest2.java b/src/main/java/nitin/collections/EqualsTest2.java index 91457efd..89efc031 100644 --- a/src/main/java/nitin/collections/EqualsTest2.java +++ b/src/main/java/nitin/collections/EqualsTest2.java @@ -4,30 +4,26 @@ public class EqualsTest2 { public static void main(String[] args) { Friend leena = new Friend("Leena", "Delhi", 24); - Friend leenaJacob = new Friend("Leena", "Delhi", 24); //Another a5object of type Friend. - Friend leejac = leena; //same reference to the Object leena + Friend leenaJacob = new Friend("Leena", "Delhi", 24); // Another a5object of type Friend. + Friend leejac = leena; // same reference to the Object leena - if (leenaJacob.equals(leena)) //these 2 objects are same in the eyes of equals() method, but not in the eyes of == + if (leenaJacob.equals( + leena)) // these 2 objects are same in the eyes of equals() method, but not in the + // eyes of == System.out.println("Both are equal in the eyes of equals() method"); - else - System.out.println("Both are Unequal n the eyes of equals() method"); + else System.out.println("Both are Unequal n the eyes of equals() method"); - if (leenaJacob == leena) //these 2 objects are different in the eyes of == - System.out.println("Both are equal n the eyes of == method"); - else - System.out.println("Both are Unequal n the eyes of == method"); - - if (leejac.equals(leena)) //leejac refers to leena so there is only one a5object - System.out.println("Both are equal"); - else - System.out.println("Both are UNequal"); - - if (leejac == leena) //leejac refers to leena so there is only one a5object - System.out.println("Both are equal"); - else - System.out.println("Both are UNequal"); + if (leenaJacob == leena) // these 2 objects are different in the eyes of == + System.out.println("Both are equal n the eyes of == method"); + else System.out.println("Both are Unequal n the eyes of == method"); + if (leejac.equals(leena)) // leejac refers to leena so there is only one a5object + System.out.println("Both are equal"); + else System.out.println("Both are UNequal"); + if (leejac == leena) // leejac refers to leena so there is only one a5object + System.out.println("Both are equal"); + else System.out.println("Both are UNequal"); } } @@ -37,11 +33,11 @@ class Friend { private final int age; public Friend(String name1, String place1, int age1) { - /* Without using this.name type assignment - * Class FriendInfo(String name,String city,int age){ - name = this.name; //this could also be name = name1 where name1 could be the parameter to the constructor - city = this.city; //when constructor is invoked this.city will have the info whic is copied to city - age = this.age;*/ + /* Without using this.name type assignment + * Class FriendInfo(String name,String city,int age){ + name = this.name; //this could also be name = name1 where name1 could be the parameter to the constructor + city = this.city; //when constructor is invoked this.city will have the info whic is copied to city + age = this.age;*/ name = name1; place = place1; age = age1; @@ -59,11 +55,11 @@ public int getAge() { return age; } - public boolean equals(Object l) {//leena Object is copied to l - //check the difference between this.name and name - return (l instanceof Friend) && - (((Friend) l).getName() == this.name) && - (((Friend) l).getPlace() == place) && - (((Friend) l).getAge() == age); + public boolean equals(Object l) { // leena Object is copied to l + // check the difference between this.name and name + return (l instanceof Friend) + && (((Friend) l).getName() == this.name) + && (((Friend) l).getPlace() == place) + && (((Friend) l).getAge() == age); } } diff --git a/src/main/java/nitin/collections/ListRemovalUsingForLoop.java b/src/main/java/nitin/collections/ListRemovalUsingForLoop.java index fe64258a..2026e44c 100644 --- a/src/main/java/nitin/collections/ListRemovalUsingForLoop.java +++ b/src/main/java/nitin/collections/ListRemovalUsingForLoop.java @@ -17,11 +17,10 @@ public static void main(String[] args) { for (int i = 0; i < list.size(); i++) { if (i == 2) { - //System.out.println(list.get(i)); + // System.out.println(list.get(i)); list.remove(i); } System.out.println(list.get(i)); - } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/a_list/ArrayList/BasicListInteger.java b/src/main/java/nitin/collections/a_list/ArrayList/BasicListInteger.java index fb93de71..23805f74 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/BasicListInteger.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/BasicListInteger.java @@ -4,9 +4,7 @@ import java.util.Iterator; import java.util.List; -/** - * Created by synergisticit on 2/25/2016. - */ +/** Created by synergisticit on 2/25/2016. */ public class BasicListInteger { public static void main(String[] args) { @@ -19,12 +17,12 @@ public static void main(String[] args) { list.add(4); removeOddNumber(list); - //How to Iterate + // How to Iterate printList(list); - //NOTE: FOR EACH NOT APPLICABLE FOR ITERATOR + // NOTE: FOR EACH NOT APPLICABLE FOR ITERATOR - //printSet(b_set); + // printSet(b_set); } @@ -39,23 +37,17 @@ private static void removeOddNumber(List list) { list.remove(curr); } } - } - /** - * 3 main methods of iterator - * 1. hasNext() - * 2. next() - * 3. remove() - */ + /** 3 main methods of iterator 1. hasNext() 2. next() 3. remove() */ private static void printList(List list) { - //Printing with Iterator + // Printing with Iterator Iterator itr = list.iterator(); - //From this point on, DO NOT USE b_set.get or b_set.remove!! + // From this point on, DO NOT USE b_set.get or b_set.remove!! // USE ONLY ITERATOR while (itr.hasNext()) { System.out.print(itr.next() + " - "); } System.out.println(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/a_list/ArrayList/BasicListString.java b/src/main/java/nitin/collections/a_list/ArrayList/BasicListString.java index 796d8a9d..57e45a0e 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/BasicListString.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/BasicListString.java @@ -4,9 +4,7 @@ import java.util.Iterator; import java.util.List; -/** - * Created by synergisticit on 2/25/2016. - */ +/** Created by synergisticit on 2/25/2016. */ public class BasicListString { public static void main(String[] args) { @@ -24,18 +22,18 @@ public static void main(String[] args) { list.add("luluo"); // Ordering not guarenteed in HashSet - //Set b_set = new TreeSet(); + // Set b_set = new TreeSet(); // How to Add - //addSet(b_set); + // addSet(b_set); System.out.println("Longest string is=" + findlongestString(list)); - //How to Iterate + // How to Iterate printSet(list); - //How to Remove + // How to Remove - //printSet(b_set); + // printSet(b_set); } @@ -48,31 +46,21 @@ private static String findlongestString(List list) { if (curr.length() >= temp) { temp = curr.length(); ret = curr; - } } return ret; - } - /** - * 3 main methids of iterator - * 1. hasNext() - * 2. next() - * 3. remove() - */ + /** 3 main methids of iterator 1. hasNext() 2. next() 3. remove() */ private static void printSet(List list) { - //Printing with Iterator + // Printing with Iterator Iterator itr = list.iterator(); - //From this point on, DO NOT USE b_set.get or b_set.remove!! + // From this point on, DO NOT USE b_set.get or b_set.remove!! // USE ONLY ITERATOR while (itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(); - } - - } diff --git a/src/main/java/nitin/collections/a_list/ArrayList/DynamicShrinkingArrayList.java b/src/main/java/nitin/collections/a_list/ArrayList/DynamicShrinkingArrayList.java index df23f54a..f6936303 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/DynamicShrinkingArrayList.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/DynamicShrinkingArrayList.java @@ -27,7 +27,7 @@ private static void dynamicallyShrinkList(List list, int wordLength) { for (int i = 0; i < list.size(); i++) { String curr = list.get(i); if (curr.length() >= WORD_LENGTH) { - //System.out.println("Removed Word = " + curr); + // System.out.println("Removed Word = " + curr); list.remove(i); } } @@ -36,14 +36,14 @@ private static void dynamicallyShrinkList(List list, int wordLength) { private static List readFileFromInternet() { Scanner s = null; try { - //The English word List + // The English word List URL url = new URL("https://www.mit.edu/~ecprice/wordlist.10000"); s = new Scanner(url.openStream()); } catch (IOException ex) { ex.printStackTrace(); // for now, simply output it. } - //Construct a list of Long Words + // Construct a list of Long Words List list = new ArrayList<>(); while (s.hasNext()) { String word = s.nextLine(); @@ -53,4 +53,4 @@ private static List readFileFromInternet() { } return list; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForEachRemove.java b/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForEachRemove.java index 3b1c983b..0b60b4dd 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForEachRemove.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForEachRemove.java @@ -4,13 +4,11 @@ import java.util.List; /** - * Created by nitin on 1/13/16. - * ArrayList arrayList=new ArrayList(11); - * ArrayList Initial Size 10; Later incremented by 3/2 + 1 - * Vector Initial Size 16; Incremented by 2X - *

- * list.remove() --> ConcurrentModificationException id used with Iterator - * itr.remove() --> correct way to remove + * Created by nitin on 1/13/16. ArrayList arrayList=new ArrayList(11); ArrayList Initial Size 10; + * Later incremented by 3/2 + 1 Vector Initial Size 16; Incremented by 2X + * + *

list.remove() --> ConcurrentModificationException id used with Iterator itr.remove() --> + * correct way to remove */ public class L3RemoveElementsUsingForEachRemove { public static void main(String[] args) { @@ -21,18 +19,20 @@ public static void main(String[] args) { list.add("D"); list.add("E"); - list.remove(2);// Removing the element, from anywhere + list.remove(2); // Removing the element, from anywhere - System.out.println("******************* LIST BEFORE REMOVAL ***************************** "); + System.out.println( + "******************* LIST BEFORE REMOVAL ***************************** "); System.out.println(list); - System.out.println("******************* LIST DURING REMOVAL ***************************** "); + System.out.println( + "******************* LIST DURING REMOVAL ***************************** "); // Removing the elements from the a_list - //FOR EACH is a Read Only Loop, so it will end in ConCurrent modification exception + // FOR EACH is a Read Only Loop, so it will end in ConCurrent modification exception for (String str : list) { System.out.println(str); - list.remove(str);//ConcurrentModificationException + list.remove(str); // ConcurrentModificationException } System.out.println("******************* LIST AFTER REMOVAL ***************************** "); diff --git a/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForLoopRemove.java b/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForLoopRemove.java index 6b985164..03fbbe94 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForLoopRemove.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingForLoopRemove.java @@ -4,13 +4,10 @@ import java.util.List; /** - * Created by nitin on 1/13/16. - * ArrayList arrayList=new ArrayList(11); - * ArrayList Initial Size 10; Later incremented by 3/2 + 1 - * Vector Initial Size 16; Incremented by 2X - *

- * list.remove() --> ConcurrentModificationException - * itr.remove() --> correct way to remove + * Created by nitin on 1/13/16. ArrayList arrayList=new ArrayList(11); ArrayList Initial Size 10; + * Later incremented by 3/2 + 1 Vector Initial Size 16; Incremented by 2X + * + *

list.remove() --> ConcurrentModificationException itr.remove() --> correct way to remove */ public class L3RemoveElementsUsingForLoopRemove { public static void main(String[] args) { @@ -25,16 +22,18 @@ public static void main(String[] args) { list.add("H"); list.add("I"); list.add("J"); - //list.remove(2);// Removing the element, from anywhere + // list.remove(2);// Removing the element, from anywhere - System.out.println("******************* LIST BEFORE REMOVAL ***************************** "); + System.out.println( + "******************* LIST BEFORE REMOVAL ***************************** "); System.out.println(list); - System.out.println("******************* LIST DURING REMOVAL ***************************** "); + System.out.println( + "******************* LIST DURING REMOVAL ***************************** "); // Removing the elements from the a_list // Removal Like this has a bug!! - //The List reshuffles after each Removal + // The List reshuffles after each Removal for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); list.remove(i); diff --git a/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingIterator.java b/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingIterator.java index 5a8e9361..b39aa48e 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingIterator.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/L3RemoveElementsUsingIterator.java @@ -5,13 +5,10 @@ import java.util.List; /** - * Created by nitin on 1/13/16. - * ArrayList arrayList=new ArrayList(11); - * ArrayList Initial Size 10; Later incremented by 3/2 + 1 - * Vector Initial Size 16; Incremented by 2X - *

- * list.remove() --> ConcurrentModificationException - * itr.remove() --> correct way to remove + * Created by nitin on 1/13/16. ArrayList arrayList=new ArrayList(11); ArrayList Initial Size 10; + * Later incremented by 3/2 + 1 Vector Initial Size 16; Incremented by 2X + * + *

list.remove() --> ConcurrentModificationException itr.remove() --> correct way to remove */ public class L3RemoveElementsUsingIterator { public static void main(String[] args) { @@ -22,21 +19,23 @@ public static void main(String[] args) { list.add("D"); list.add("E"); - list.remove(2);// Removing the element, from anywhere + list.remove(2); // Removing the element, from anywhere - System.out.println("******************* LIST BEFORE REMOVAL ***************************** "); + System.out.println( + "******************* LIST BEFORE REMOVAL ***************************** "); System.out.println(list); Iterator itr = list.iterator(); // Removing the elements from the a_list - System.out.println("******************* LIST DURING REMOVAL ***************************** "); + System.out.println( + "******************* LIST DURING REMOVAL ***************************** "); while (itr.hasNext()) { // itr.remove();// Wrong Place as the itr is accessed in SOP // list.remove(1);//ConcurrentModificationException System.out.println(itr.next()); itr.remove(); - }// The a_list will be empty after this + } // The a_list will be empty after this System.out.println("******************* LIST AFTER REMOVAL ***************************** "); System.out.println(list); diff --git a/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/ListSortDriver.java b/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/ListSortDriver.java index e8eacc3c..1c719753 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/ListSortDriver.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/ListSortDriver.java @@ -1,15 +1,12 @@ package nitin.collections.a_list.ArrayList.ListSortingApplication; -import lombok.AllArgsConstructor; -import lombok.Data; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Data; -/** - * Created by synergisticit on 2/26/2016. - */ +/** Created by synergisticit on 2/26/2016. */ public class ListSortDriver { public static void main(String[] args) { Student s1 = new Student(4, "ducy", "Taylor", "Jenkov Taylor"); @@ -32,7 +29,6 @@ public static void main(String[] args) { System.out.println("List after Sorting"); for (Student s : students) { System.out.println(s); - } } } @@ -44,4 +40,4 @@ class Student { String fName; String lName; String fathersFullName; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/StudentComparator.java b/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/StudentComparator.java index b9f0c728..38cbfcfa 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/StudentComparator.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/ListSortingApplication/StudentComparator.java @@ -2,27 +2,19 @@ import java.util.Comparator; -/** - * Created by synergisticit on 2/26/2016. - */ +/** Created by synergisticit on 2/26/2016. */ public class StudentComparator implements Comparator { @Override public int compare(Student s1, Student s2) { - if (s1.id > s2.id) - return 1; - else if (s1.id < s2.id) - return -1; - else - return fNameComparator(s1, s2); + if (s1.id > s2.id) return 1; + else if (s1.id < s2.id) return -1; + else return fNameComparator(s1, s2); } private int fNameComparator(Student s1, Student s2) { - if (s1.fName.compareTo(s2.fName) > 1) - return 1; - else if (s1.fName.compareTo(s2.fName) < 1) - return -1; - else - return 0; + if (s1.fName.compareTo(s2.fName) > 1) return 1; + else if (s1.fName.compareTo(s2.fName) < 1) return -1; + else return 0; } } diff --git a/src/main/java/nitin/collections/a_list/ArrayList/RemoveVSIterator.java b/src/main/java/nitin/collections/a_list/ArrayList/RemoveVSIterator.java index 3a48b8d8..c3676448 100644 --- a/src/main/java/nitin/collections/a_list/ArrayList/RemoveVSIterator.java +++ b/src/main/java/nitin/collections/a_list/ArrayList/RemoveVSIterator.java @@ -3,25 +3,22 @@ import java.util.ArrayList; import java.util.Arrays; -/** - * Created by Nitin Chaurasia on 1/24/18 at 9:27 PM. - */ +/** Created by Nitin Chaurasia on 1/24/18 at 9:27 PM. */ public class RemoveVSIterator { public static void main(String[] args) { ArrayList list = new ArrayList<>(); list.addAll(Arrays.asList(4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7)); - //filterRange(list, 5, 7); should remove all values between 5 and 7, + // filterRange(list, 5, 7); should remove all values between 5 and 7, filterRange(list, 5, 7); System.out.println(list); } private static void filterRange(ArrayList list, int min, int max) { - //To remove an element from an arraylist, running from the end is a good deal + // To remove an element from an arraylist, running from the end is a good deal for (int i = list.size() - 1; i >= 0; i--) { - if (list.get(i) >= min && list.get(i) <= max) - list.remove(i); + if (list.get(i) >= min && list.get(i) <= max) list.remove(i); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/a_list/L0ListAdd.java b/src/main/java/nitin/collections/a_list/L0ListAdd.java index 67713b36..b361efad 100644 --- a/src/main/java/nitin/collections/a_list/L0ListAdd.java +++ b/src/main/java/nitin/collections/a_list/L0ListAdd.java @@ -5,10 +5,9 @@ import java.util.List; /** - * Created by nitin on 1/13/16. - * Add at a particular Index. It has to be in an order. - *

- * You can change the value at a particular index + * Created by nitin on 1/13/16. Add at a particular Index. It has to be in an order. + * + *

You can change the value at a particular index */ public class L0ListAdd { public static void main(String[] args) { @@ -17,17 +16,17 @@ public static void main(String[] args) { list.add(1, "def"); list.add("pqr"); list.add("xyz"); - //a_list.add(6,"wer");// Will throw an exception IndexOutOfBoundsException: Index: 6, Size: 4 + // a_list.add(6,"wer");// Will throw an exception IndexOutOfBoundsException: Index: 6, Size: + // 4 System.out.println(list); - list.add(0, "ADDED VALUE!!!");// This will shift the entire array!! + list.add(0, "ADDED VALUE!!!"); // This will shift the entire array!! - list.set(1, "REPLACING THE VALUE");// Set replaces the value + list.set(1, "REPLACING THE VALUE"); // Set replaces the value Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } - } } diff --git a/src/main/java/nitin/collections/a_list/L1UnmodifiableList.java b/src/main/java/nitin/collections/a_list/L1UnmodifiableList.java index 34bac2b9..8ca883d9 100644 --- a/src/main/java/nitin/collections/a_list/L1UnmodifiableList.java +++ b/src/main/java/nitin/collections/a_list/L1UnmodifiableList.java @@ -4,10 +4,9 @@ /** * Created by nitin on 1/13/16. - *

- * The a10collections Utility Class provides the method to make a a_list FINAL - * Collections.unmodifiableList(a_list) - * READ ONLY. Throws UnsopportedOperationException + * + *

The a10collections Utility Class provides the method to make a a_list FINAL + * Collections.unmodifiableList(a_list) READ ONLY. Throws UnsopportedOperationException */ public class L1UnmodifiableList { public static void main(String[] args) { @@ -16,11 +15,11 @@ public static void main(String[] args) { list.add(2); list.add(3); - //Makes the a_list Unmodifiable + // Makes the a_list Unmodifiable Collection collection = Collections.unmodifiableList(list); - //a_list.add("123"); // Collections$UnmodifiableCollection + // a_list.add("123"); // Collections$UnmodifiableCollection - //collection.add(55); // Collections$UnmodifiableCollection + // collection.add(55); // Collections$UnmodifiableCollection Iterator itr = list.iterator(); while (itr.hasNext()) { diff --git a/src/main/java/nitin/collections/a_list/L2CopyOnWrite.java b/src/main/java/nitin/collections/a_list/L2CopyOnWrite.java index 6deddb5a..99b633b5 100644 --- a/src/main/java/nitin/collections/a_list/L2CopyOnWrite.java +++ b/src/main/java/nitin/collections/a_list/L2CopyOnWrite.java @@ -3,21 +3,20 @@ import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; -/** - * Created by nitin on 1/13/16. - * Part of Java Util Concurrent. Can write while Reading!! - */ +/** Created by nitin on 1/13/16. Part of Java Util Concurrent. Can write while Reading!! */ public class L2CopyOnWrite { public static void main(String[] args) { CopyOnWriteArrayList list = new CopyOnWriteArrayList(); - //List a_list=new ArrayList();// List will Give Concurrent Modification Exception + // List a_list=new ArrayList();// List will Give Concurrent Modification Exception list.add("abc"); list.add("def"); list.add("pqer"); Iterator iterator = list.iterator(); while (iterator.hasNext()) { - list.add("bcd"); //Adding while Iterating possible with CopyOnWriteArrayList, Concurrent modification Exception with ArrayList + list.add( + "bcd"); // Adding while Iterating possible with CopyOnWriteArrayList, Concurrent + // modification Exception with ArrayList System.out.println(iterator.next()); } diff --git a/src/main/java/nitin/collections/a_list/ListRamdomPrint.java b/src/main/java/nitin/collections/a_list/ListRamdomPrint.java index a828872f..4ad4b8da 100644 --- a/src/main/java/nitin/collections/a_list/ListRamdomPrint.java +++ b/src/main/java/nitin/collections/a_list/ListRamdomPrint.java @@ -8,23 +8,22 @@ public class ListRamdomPrint { public static void main(String[] args) { - List listOfFriends = new ArrayList(); - listOfFriends.add("Ritesh"); //index0 + listOfFriends.add("Ritesh"); // index0 listOfFriends.add("Leena"); listOfFriends.add("Prashant"); listOfFriends.add("Madhur"); listOfFriends.add("Skand"); listOfFriends.add("Neeraj"); - //listOfFriends.b_set(17, "Rochelle"); //IndexOutOfBoundsException: Index: 17, Size: 6 + // listOfFriends.b_set(17, "Rochelle"); //IndexOutOfBoundsException: Index: 17, Size: 6 - //List frndNcoll = new ArrayList(); + // List frndNcoll = new ArrayList(); System.out.println(listOfFriends); Collections.shuffle(listOfFriends, new Random()); - System.out.println(listOfFriends);//shuffeled + System.out.println(listOfFriends); // shuffeled - System.out.println(listOfFriends.get(2)); //indexing begins at 0 + System.out.println(listOfFriends.get(2)); // indexing begins at 0 System.out.println(listOfFriends.getClass()); System.out.println(listOfFriends.hashCode()); diff --git a/src/main/java/nitin/collections/a_list/ListTest.java b/src/main/java/nitin/collections/a_list/ListTest.java index c4cbe69c..885f0e52 100644 --- a/src/main/java/nitin/collections/a_list/ListTest.java +++ b/src/main/java/nitin/collections/a_list/ListTest.java @@ -25,7 +25,7 @@ public static void main(String[] args) { myFamily.add(new Family("nishu")); myFamily.add(new Family("varun")); - //make an iterator to traverse through the a_list + // make an iterator to traverse through the a_list Iterator i = myFamily.iterator(); while (i.hasNext()) { @@ -35,17 +35,17 @@ public static void main(String[] args) { System.out.println("\nIndex of Amma is = " + myFamily.indexOf(amma)); System.out.println("Number of members = " + myFamily.size()); System.out.println("Member at index 5 HashCode = " + myFamily.get(5)); - System.out.println("Member at index 5 = " + myFamily.get(5).name);//SEE THE DIFFERENCE IN THE TWO LINES + System.out.println( + "Member at index 5 = " + + myFamily.get(5).name); // SEE THE DIFFERENCE IN THE TWO LINES myFamily.remove(2); - Object[] fmly = myFamily.toArray(); //created an Object of type Family + Object[] fmly = myFamily.toArray(); // created an Object of type Family System.out.print("Members from fmly Array\n"); for (Object o : fmly) { - Family f = (Family) o; //but has to cast to compare + Family f = (Family) o; // but has to cast to compare System.out.print(f.name + " "); } - } - } diff --git a/src/main/java/nitin/collections/a_list/stack/ParenthesisCheckerJava8.java b/src/main/java/nitin/collections/a_list/stack/ParenthesisCheckerJava8.java index 9b681cac..fc0bcc6c 100644 --- a/src/main/java/nitin/collections/a_list/stack/ParenthesisCheckerJava8.java +++ b/src/main/java/nitin/collections/a_list/stack/ParenthesisCheckerJava8.java @@ -3,9 +3,7 @@ import java.util.Stack; import java.util.function.Consumer; -/** - * Created by nitin on Monday, October/14/2019 at 2:02 AM - */ +/** Created by nitin on Monday, October/14/2019 at 2:02 AM */ public class ParenthesisCheckerJava8 { public static void main(String[] args) { System.out.println(checker("({{}}(){()})")); @@ -14,22 +12,21 @@ public static void main(String[] args) { private static boolean checker(String str) { Stack s = new Stack<>(); - Consumer consumer = (c) -> { - if (c.toString().equals("(") || c == '{') { - s.push(c); - } + Consumer consumer = + (c) -> { + if (c.toString().equals("(") || c == '{') { + s.push(c); + } - if (c == '}' && s.peek() == '{') { - s.pop(); - } + if (c == '}' && s.peek() == '{') { + s.pop(); + } - if (c == ')' && s.peek() == '(') { - s.pop(); - } - }; - str.chars() - .mapToObj(i -> (char) i) - .forEach(x -> consumer.accept(x)); + if (c == ')' && s.peek() == '(') { + s.pop(); + } + }; + str.chars().mapToObj(i -> (char) i).forEach(x -> consumer.accept(x)); return s.isEmpty(); } diff --git a/src/main/java/nitin/collections/a_list/stack/S1StackBasics.java b/src/main/java/nitin/collections/a_list/stack/S1StackBasics.java index 00baa6d7..76ef1305 100644 --- a/src/main/java/nitin/collections/a_list/stack/S1StackBasics.java +++ b/src/main/java/nitin/collections/a_list/stack/S1StackBasics.java @@ -2,14 +2,12 @@ import java.util.Stack; -/** - * Created by nitin on Thu, 2/2/17 at 10:34 PM. - */ +/** Created by nitin on Thu, 2/2/17 at 10:34 PM. */ public class S1StackBasics { public static void main(String[] args) { -// List stack = new Stack<>();//Only List methods are available + // List stack = new Stack<>();//Only List methods are available Stack stack = new Stack<>(); - //Push and add does the same thing + // Push and add does the same thing stack.push(10); stack.push(15); stack.push(35); diff --git a/src/main/java/nitin/collections/b_set/FindDuplicates.java b/src/main/java/nitin/collections/b_set/FindDuplicates.java index 7b97d0e6..9a7010af 100644 --- a/src/main/java/nitin/collections/b_set/FindDuplicates.java +++ b/src/main/java/nitin/collections/b_set/FindDuplicates.java @@ -9,10 +9,8 @@ public static void main(String[] args) { String[] test = {"i", "came", "i", "saw", "i", "left"}; Set s = new HashSet(); for (String g : test) { - if (!s.add(g)) - System.out.println("Duplicate detected " + g); - else - System.out.println("Value Added " + g); + if (!s.add(g)) System.out.println("Duplicate detected " + g); + else System.out.println("Value Added " + g); } System.out.println(s.size() + " distinct words: " + s); @@ -21,8 +19,8 @@ public static void main(String[] args) { Set dups = new HashSet(); for (String g : test) - if (!uniques.add(g)) //uniques.add will return true - dups.add(g); + if (!uniques.add(g)) // uniques.add will return true + dups.add(g); uniques.removeAll(dups); diff --git a/src/main/java/nitin/collections/b_set/S1AddMultipleValues.java b/src/main/java/nitin/collections/b_set/S1AddMultipleValues.java index 88086dd1..6c634485 100644 --- a/src/main/java/nitin/collections/b_set/S1AddMultipleValues.java +++ b/src/main/java/nitin/collections/b_set/S1AddMultipleValues.java @@ -4,19 +4,18 @@ import java.util.Iterator; /** - * Created by nitin on 1/13/16. - * Repeated Entries are possible but only the latest one will be kept + * Created by nitin on 1/13/16. Repeated Entries are possible but only the latest one will be kept */ public class S1AddMultipleValues { public static void main(String[] args) { - //TreeSet hashSet = new TreeSet(); + // TreeSet hashSet = new TreeSet(); HashSet hashSet = new HashSet(); hashSet.add("B"); hashSet.add(null); hashSet.add("A"); - System.out.println(hashSet.add("C"));// First Entry TRUE - System.out.println(hashSet.add("C"));// Second Entry False - System.out.println(hashSet.add(null));// false, null already added + System.out.println(hashSet.add("C")); // First Entry TRUE + System.out.println(hashSet.add("C")); // Second Entry False + System.out.println(hashSet.add(null)); // false, null already added System.out.println("****************************************"); diff --git a/src/main/java/nitin/collections/b_set/S2BasicSetInteger.java b/src/main/java/nitin/collections/b_set/S2BasicSetInteger.java index cdacb1b6..8be8afe0 100644 --- a/src/main/java/nitin/collections/b_set/S2BasicSetInteger.java +++ b/src/main/java/nitin/collections/b_set/S2BasicSetInteger.java @@ -6,8 +6,8 @@ import java.util.TreeSet; /** - * Created by synergisticit on 2/25/2016. - * while adding into a set, a test of equality happens, to determine if the a5object being pushed already exist + * Created by synergisticit on 2/25/2016. while adding into a set, a test of equality happens, to + * determine if the a5object being pushed already exist */ public class S2BasicSetInteger { public static void main(String[] args) { @@ -19,20 +19,18 @@ public static void main(String[] args) { Set set = new TreeSet(); // Ordering NOT guarenteed in HashSet - //Set b_set = new HashSet(); + // Set b_set = new HashSet(); // How to Add addSet(set); - //How to Iterate + // How to Iterate printSet(set); - //How to Remove + // How to Remove removeOddNumber(set); printSet(set); - - } private static void removeOddNumber(Set set) { @@ -43,22 +41,16 @@ private static void removeOddNumber(Set set) { if (curr % 2 != 0) { itr.remove(); // ConcurrentModificationException - //b_set.remove(curr); + // b_set.remove(curr); } } - } - /** - * 3 main methods of iterator - * 1. hasNext() - * 2. next() - * 3. remove() - */ + /** 3 main methods of iterator 1. hasNext() 2. next() 3. remove() */ private static void printSet(Set set) { - //Printing with Iterator + // Printing with Iterator Iterator itr = set.iterator(); - //From this point on, DO NOT USE set.get or set.remove!! + // From this point on, DO NOT USE set.get or set.remove!! // USE ONLY ITERATOR while (itr.hasNext()) { System.out.print(itr.next() + " - "); @@ -72,12 +64,10 @@ private static void printSet(Set set) { } System.out.println(); - } /** - * 1. Demonstrating adding USING A COLLECTION - * 2. and adding individual elements + * 1. Demonstrating adding USING A COLLECTION 2. and adding individual elements * * @param set */ diff --git a/src/main/java/nitin/collections/b_set/S3BasicSetString.java b/src/main/java/nitin/collections/b_set/S3BasicSetString.java index 26fde174..1e34c081 100644 --- a/src/main/java/nitin/collections/b_set/S3BasicSetString.java +++ b/src/main/java/nitin/collections/b_set/S3BasicSetString.java @@ -2,9 +2,7 @@ import java.util.*; -/** - * Created by synergisticit on 2/25/2016. - */ +/** Created by synergisticit on 2/25/2016. */ public class S3BasicSetString { public static void main(String[] args) { @@ -15,46 +13,39 @@ public static void main(String[] args) { Set set = new TreeSet(); // Ordering not guarenteed in HashSet - //Set b_set = new TreeSet(); + // Set b_set = new TreeSet(); // How to Add addSet(set); - //How to Iterate + // How to Iterate printSet(set); - //How to find + // How to find System.out.println(findLongString(set)); - } /** - * 1. Demonstrating adding USING A COLLECTION - * 2. and adding individual elements + * 1. Demonstrating adding USING A COLLECTION 2. and adding individual elements * * @param set */ private static void addSet(Set set) { - String[] arr = new String[]{"Lucia", "Brendan", "Sophia", "Sara"}; + String[] arr = new String[] {"Lucia", "Brendan", "Sophia", "Sara"}; List arr1 = new ArrayList(); - //Adding some other collection into the b_set + // Adding some other collection into the b_set arr1 = Arrays.asList(arr); set.addAll(arr1); - //Adding an individual element + // Adding an individual element set.add("1234"); } - /** - * 3 main methids of iterator - * 1. hasNext() - * 2. next() - * 3. remove() - */ + /** 3 main methids of iterator 1. hasNext() 2. next() 3. remove() */ private static void printSet(Set set) { - //Printing with Iterator + // Printing with Iterator Iterator itr = set.iterator(); - //From this point on, DO NOT USE b_set.get or b_set.remove!! + // From this point on, DO NOT USE b_set.get or b_set.remove!! // USE ONLY ITERATOR while (itr.hasNext()) { @@ -75,7 +66,7 @@ private static String findLongString(Set set) { String ret = null; while (itr.hasNext()) { - //Save the current value to avoid two itr.next + // Save the current value to avoid two itr.next String current = itr.next(); if (current.length() > strLen) { diff --git a/src/main/java/nitin/collections/b_set/S4TreeSetOfObjects.java b/src/main/java/nitin/collections/b_set/S4TreeSetOfObjects.java index 7cb0008c..a191b91f 100644 --- a/src/main/java/nitin/collections/b_set/S4TreeSetOfObjects.java +++ b/src/main/java/nitin/collections/b_set/S4TreeSetOfObjects.java @@ -1,30 +1,50 @@ package nitin.collections.b_set; +import java.util.*; import lombok.AllArgsConstructor; import lombok.Data; -import java.util.*; - -/** - * Created by nitin on Saturday, August/24/2019 at 22:07 - */ +/** Created by nitin on Saturday, August/24/2019 at 22:07 */ public class S4TreeSetOfObjects { - public static void main(String[] args) { - Car a = new Car("Honda", "CRV", new int[]{05, 2019}, new ArrayList(Arrays.asList("AWD", "Leather", "Sun Roof", "Grey Interior"))); - Car b = new Car("Toyota", "RAV4", new int[]{03, 2019}, new ArrayList(Arrays.asList("2WD", "Cotton", "Sun Roof", "Grey Interior"))); - Car c = new Car("Honda", "Accord", new int[]{03, 2018}, new ArrayList(Arrays.asList("AWD", "Leather", "Sun Roof", "Grey Interior"))); - Car d = new Car("Toyota", "Camry", new int[]{06, 2018}, new ArrayList(Arrays.asList("2WD", "Cotton", "Sun Roof", "Grey Interior"))); + Car a = + new Car( + "Honda", + "CRV", + new int[] {05, 2019}, + new ArrayList( + Arrays.asList("AWD", "Leather", "Sun Roof", "Grey Interior"))); + Car b = + new Car( + "Toyota", + "RAV4", + new int[] {03, 2019}, + new ArrayList( + Arrays.asList("2WD", "Cotton", "Sun Roof", "Grey Interior"))); + Car c = + new Car( + "Honda", + "Accord", + new int[] {03, 2018}, + new ArrayList( + Arrays.asList("AWD", "Leather", "Sun Roof", "Grey Interior"))); + Car d = + new Car( + "Toyota", + "Camry", + new int[] {06, 2018}, + new ArrayList( + Arrays.asList("2WD", "Cotton", "Sun Roof", "Grey Interior"))); - Set set = new TreeSet<>(Comparator - .comparing(Car::getMake)//Default Natural Sorting Order - .thenComparing(Car::getModel) - .thenComparingInt(car -> car.getYymm()[0]) - .thenComparingInt(car -> car.getYymm()[1]) - .thenComparingInt(car -> car.getFeatures().size()) - ); + Set set = + new TreeSet<>( + Comparator.comparing(Car::getMake) // Default Natural Sorting Order + .thenComparing(Car::getModel) + .thenComparingInt(car -> car.getYymm()[0]) + .thenComparingInt(car -> car.getYymm()[1]) + .thenComparingInt(car -> car.getFeatures().size())); System.out.println(set.add(a)); System.out.println(set.add(b)); System.out.println(set.add(c)); @@ -42,4 +62,4 @@ class Car { private String make; private int[] yymm; private List features; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/b_set/SetApplication.java b/src/main/java/nitin/collections/b_set/SetApplication.java index 75021f7a..cfbda19b 100644 --- a/src/main/java/nitin/collections/b_set/SetApplication.java +++ b/src/main/java/nitin/collections/b_set/SetApplication.java @@ -2,9 +2,7 @@ import java.util.*; -/** - * Created by synergisticit on 2/26/2016. - */ +/** Created by synergisticit on 2/26/2016. */ public class SetApplication { public static void main(String[] args) { Integer[] arr = {1, 2, 1, 3, 4, 5, 2, 1, 3, 4, 5, 6, 7, 8, 97, 1, 2}; @@ -15,7 +13,6 @@ public static void main(String[] args) { System.out.println("Unique Elements : " + uniqueElements); System.out.println("Max value is : " + maxValue); - } private static int countUnique(List list) { @@ -43,10 +40,8 @@ private static int maxValueInList(List list) { while (itr.hasNext()) { int value = itr.next(); System.out.println(value); - if (value > max) - max = value; + if (value > max) max = value; } return max; } - } diff --git a/src/main/java/nitin/collections/c_queue/PriorityQu.java b/src/main/java/nitin/collections/c_queue/PriorityQu.java index 24e19e77..0143cfeb 100644 --- a/src/main/java/nitin/collections/c_queue/PriorityQu.java +++ b/src/main/java/nitin/collections/c_queue/PriorityQu.java @@ -5,35 +5,34 @@ import java.util.Queue; /** - * Heaps are represented using Priority Queue. It gives O(1) seek time - * add(E e) Inserts the specified element into this priority queue. - * offer(E e) Inserts the specified element into this priority queue - * poll() Retrieves and removes the head of this queue, or returns null if this queue is empty. + * Heaps are represented using Priority Queue. It gives O(1) seek time add(E e) Inserts the + * specified element into this priority queue. offer(E e) Inserts the specified element into this + * priority queue poll() Retrieves and removes the head of this queue, or returns null if this queue + * is empty. */ - public class PriorityQu { public static void main(String[] args) { int[] q = {5, 3, 8, 6, 9, 1, 7}; Queue pq = new PriorityQueue<>(Comparator.reverseOrder()); for (int i : q) { - pq.offer(i);//Add values + pq.offer(i); // Add values } System.out.println("Printing Priority Queue"); - System.out.println(pq); //Print directly + System.out.println(pq); // Print directly for (int j : q) { - System.out.print(" " + pq.poll());//Poll removes the elements + System.out.print(" " + pq.poll()); // Poll removes the elements } - //pqWithSort(q); + // pqWithSort(q); } private static void pqWithSort(int[] q) { PQsort pqs = new PQsort(); PriorityQueue pq2 = new PriorityQueue(10, pqs); for (int x : q) // load queue - pq2.offer(x); + pq2.offer(x); System.out.println("\nsize " + pq2.size()); System.out.println("peek " + pq2.peek()); System.out.println("size " + pq2.size()); @@ -41,7 +40,7 @@ private static void pqWithSort(int[] q) { System.out.println("size " + pq2.size()); for (int k : q) // review queue - System.out.print(pq2.poll() + " "); + System.out.print(pq2.poll() + " "); } static class PQsort implements Comparator { diff --git a/src/main/java/nitin/collections/c_queue/QueueExample.java b/src/main/java/nitin/collections/c_queue/QueueExample.java index 3aaa043d..d3b9809c 100644 --- a/src/main/java/nitin/collections/c_queue/QueueExample.java +++ b/src/main/java/nitin/collections/c_queue/QueueExample.java @@ -5,10 +5,10 @@ import java.util.Queue; /** - * Created by nitin.chaurasia on 2/11/2017. - * peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. - * poll() Retrieves and removes the head of this queue, or returns null if this queue is empty. - * remove() Removes a single instance of the specified element from this queue, if it is present. + * Created by nitin.chaurasia on 2/11/2017. peek() Retrieves, but does not remove, the head of this + * queue, or returns null if this queue is empty. poll() Retrieves and removes the head of this + * queue, or returns null if this queue is empty. remove() Removes a single instance of the + * specified element from this queue, if it is present. */ public class QueueExample { public static void main(String[] args) { @@ -18,7 +18,8 @@ public static void main(String[] args) { q.add(i); } - System.out.println("Peek at the element at the head without taking the element out of the queue with element method"); + System.out.println( + "Peek at the element at the head without taking the element out of the queue with element method"); // peek at the element at the head without taking the element out of the queue // element() method System.out.println(q.element()); diff --git a/src/main/java/nitin/collections/collectionsClass/CollectionsClassPrimitive.java b/src/main/java/nitin/collections/collectionsClass/CollectionsClassPrimitive.java index fefb11c6..6c84c115 100644 --- a/src/main/java/nitin/collections/collectionsClass/CollectionsClassPrimitive.java +++ b/src/main/java/nitin/collections/collectionsClass/CollectionsClassPrimitive.java @@ -1,24 +1,19 @@ package nitin.collections.collectionsClass; import com.utilities.InternetUtilities; - import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -/** - * Created by nitin on Wednesday, September/25/2019 at 10:15 PM - */ +/** Created by nitin on Wednesday, September/25/2019 at 10:15 PM */ public class CollectionsClassPrimitive { private static final int WORD_LENGTH = 15; public static void main(String[] args) { List list = InternetUtilities.bringWordListFromNet(); - list = list.stream() - .filter(s -> s.length() > WORD_LENGTH) - .collect(Collectors.toList()); + list = list.stream().filter(s -> s.length() > WORD_LENGTH).collect(Collectors.toList()); System.out.println(list); @@ -26,10 +21,10 @@ public static void main(String[] args) { System.out.println("Shuffled List"); System.out.println(list); - //Reverse Sorting + // Reverse Sorting list.sort(Comparator.naturalOrder()); - //list.stream().sorted(Comparator.comparing(s -> s.length())); + // list.stream().sorted(Comparator.comparing(s -> s.length())); System.out.println("Reversed SortedList"); System.out.println(list); diff --git a/src/main/java/nitin/collections/comparable/ComparableTestFailed.java b/src/main/java/nitin/collections/comparable/ComparableTestFailed.java index 29c1ba5f..09299177 100644 --- a/src/main/java/nitin/collections/comparable/ComparableTestFailed.java +++ b/src/main/java/nitin/collections/comparable/ComparableTestFailed.java @@ -6,15 +6,15 @@ /** * Created by synergisticit on 2/25/2016 - *

- * If we wish to insert Student a5object into TreeSet (which needs compare logic), we will get the following error - * java.lang.ClassCastException if Student does not implement java.lang.Comparable - * MNEMONIC BC (comparaBle - ClassCast) - *

- * Whenever we use Object other THAN WRAPPER - *

- * This problem CANNOT be solved with COMPARATOR. - * comparator can be used when we call java Utility Class + * + *

If we wish to insert Student a5object into TreeSet (which needs compare logic), we will get + * the following error java.lang.ClassCastException if Student does not implement + * java.lang.Comparable MNEMONIC BC (comparaBle - ClassCast) + * + *

Whenever we use Object other THAN WRAPPER + * + *

This problem CANNOT be solved with COMPARATOR. comparator can be used when we call java + * Utility Class */ // a10collections.sort(List, comparator<...>) public class ComparableTestFailed { @@ -24,7 +24,7 @@ public static void main(String[] args) { Student s3 = new Student(1, "Joe", "Kresman", "Andrew Taylor"); Student s4 = new Student(4, "Lucy", "Green", "Taylor Zimmarman"); - //HashSet does not need COMPARATOR, but TREE DOES + // HashSet does not need COMPARATOR, but TREE DOES Set studentSet = new TreeSet<>(); studentSet.add(s1); @@ -62,10 +62,8 @@ public int compareTo(Object o) { private int compareFirstNames(Object o) { Student curr = (Student) o; int ret = this.fName.compareTo(curr.fName); - if (ret != 0) - return ret; - else - return compareFathersName(o); + if (ret != 0) return ret; + else return compareFathersName(o); } private int compareFathersName(Object o) { @@ -76,11 +74,18 @@ private int compareFathersName(Object o) { @Override public String toString() { - return "Student{" + - "id=" + id + - ", fName='" + fName + '\'' + - ", lName='" + lName + '\'' + - ", fathersFullName='" + fathersFullName + '\'' + - '}'; + return "Student{" + + "id=" + + id + + ", fName='" + + fName + + '\'' + + ", lName='" + + lName + + '\'' + + ", fathersFullName='" + + fathersFullName + + '\'' + + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/comparator/ComparatorTest.java b/src/main/java/nitin/collections/comparator/ComparatorTest.java index 7edbf1d5..c37bb671 100644 --- a/src/main/java/nitin/collections/comparator/ComparatorTest.java +++ b/src/main/java/nitin/collections/comparator/ComparatorTest.java @@ -4,9 +4,7 @@ import java.util.Set; import java.util.TreeSet; -/** - * Created by synergisticit on 2/26/2016. - */ +/** Created by synergisticit on 2/26/2016. */ public class ComparatorTest { public static void main(String[] args) { Student s1 = new Student(4, "Lucy", "Taylor", "Jenkov Taylor"); @@ -14,7 +12,7 @@ public static void main(String[] args) { Student s3 = new Student(1, "Joe", "Kresman", "Andrew Taylor"); Student s4 = new Student(4, "Lucy", "Green", "Taylor Zimmarman"); - //HashSet does not need COMPARATOR, but TREESET DOES + // HashSet does not need COMPARATOR, but TREESET DOES Set studentSet = new TreeSet(new StudentComparator()); studentSet.add(s1); @@ -27,6 +25,5 @@ public static void main(String[] args) { while (itr.hasNext()) { System.out.println(itr.next()); } - } } diff --git a/src/main/java/nitin/collections/comparator/StudentComparator.java b/src/main/java/nitin/collections/comparator/StudentComparator.java index 88ef56a7..7c30f120 100644 --- a/src/main/java/nitin/collections/comparator/StudentComparator.java +++ b/src/main/java/nitin/collections/comparator/StudentComparator.java @@ -4,10 +4,9 @@ /** * Created by synergisticit on 2/26/2016. - *

- * First Compare with StudentId, if found same, compare with - * First name. If the first name is also same - * then compare with the fathers name. + * + *

First Compare with StudentId, if found same, compare with First name. If the first name is + * also same then compare with the fathers name. */ public class StudentComparator implements Comparator { @Override @@ -15,23 +14,17 @@ public int compare(Student o1, Student o2) { Student s1 = o1; Student s2 = o2; - //System.out.println(s1.id.compareTo(s2.id)); + // System.out.println(s1.id.compareTo(s2.id)); - if (s1.id > s2.id) - return 1; - else if (s1.id < s2.id) - return -1; - else - return compareNameCompare(s1, s2); + if (s1.id > s2.id) return 1; + else if (s1.id < s2.id) return -1; + else return compareNameCompare(s1, s2); } private int compareNameCompare(Student s1, Student s2) { - if (s1.fName.compareTo(s2.fName) > 0) - return 1; - else if (s1.fName.compareTo(s2.fName) < 0) - return -1; - else - return compareFathersName(s1, s2); + if (s1.fName.compareTo(s2.fName) > 0) return 1; + else if (s1.fName.compareTo(s2.fName) < 0) return -1; + else return compareFathersName(s1, s2); } private int compareFathersName(Student s1, Student s2) { @@ -54,11 +47,18 @@ public Student(int id, String fName, String lName, String fathersFullName) { @Override public String toString() { - return "Student{" + - "id=" + id + - ", fName='" + fName + '\'' + - ", lName='" + lName + '\'' + - ", fathersFullName='" + fathersFullName + '\'' + - '}'; + return "Student{" + + "id=" + + id + + ", fName='" + + fName + + '\'' + + ", lName='" + + lName + + '\'' + + ", fathersFullName='" + + fathersFullName + + '\'' + + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/comparator/withLambda/Driver.java b/src/main/java/nitin/collections/comparator/withLambda/Driver.java index 8299ec6e..0674dc31 100644 --- a/src/main/java/nitin/collections/comparator/withLambda/Driver.java +++ b/src/main/java/nitin/collections/comparator/withLambda/Driver.java @@ -4,9 +4,7 @@ import java.util.Set; import java.util.TreeSet; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class Driver { public static void main(String[] args) { Set s = new TreeSet<>(new SquirrelComparator()); @@ -14,7 +12,7 @@ public static void main(String[] args) { s.add(new Squirrel("Angie", 20)); s.add(new Squirrel("Angie", 23)); s.add(new Squirrel("Cngie", 28)); - s.add(new Squirrel("Angie", 20));//NOT ADDED + s.add(new Squirrel("Angie", 20)); // NOT ADDED s.add(new Squirrel("Engie", 22)); s.add(new Squirrel("Fngie", 20)); s.add(new Squirrel("Gngie", 14)); diff --git a/src/main/java/nitin/collections/comparator/withLambda/Squirrel.java b/src/main/java/nitin/collections/comparator/withLambda/Squirrel.java index 6e17d5d7..4fc53c20 100644 --- a/src/main/java/nitin/collections/comparator/withLambda/Squirrel.java +++ b/src/main/java/nitin/collections/comparator/withLambda/Squirrel.java @@ -1,8 +1,6 @@ package nitin.collections.comparator.withLambda; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class Squirrel { private String species; @@ -14,10 +12,8 @@ public Squirrel(String species, int weight) { } public Squirrel(String theSpecies) { - if (theSpecies == null) - throw new IllegalArgumentException(); - else - this.species = theSpecies; + if (theSpecies == null) throw new IllegalArgumentException(); + else this.species = theSpecies; } public String getSpecies() { @@ -38,9 +34,6 @@ public void setWeight(int weight) { @Override public String toString() { - return "Squirrel{" + - "species='" + species + '\'' + - ", weight=" + weight + - '}'; + return "Squirrel{" + "species='" + species + '\'' + ", weight=" + weight + '}'; } } diff --git a/src/main/java/nitin/collections/comparator/withLambda/SquirrelComparator.java b/src/main/java/nitin/collections/comparator/withLambda/SquirrelComparator.java index 3a41d999..f4e3dbb3 100644 --- a/src/main/java/nitin/collections/comparator/withLambda/SquirrelComparator.java +++ b/src/main/java/nitin/collections/comparator/withLambda/SquirrelComparator.java @@ -2,9 +2,7 @@ import java.util.Comparator; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class SquirrelComparator implements Comparator { @Override public int compare(Squirrel s1, Squirrel s2) { diff --git a/src/main/java/nitin/collections/concurrentCollections/CC1Test.java b/src/main/java/nitin/collections/concurrentCollections/CC1Test.java index 8dd91e29..dde2ae1b 100644 --- a/src/main/java/nitin/collections/concurrentCollections/CC1Test.java +++ b/src/main/java/nitin/collections/concurrentCollections/CC1Test.java @@ -1,8 +1,6 @@ package nitin.collections.concurrentCollections; -/** - * Created by nitin.chaurasia on 1/22/2017. - */ +/** Created by nitin.chaurasia on 1/22/2017. */ public class CC1Test { public static void main(String[] args) { System.out.println("Study Concurrent Collections"); diff --git a/src/main/java/nitin/collections/d_maps/BasicMapInteger.java b/src/main/java/nitin/collections/d_maps/BasicMapInteger.java index d6ae2edf..69760378 100644 --- a/src/main/java/nitin/collections/d_maps/BasicMapInteger.java +++ b/src/main/java/nitin/collections/d_maps/BasicMapInteger.java @@ -7,9 +7,9 @@ /** * Created by synergisticit on 2/25/2016. - *

- * HashMAp and HashSet doest guarantee the order of retrieval - * TreeSet and TreeMap guarantees order (for map, the order is DNSO of keys) + * + *

HashMAp and HashSet doest guarantee the order of retrieval TreeSet and TreeMap guarantees + * order (for map, the order is DNSO of keys) */ public class BasicMapInteger { public static void main(String[] args) { @@ -24,71 +24,66 @@ public static void main(String[] args) { map.put(1006, 11); map.put(1007, 12); + // printMapUsingSet(map); - //printMapUsingSet(map); - - //printMapUsingEntrySet(map); + // printMapUsingEntrySet(map); removeOddNumber(map); printMapUsingEntrySetForEach(map); - - } private static void removeOddNumber(Map map) { - //KeySet is a method in Map which RETURNS SET OF KEYS + // KeySet is a method in Map which RETURNS SET OF KEYS Iterator itr = map.keySet().iterator(); while (itr.hasNext()) { int tempKey = itr.next(); if (map.get(tempKey) % 2 == 0) { // Concurrent Modification Exception - //map.remove(tempKey); + // map.remove(tempKey); - //ALWAYS REMOVE USING ITERATOR + // ALWAYS REMOVE USING ITERATOR itr.remove(); } } } private static void printMapUsingEntrySetForEach(Map map) { - //loop a Map + // loop a Map for (Map.Entry itr : map.entrySet()) { System.out.println("Key : " + itr.getKey() + " Value : " + itr.getValue()); } } /** - * Iterating through a Map using Entry Set. - * NOTE: ENTRY SET RETURNS A SET OF ENTRY WHICH KEY ADN VALUE + * Iterating through a Map using Entry Set. NOTE: ENTRY SET RETURNS A SET OF ENTRY WHICH KEY ADN + * VALUE * * @param map */ private static void printMapUsingEntrySet(Map map) { - //Extracting the entry set and iterating over it + // Extracting the entry set and iterating over it Set myMap = map.entrySet(); Iterator> itr = myMap.iterator(); while (itr.hasNext()) { Map.Entry curr = itr.next(); - //Return the toString representation of Map.Entry + // Return the toString representation of Map.Entry System.out.println(curr); - //Extracting the key and value out of Entry + // Extracting the key and value out of Entry System.out.println("Key is : " + curr.getKey() + " Value is " + curr.getValue()); } } /** * Map is not a part of Collection thus Iterator is not available - *

- * There are two ways to iterate a map - * 1. Using Set (for loop) - * 2. Using EntrySet (for each) + * + *

There are two ways to iterate a map 1. Using Set (for loop) 2. Using EntrySet (for each) * * @param map */ private static void printMapUsingSet(Map map) { - //KeySet is a method in map which RETURNS A SET OF KEYS + // KeySet is a method in map which RETURNS A SET OF KEYS Set key = map.keySet(); Iterator itr = key.iterator(); diff --git a/src/main/java/nitin/collections/d_maps/BasicMapString.java b/src/main/java/nitin/collections/d_maps/BasicMapString.java index 2cec259e..a6c2a4df 100644 --- a/src/main/java/nitin/collections/d_maps/BasicMapString.java +++ b/src/main/java/nitin/collections/d_maps/BasicMapString.java @@ -5,9 +5,7 @@ import java.util.Set; import java.util.TreeMap; -/** - * Created by synergisticit on 2/25/2016. - */ +/** Created by synergisticit on 2/25/2016. */ public class BasicMapString { public static void main(String[] args) { @@ -24,14 +22,14 @@ public static void main(String[] args) { map.put(5, "Abc"); map.put(6, "sangrampisal"); - //printMapUsingSet(map); + // printMapUsingSet(map); System.out.print("Longest Key is-----"); System.out.print(findLongString(map)); } private static String findLongString(Map map) { - //KeySet is a method in map which RETURNS A SET OF KEYS + // KeySet is a method in map which RETURNS A SET OF KEYS Set key = map.keySet(); Iterator itr = key.iterator(); @@ -51,15 +49,13 @@ private static String findLongString(Map map) { /** * Map is not a part of Collection thus Iterator is not available - *

- * There are two ways to iterate a map - * 1. Using Set (for loop) - * 2. Using EntrySet (for each) + * + *

There are two ways to iterate a map 1. Using Set (for loop) 2. Using EntrySet (for each) * * @param map */ private static void printMapUsingSet(Map map) { - //KeySet is a method in map which RETURNS A SET OF KEYS + // KeySet is a method in map which RETURNS A SET OF KEYS Set key = map.keySet(); Iterator itr = key.iterator(); diff --git a/src/main/java/nitin/collections/d_maps/H1HashMapIterationDemo.java b/src/main/java/nitin/collections/d_maps/H1HashMapIterationDemo.java index d313a8e8..4b430eea 100644 --- a/src/main/java/nitin/collections/d_maps/H1HashMapIterationDemo.java +++ b/src/main/java/nitin/collections/d_maps/H1HashMapIterationDemo.java @@ -5,9 +5,7 @@ import java.util.Map; import java.util.Set; -/** - * Created by nitin on 1/13/16. - */ +/** Created by nitin on 1/13/16. */ public class H1HashMapIterationDemo { public static void main(String[] args) { Map map = new HashMap(); @@ -26,12 +24,12 @@ public static void main(String[] args) { Iterator itr = keySet.iterator(); // ***************** COMBINING ABOVE TWO*********************8 - //Iterator itr = map.keySet().iterator(); + // Iterator itr = map.keySet().iterator(); while (itr.hasNext()) { - //Key is from the Set + // Key is from the Set int key = (int) itr.next(); - //Value is from the Map + // Value is from the Map String value = map.get(key); System.out.print("Key = " + key); System.out.println(" Value = " + value); @@ -43,7 +41,7 @@ public static void main(String[] args) { Set entry = map.entrySet(); Iterator itr2 = entry.iterator(); // Can be written as - //Iterator itr3 = (Iterator) map.entrySet(); + // Iterator itr3 = (Iterator) map.entrySet(); while (itr2.hasNext()) { Map.Entry me = (Map.Entry) itr2.next(); diff --git a/src/main/java/nitin/collections/d_maps/H2HashTableEnumerationDemo.java b/src/main/java/nitin/collections/d_maps/H2HashTableEnumerationDemo.java index b5c3ca19..a32bed41 100644 --- a/src/main/java/nitin/collections/d_maps/H2HashTableEnumerationDemo.java +++ b/src/main/java/nitin/collections/d_maps/H2HashTableEnumerationDemo.java @@ -8,8 +8,8 @@ public class H2HashTableEnumerationDemo { public static void main(String[] args) { // Create a hash map Hashtable balance = new Hashtable<>(); - //Enumeration names; - //Iterator itr = (Iterator) balance.; + // Enumeration names; + // Iterator itr = (Iterator) balance.; String str; double bal; @@ -23,14 +23,12 @@ public static void main(String[] args) { Enumeration names = balance.keys(); while (names.hasMoreElements()) { str = names.nextElement(); - System.out.println(str + ": " + - balance.get(str)); + System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into Zara's account bal = balance.get("Zara").doubleValue(); balance.put("Zara", Double.valueOf(bal + 1000)); - System.out.println("Zara's new balance: " + - balance.get("Zara")); + System.out.println("Zara's new balance: " + balance.get("Zara")); } } diff --git a/src/main/java/nitin/collections/d_maps/HashMap/HashMapEg.java b/src/main/java/nitin/collections/d_maps/HashMap/HashMapEg.java index 71210c1d..2f70537c 100644 --- a/src/main/java/nitin/collections/d_maps/HashMap/HashMapEg.java +++ b/src/main/java/nitin/collections/d_maps/HashMap/HashMapEg.java @@ -3,32 +3,39 @@ import java.util.HashMap; import java.util.Map; -enum Pets {CATS, DOGS, HORSES} +enum Pets { + CATS, + DOGS, + HORSES +} public class HashMapEg { public static void main(String[] args) { Map m = new HashMap(); - //Putting some RANDOM KEY and VALUE + // Putting some RANDOM KEY and VALUE - m.put("1998", new Dog("Tuffy"));//1998 IS THE kEY + m.put("1998", new Dog("Tuffy")); // 1998 IS THE kEY Dog d1 = new Dog("kalloo"); - m.put(d1, "Dog Key 1992");//a5object d1 is used as a key - m.put("k2", Pets.DOGS);//ENUM as Value + m.put(d1, "Dog Key 1992"); // a5object d1 is used as a key + m.put("k2", Pets.DOGS); // ENUM as Value m.put(Pets.CATS, "CAT Key"); m.put(new Cat(), "Key value"); - System.out.println(m.get("1998")); //dOG OBJECT -->THE VALUE WILL VARY - System.out.println(m.get(d1)); //a5object d1 is used as a key - System.out.println(m.get("k2")); //Getting enum VALUE - System.out.println(m.get(Pets.CATS)); //GETTING STRINGS on enum as a KEY -->enums override equals() and hashCode(). - System.out.println(m.get(new Cat())); //the get() method failed to find the Cat a5object that was inserted earlier.It's easy to see that Dog overrode equals() and hashCode() while Cat didn't. + System.out.println(m.get("1998")); // dOG OBJECT -->THE VALUE WILL VARY + System.out.println(m.get(d1)); // a5object d1 is used as a key + System.out.println(m.get("k2")); // Getting enum VALUE + System.out.println(m.get(Pets.CATS)); // GETTING STRINGS on enum as a KEY -->enums override + // equals() and hashCode(). + System.out.println( + m.get(new Cat())); // the get() method failed to find the Cat a5object that was + // inserted earlier.It's easy to see that Dog overrode equals() + // and hashCode() while Cat didn't. System.out.println(m.size()); } } -class Cat { -} +class Cat {} class Dog { String name; @@ -45,5 +52,3 @@ public int HashCode() { return name.length(); } } - - diff --git a/src/main/java/nitin/collections/d_maps/HashMap/HashMapRevisions.java b/src/main/java/nitin/collections/d_maps/HashMap/HashMapRevisions.java index 67e5699d..9881f899 100644 --- a/src/main/java/nitin/collections/d_maps/HashMap/HashMapRevisions.java +++ b/src/main/java/nitin/collections/d_maps/HashMap/HashMapRevisions.java @@ -5,13 +5,13 @@ public class HashMapRevisions { public static void main(String[] args) { - int[] a = new int[]{10, 20, 30, 40, 50, 60, 70, 80}; + int[] a = new int[] {10, 20, 30, 40, 50, 60, 70, 80}; int target = 150; List list = new ArrayList<>(); Map map = new HashMap<>(); - //Putting in the int array in the HashMap + // Putting in the int array in the HashMap for (int i = 0; i < a.length; i++) { map.put(a[i], target - a[i]); } @@ -21,11 +21,11 @@ public static void main(String[] args) { int key = itr.next(); int value = map.get(key); - //Bug: Fails if target/2 exist in the Array + // Bug: Fails if target/2 exist in the Array if (map.containsKey(value)) { list.add(key); } } System.out.println(list); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/d_maps/LinkedHashMap/LinkedHashMapExample.java b/src/main/java/nitin/collections/d_maps/LinkedHashMap/LinkedHashMapExample.java index 1f3775ab..3e594ebd 100644 --- a/src/main/java/nitin/collections/d_maps/LinkedHashMap/LinkedHashMapExample.java +++ b/src/main/java/nitin/collections/d_maps/LinkedHashMap/LinkedHashMapExample.java @@ -5,8 +5,8 @@ import java.util.function.BiConsumer; /** - * Created by nitin on Monday, October/14/2019 at 1:10 AM - * Linked HashMap keeps the order of insertion intact + * Created by nitin on Monday, October/14/2019 at 1:10 AM Linked HashMap keeps the order of + * insertion intact */ public class LinkedHashMapExample { @@ -17,25 +17,26 @@ public static void main(String[] args) { } // Relativity Assignment in Java8 - //Return a string, ignoring the case of characters like t':5,'h':1,'e':3,' ':4 + // Return a string, ignoring the case of characters like t':5,'h':1,'e':3,' ':4 public static void demo(String str) { - //String.chars returns int streams + // String.chars returns int streams Map map = new LinkedHashMap<>(); - //BiConsumer b1 = map::put; - BiConsumer b2 = (k, v) -> { - //map.put(k, map.getOrDefault(k,1) + 1); - if (map.containsKey(k)) { - map.put(k, map.get(k) + 1); - } else { - map.put(k, 1); - } - }; + // BiConsumer b1 = map::put; + BiConsumer b2 = + (k, v) -> { + // map.put(k, map.getOrDefault(k,1) + 1); + if (map.containsKey(k)) { + map.put(k, map.get(k) + 1); + } else { + map.put(k, 1); + } + }; str.chars() .mapToObj(i -> (char) i) - //Ignoring the case + // Ignoring the case .map(x -> Character.toLowerCase(x)) - //Putting the character and its count into the map + // Putting the character and its count into the map .forEach(x -> b2.accept(x, 0)); String ret = ""; @@ -46,7 +47,7 @@ public static void demo(String str) { ret = ret + "'" + c + "'" + ":" + i + ","; } - //Off by one Error : Removing the last Comma + // Off by one Error : Removing the last Comma System.out.println(ret.substring(0, ret.length() - 1)); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorObjectKey.java b/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorObjectKey.java index 34127019..4b9be253 100644 --- a/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorObjectKey.java +++ b/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorObjectKey.java @@ -1,14 +1,13 @@ package nitin.collections.d_maps.TreeMap; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.Comparator; -import java.util.Set; -import java.util.TreeSet; - public class TreeMapComparatorObjectKey { public static void main(String[] args) { Set set = new TreeSet<>(new CityComparator()); @@ -22,7 +21,6 @@ public static void main(String[] args) { set.add(new City("Sanford", "FL", 32772)); set.add(new City("Sanford", "FL", 32773)); - for (City city : set) { System.out.println(city); } @@ -37,7 +35,7 @@ public static void main(String[] args) { @ToString class City { - //Integer is used so that City.getZip1.compareTo(City.getZip2) be used + // Integer is used so that City.getZip1.compareTo(City.getZip2) be used String name; String state; Integer zip; @@ -48,19 +46,16 @@ class CityComparator implements Comparator { @Override public int compare(City c1, City c2) { - //Level 1 Comparison : City Name (Reverse Sorted) + // Level 1 Comparison : City Name (Reverse Sorted) int cityCompare = c2.getName().compareTo(c1.getName()); - //Level 2 Comparison : State + // Level 2 Comparison : State int stateCompare = c1.getState().compareTo(c2.getState()); - //Level 3 Comparison : Zip + // Level 3 Comparison : Zip int zipCompare = c2.getZip().compareTo(c1.getZip()); - if (cityCompare != 0) - return cityCompare; - if (cityCompare == 0 && stateCompare != 0) - return stateCompare; - //if ( cityCompare == 0 && stateCompare == 0 && zipCompare != 0) + if (cityCompare != 0) return cityCompare; + if (cityCompare == 0 && stateCompare != 0) return stateCompare; + // if ( cityCompare == 0 && stateCompare == 0 && zipCompare != 0) return zipCompare; - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorPrimitiveKey.java b/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorPrimitiveKey.java index bc99d85d..0f31512f 100644 --- a/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorPrimitiveKey.java +++ b/src/main/java/nitin/collections/d_maps/TreeMap/TreeMapComparatorPrimitiveKey.java @@ -6,24 +6,26 @@ public class TreeMapComparatorPrimitiveKey { - //Using Default Comparator + // Using Default Comparator public static void main(String[] args) { - Map map = new TreeMap<>(new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return (o2 - o1); - } - }); + Map map = + new TreeMap<>( + new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return (o2 - o1); + } + }); - String[] arr = new String[]{"", "kumar", "chaurasia"}; + String[] arr = new String[] {"", "kumar", "chaurasia"}; for (int i = 0; i < arr.length; i++) { map.put(i, arr[i]); } - for (Map.Entry entry : - map.entrySet()) { - System.out.println("Key is : " + entry.getKey() + " And value is : " + entry.getValue()); + for (Map.Entry entry : map.entrySet()) { + System.out.println( + "Key is : " + entry.getKey() + " And value is : " + entry.getValue()); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/collections/d_maps/addSameKeyMap.java b/src/main/java/nitin/collections/d_maps/addSameKeyMap.java index f7239854..6eddab5f 100644 --- a/src/main/java/nitin/collections/d_maps/addSameKeyMap.java +++ b/src/main/java/nitin/collections/d_maps/addSameKeyMap.java @@ -4,9 +4,7 @@ import java.util.Iterator; import java.util.Map; -/** - * Created by synergisticit on 2/25/2016. - */ +/** Created by synergisticit on 2/25/2016. */ public class addSameKeyMap { public static void main(String[] args) { Map map = new HashMap(); diff --git a/src/main/java/nitin/collections/iterators/I1EnumerationDemo.java b/src/main/java/nitin/collections/iterators/I1EnumerationDemo.java index 489d88a9..7043577e 100644 --- a/src/main/java/nitin/collections/iterators/I1EnumerationDemo.java +++ b/src/main/java/nitin/collections/iterators/I1EnumerationDemo.java @@ -5,8 +5,8 @@ /** * Created by nitin on 1/13/16. - *

- * Enumeration is used with the Legacy Datastructures like Vector and HashTable + * + *

Enumeration is used with the Legacy Datastructures like Vector and HashTable */ public class I1EnumerationDemo { public static void main(String[] args) { diff --git a/src/main/java/nitin/collections/iterators/I2MapIterators.java b/src/main/java/nitin/collections/iterators/I2MapIterators.java index 71906f9a..28d74d06 100644 --- a/src/main/java/nitin/collections/iterators/I2MapIterators.java +++ b/src/main/java/nitin/collections/iterators/I2MapIterators.java @@ -6,8 +6,8 @@ /** * Created by synergisticit on 2/25/2016. - *

- * 4 ways of iterating the Map + * + *

4 ways of iterating the Map */ public class I2MapIterators { public static void main(String[] args) { @@ -18,25 +18,22 @@ public static void main(String[] args) { map.put("am", 4); map.put("ngram", 5); - //printUsingKeySet(map); - //printUsingEntrySet(map); - //printUsingKeySetForEach(map); + // printUsingKeySet(map); + // printUsingEntrySet(map); + // printUsingKeySetForEach(map); printUsingEntrySetForEach(map); - } private static void printUsingEntrySetForEach(Map map) { for (Map.Entry entry : map.entrySet()) { System.out.println("Key is= " + entry.getKey() + " value= " + entry.getValue()); } - } private static void printUsingKeySetForEach(Map map) { for (String key : map.keySet()) { System.out.println("Key is= " + key + " value= " + map.get(key)); } - } private static void printUsingEntrySet(Map map) { @@ -50,7 +47,6 @@ private static void printUsingEntrySet(Map map) { } } - private static void printUsingKeySet(Map map) { Iterator itr = map.keySet().iterator(); diff --git a/src/main/java/nitin/collections/linkedList/LinkedListExample.java b/src/main/java/nitin/collections/linkedList/LinkedListExample.java index c7303e3a..3f7bd8a1 100644 --- a/src/main/java/nitin/collections/linkedList/LinkedListExample.java +++ b/src/main/java/nitin/collections/linkedList/LinkedListExample.java @@ -36,4 +36,3 @@ public static void main(String[] args) { System.out.println("Final LinkedList: " + linkedList); } } - diff --git a/src/main/java/nitin/collections/unmodifiableCollection/F1ImmutableList.java b/src/main/java/nitin/collections/unmodifiableCollection/F1ImmutableList.java index 45814fd4..0d7d41a5 100644 --- a/src/main/java/nitin/collections/unmodifiableCollection/F1ImmutableList.java +++ b/src/main/java/nitin/collections/unmodifiableCollection/F1ImmutableList.java @@ -2,15 +2,12 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.*; -/** - * Created by Nitin Chaurasia on 2/1/18 at 12:05 AM. - */ +/** Created by Nitin Chaurasia on 2/1/18 at 12:05 AM. */ public class F1ImmutableList { public static void main(String[] args) { - //Traditional way + // Traditional way List list = new ArrayList<>(); list.add(2); @@ -20,45 +17,46 @@ public static void main(String[] args) { list.add(6); list.add(7); - //This is how an unmodifiable collection is created + // This is how an unmodifiable collection is created list = Collections.unmodifiableList(list); - //list.add(3);// java.lang.UnsupportedOperationException + // list.add(3);// java.lang.UnsupportedOperationException - //What is Static Factory Method? + // What is Static Factory Method? // When a static method returns the same Class Object (reference type) of its own class, // its called Static Factory Method Runtime r = Runtime.getRuntime(); /* JAVA 9 Enhancement; of() method is static factory method */ // shortcut way to create UNMODIFIABLE Collection Object (no add or remove works after it) - List l = List.of(2, 3, 4, 5, 6, 7);//upto 10 elements, post which var-arg method + List l = List.of(2, 3, 4, 5, 6, 7); // upto 10 elements, post which var-arg method // but using var arg is costly - //Internally java.util.ImmutableCollections$ListN, inner class is created, not ArrayList or LL + // Internally java.util.ImmutableCollections$ListN, inner class is created, not ArrayList or + // LL System.out.println(l.getClass().getName()); // Element should not be null else NULL POINTER EXCEPTION - //List test = List.of(3,null);//java.lang.NullPointerException + // List test = List.of(3,null);//java.lang.NullPointerException Optional> strOptional = Optional.of(Arrays.asList("John", "Doe")); List stringList = strOptional.get(); int[] arr = {4, 5, 3, 8, 2}; Arrays.sort(arr); - for (int a : arr) - System.out.println(arr); + for (int a : arr) System.out.println(arr); List employees = SampleData.getSimpleEmployees(); - Queue heap = new PriorityQueue<>( - Comparator.comparing(EmployeeSimple::getAge).reversed() - .thenComparing(EmployeeSimple::getSalary).reversed()); + Queue heap = + new PriorityQueue<>( + Comparator.comparing(EmployeeSimple::getAge) + .reversed() + .thenComparing(EmployeeSimple::getSalary) + .reversed()); for (EmployeeSimple emp : employees) { heap.add(emp); } heap.forEach(x -> System.out.println(x.getAge() + x.getName() + x.getSalary())); - - } } diff --git a/src/main/java/nitin/collections/unmodifiableCollection/F2ImmutableSet.java b/src/main/java/nitin/collections/unmodifiableCollection/F2ImmutableSet.java index 70385db4..5b84b9e2 100644 --- a/src/main/java/nitin/collections/unmodifiableCollection/F2ImmutableSet.java +++ b/src/main/java/nitin/collections/unmodifiableCollection/F2ImmutableSet.java @@ -2,15 +2,12 @@ import java.util.Set; -/** - * Created by Nitin Chaurasia on 2/1/18 at 12:26 AM. - */ +/** Created by Nitin Chaurasia on 2/1/18 at 12:26 AM. */ public class F2ImmutableSet { public static void main(String[] args) { // For more elements, internally var args method is called Set set = Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); - System.out.println(set.getClass().getName());//java.util.ImmutableCollections$SetN - + System.out.println(set.getClass().getName()); // java.util.ImmutableCollections$SetN } } diff --git a/src/main/java/nitin/collections/unmodifiableCollection/F3UnmodifiableMap.java b/src/main/java/nitin/collections/unmodifiableCollection/F3UnmodifiableMap.java index 0e1ffe56..3c7ad75a 100644 --- a/src/main/java/nitin/collections/unmodifiableCollection/F3UnmodifiableMap.java +++ b/src/main/java/nitin/collections/unmodifiableCollection/F3UnmodifiableMap.java @@ -2,21 +2,19 @@ import java.util.Map; -/** - * Created by Nitin Chaurasia on 2/1/18 at 12:33 AM. - */ +/** Created by Nitin Chaurasia on 2/1/18 at 12:33 AM. */ public class F3UnmodifiableMap { public static void main(String[] args) { Map map = Map.of(1, "Nitin", 2, "Kirti"); - //null is not allowed either for key or value + // null is not allowed either for key or value - //For more than 10 K-V pairs, have to use ofEntries method + // For more than 10 K-V pairs, have to use ofEntries method - //Creating Map.Entry Object (Entry is an interface inside Map Interface) + // Creating Map.Entry Object (Entry is an interface inside Map Interface) Map.Entry e1 = Map.entry(1, "Test1"); Map.Entry e2 = Map.entry(2, "Test2"); - //Creating unmodifiable Map using ofEntries method + // Creating unmodifiable Map using ofEntries method Map m = Map.ofEntries(e1, e2); System.out.println(m); diff --git a/src/main/java/nitin/collections/unmodifiableCollection/F4SerializationWRTunmodifiableColl.java b/src/main/java/nitin/collections/unmodifiableCollection/F4SerializationWRTunmodifiableColl.java index 8a1b24e7..2848a3a8 100644 --- a/src/main/java/nitin/collections/unmodifiableCollection/F4SerializationWRTunmodifiableColl.java +++ b/src/main/java/nitin/collections/unmodifiableCollection/F4SerializationWRTunmodifiableColl.java @@ -3,30 +3,30 @@ import java.io.*; import java.util.List; -/** - * Created by Nitin Chaurasia on 2/1/18 at 12:47 AM. - */ +/** Created by Nitin Chaurasia on 2/1/18 at 12:47 AM. */ public class F4SerializationWRTunmodifiableColl { - private static final String FILE_NAME = "src/main/java/com/nitin/zjava9/factoryMethodsForUnmodifiableCollection/serialization.txt"; + private static final String FILE_NAME = + "src/main/java/com/nitin/zjava9/factoryMethodsForUnmodifiableCollection/serialization.txt"; public static void main(String[] args) throws IOException, ClassNotFoundException { - //Obtaining the File name + // Obtaining the File name File f = new File(FILE_NAME); - //Creating unmodifiable Collection + // Creating unmodifiable Collection List list = List.of(1, 2, 3, 4, 5); - //Checking if the File exists or not + // Checking if the File exists or not if (!f.exists()) { f.createNewFile(); - //If file by that name does not exist, then create the file + // If file by that name does not exist, then create the file System.out.println("Created File..."); } - /** The Process of Serialization needs File Output Stream to write the Object into the File + /** + * The Process of Serialization needs File Output Stream to write the Object into the File * The Object is written onto the FOS, which inturns writes it in the File - * */ + */ // File Output Stream is needed by ObjectOutputStream FileOutputStream fileOutputStream = new FileOutputStream(f); @@ -37,9 +37,11 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio objectOutputStream.writeObject(list); objectOutputStream.close(); - /** The Process of Deserialization needs File Input Stream to be able to read the Object from the File - * The Object is written onto the FIS, which inturns gives it back to the OIS (ObjectInputStream) - * */ + /** + * The Process of Deserialization needs File Input Stream to be able to read the Object from + * the File The Object is written onto the FIS, which inturns gives it back to the OIS + * (ObjectInputStream) + */ // Opening the Input Stream FileInputStream fileInputStream = new FileInputStream(f); @@ -47,14 +49,13 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio // Opening the ObjectInput Stream ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); - //Read the Object + // Read the Object List d2 = (List) objectInputStream.readObject(); System.out.println(d2); objectInputStream.close(); // Test that list remains unmodifiable even after Deserialization - //d2.add(4);//java.lang.UnsupportedOperationException - + // d2.add(4);//java.lang.UnsupportedOperationException } } diff --git a/src/main/java/nitin/currency/StringFormating4Currency.java b/src/main/java/nitin/currency/StringFormating4Currency.java index 494c205a..a8d020a9 100644 --- a/src/main/java/nitin/currency/StringFormating4Currency.java +++ b/src/main/java/nitin/currency/StringFormating4Currency.java @@ -1,25 +1,32 @@ package nitin.currency; -import org.apache.commons.lang3.math.NumberUtils; - import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import java.util.Locale; +import org.apache.commons.lang3.math.NumberUtils; public class StringFormating4Currency { public static void main(String[] args) { - List number = Arrays.asList("123456.574", "123456789.57445", "12.00", "123", "0.00", null, "test default value"); + List number = + Arrays.asList( + "123456.574", + "123456789.57445", + "12.00", + "123", + "0.00", + null, + "test default value"); for (String temp : number) { // Double.parseDouble does not handle null pointer or number pointer exception - //double amount = Double.parseDouble(temp); + // double amount = Double.parseDouble(temp); double amount = NumberUtils.toDouble(temp, -1L); - //DecimalFormat formatter = new DecimalFormat("#,###.00"); + // DecimalFormat formatter = new DecimalFormat("#,###.00"); NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "CA")); System.out.println(formatter.format(amount)); - //System.out.println(formatter.format(amount).toString()); + // System.out.println(formatter.format(amount).toString()); } } } diff --git a/src/main/java/nitin/enumConcept/Asset.java b/src/main/java/nitin/enumConcept/Asset.java index a53654e9..ce2823eb 100644 --- a/src/main/java/nitin/enumConcept/Asset.java +++ b/src/main/java/nitin/enumConcept/Asset.java @@ -4,15 +4,17 @@ import lombok.Getter; import lombok.Setter; -/** - * Created by nichaurasia on Thursday, February/13/2020 at 2:49 PM - */ - +/** Created by nichaurasia on Thursday, February/13/2020 at 2:49 PM */ @Getter @Setter @AllArgsConstructor public class Asset { private final AssetType assetType; private final int value; - public enum AssetType {BOND, STOCK, COMMODITY} + + public enum AssetType { + BOND, + STOCK, + COMMODITY + } } diff --git a/src/main/java/nitin/enumConcept/AssetRunner.java b/src/main/java/nitin/enumConcept/AssetRunner.java index 914a2623..6124579b 100644 --- a/src/main/java/nitin/enumConcept/AssetRunner.java +++ b/src/main/java/nitin/enumConcept/AssetRunner.java @@ -3,27 +3,27 @@ import java.util.Arrays; import java.util.List; -/** - * Created by nichaurasia on Thursday, February/13/2020 at 2:49 PM - */ - +/** Created by nichaurasia on Thursday, February/13/2020 at 2:49 PM */ public class AssetRunner { public static void main(String[] args) { - List assets = Arrays.asList( - new Asset(Asset.AssetType.STOCK, 1000), - new Asset(Asset.AssetType.STOCK, 2000), - new Asset(Asset.AssetType.BOND, 300), - new Asset(Asset.AssetType.BOND, 500) - ); + List assets = + Arrays.asList( + new Asset(Asset.AssetType.STOCK, 1000), + new Asset(Asset.AssetType.STOCK, 2000), + new Asset(Asset.AssetType.BOND, 300), + new Asset(Asset.AssetType.BOND, 500)); System.out.println("Sum of all Assets"); System.out.println(AssetUtil.totalAssetValues(assets)); System.out.println("Sum of all Assets of type Stock"); - System.out.println(AssetUtil - .totalAssetValuesWithSelector(assets, asset -> asset.getAssetType() == Asset.AssetType.STOCK)); + System.out.println( + AssetUtil.totalAssetValuesWithSelector( + assets, asset -> asset.getAssetType() == Asset.AssetType.STOCK)); System.out.println("Sum of all Assets of type Bond"); - System.out.println(AssetUtil.totalAssetValuesWithSelector(assets, asset -> asset.getAssetType() == Asset.AssetType.BOND)); + System.out.println( + AssetUtil.totalAssetValuesWithSelector( + assets, asset -> asset.getAssetType() == Asset.AssetType.BOND)); } } diff --git a/src/main/java/nitin/enumConcept/AssetUtil.java b/src/main/java/nitin/enumConcept/AssetUtil.java index 9cab0e13..f2481716 100644 --- a/src/main/java/nitin/enumConcept/AssetUtil.java +++ b/src/main/java/nitin/enumConcept/AssetUtil.java @@ -3,28 +3,22 @@ import java.util.List; import java.util.function.Predicate; -/** - * Created by nichaurasia on Thursday, February/13/2020 at 2:49 PM - */ - +/** Created by nichaurasia on Thursday, February/13/2020 at 2:49 PM */ public class AssetUtil { - private AssetUtil() { - } + private AssetUtil() {} public static int totalAssetValues(final List assets) { return assets.stream() - //.filter(asset -> asset.getAssetType() == Asset.AssetType.STOCK) + // .filter(asset -> asset.getAssetType() == Asset.AssetType.STOCK) .filter(asset -> true) .mapToInt(Asset::getValue) .sum(); } - public static int totalAssetValuesWithSelector(final List assets, final Predicate assetSelector) { + public static int totalAssetValuesWithSelector( + final List assets, final Predicate assetSelector) { - return assets.stream() - .filter(assetSelector) - .mapToInt(Asset::getValue) - .sum(); + return assets.stream().filter(assetSelector).mapToInt(Asset::getValue).sum(); } } diff --git a/src/main/java/nitin/enumConcept/EnumDemo.java b/src/main/java/nitin/enumConcept/EnumDemo.java index 78dc7e32..7296578c 100644 --- a/src/main/java/nitin/enumConcept/EnumDemo.java +++ b/src/main/java/nitin/enumConcept/EnumDemo.java @@ -1,7 +1,7 @@ package nitin.enumConcept; public enum EnumDemo { - SUNDAY(1), //calls constructor with value =1 + SUNDAY(1), // calls constructor with value =1 MONDAY(2), TUESDAY(3), WEDNESDAY(4), @@ -18,4 +18,4 @@ public enum EnumDemo { public int getLevelCode() { return this.dayCode; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/enumConcept/EnumUsage.java b/src/main/java/nitin/enumConcept/EnumUsage.java index e9753324..3ea84948 100644 --- a/src/main/java/nitin/enumConcept/EnumUsage.java +++ b/src/main/java/nitin/enumConcept/EnumUsage.java @@ -1,14 +1,11 @@ package nitin.enumConcept; -/** - * Created by nitin on Saturday, October/12/2019 at 10:04 PM - */ +/** Created by nitin on Saturday, October/12/2019 at 10:04 PM */ public class EnumUsage { public static void main(String[] args) { EnumDemo level = EnumDemo.SUNDAY; System.out.println(level.getLevelCode()); System.out.println(level); - } } diff --git a/src/main/java/nitin/enumConcept/enums/Driver.java b/src/main/java/nitin/enumConcept/enums/Driver.java index 0ea60861..98a28e6d 100644 --- a/src/main/java/nitin/enumConcept/enums/Driver.java +++ b/src/main/java/nitin/enumConcept/enums/Driver.java @@ -1,14 +1,12 @@ package nitin.enumConcept.enums; -/** - * Created by Nitin C on 3/5/2016. - */ +/** Created by Nitin C on 3/5/2016. */ public class Driver { public static void main(String[] args) { - Season s = Season.SUMMER;//Calling the ENUM - //Season temp = Season.Summer;// Illegal Argument Exception + Season s = Season.SUMMER; // Calling the ENUM + // Season temp = Season.Summer;// Illegal Argument Exception - System.out.println(s); //summer + System.out.println(s); // summer System.out.println(s == Season.SUMMER); // true // Looping through the ENUM diff --git a/src/main/java/nitin/enumConcept/enums/Season.java b/src/main/java/nitin/enumConcept/enums/Season.java index a9cd145a..822345ad 100644 --- a/src/main/java/nitin/enumConcept/enums/Season.java +++ b/src/main/java/nitin/enumConcept/enums/Season.java @@ -2,9 +2,12 @@ /** * Created by Nitin C on 3/5/2016. - *

- * Enum is like a b_set of constants, thus use the uppercase letter convention + * + *

Enum is like a b_set of constants, thus use the uppercase letter convention */ public enum Season { - WINTER, SPRING, SUMMER, FALL + WINTER, + SPRING, + SUMMER, + FALL } diff --git a/src/main/java/nitin/escapingReferences/Library.java b/src/main/java/nitin/escapingReferences/Library.java index 31d60179..0f4b1d24 100644 --- a/src/main/java/nitin/escapingReferences/Library.java +++ b/src/main/java/nitin/escapingReferences/Library.java @@ -25,4 +25,3 @@ public Book findBook(String bookId) { // Additional methods to manipulate books in the library... } - diff --git a/src/main/java/nitin/escapingReferences/Main.java b/src/main/java/nitin/escapingReferences/Main.java index 5d234594..9e5d0a28 100644 --- a/src/main/java/nitin/escapingReferences/Main.java +++ b/src/main/java/nitin/escapingReferences/Main.java @@ -14,4 +14,3 @@ public static void main(String[] args) { System.out.println(library.findBook("1234567890").getTitle()); // Output: The Great Gatsby } } - diff --git a/src/main/java/nitin/escapingReferences/exercise/Book.java b/src/main/java/nitin/escapingReferences/exercise/Book.java index f47b7199..21cb1da2 100644 --- a/src/main/java/nitin/escapingReferences/exercise/Book.java +++ b/src/main/java/nitin/escapingReferences/exercise/Book.java @@ -36,5 +36,4 @@ public Price getPrice() { public void setPrice(Double price) { this.price = new Price(price); } - } diff --git a/src/main/java/nitin/escapingReferences/exercise/BookCollection.java b/src/main/java/nitin/escapingReferences/exercise/BookCollection.java index c5fff54d..4f2a844d 100644 --- a/src/main/java/nitin/escapingReferences/exercise/BookCollection.java +++ b/src/main/java/nitin/escapingReferences/exercise/BookCollection.java @@ -35,6 +35,4 @@ public void printAllBooks() { System.out.println(book.getTitle() + ": " + book.getPrice()); } } - } - \ No newline at end of file diff --git a/src/main/java/nitin/escapingReferences/exercise/Main.java b/src/main/java/nitin/escapingReferences/exercise/Main.java index 7d187bd4..1d9508b5 100644 --- a/src/main/java/nitin/escapingReferences/exercise/Main.java +++ b/src/main/java/nitin/escapingReferences/exercise/Main.java @@ -5,12 +5,12 @@ public class Main { public static void main(String[] args) { System.out.println("---START OF PROBLEM 1---"); - //Print out the current exchange rates + // Print out the current exchange rates System.out.println("The current exchange rates are USD 1 = "); Price price = new Price(1.0); price.getRates().forEach((k, v) -> System.out.println(k + " " + v)); - //PROBLEM 1 - can we change one of the rates? + // PROBLEM 1 - can we change one of the rates? price.getRates().put("USD", 2d); System.out.println("The current exchange rates are USD 1 = "); price.getRates().forEach((k, v) -> System.out.println(k + " " + v)); @@ -19,11 +19,11 @@ public static void main(String[] args) { System.out.println("---START OF PROBLEM 2---"); - //Get all the books printed out + // Get all the books printed out BookCollection bc = new BookCollection(); bc.printAllBooks(); - //PROBLEM 2 - can we change a book? + // PROBLEM 2 - can we change a book? Book emma = bc.findBookByName("Emma"); emma.setPrice(999d); bc.printAllBooks(); @@ -31,11 +31,11 @@ public static void main(String[] args) { System.out.println("---END OF PROBLEM 2---"); System.out.println("---START OF PROBLEM 3---"); - //Print out the price of the book Tom Jones + // Print out the price of the book Tom Jones Book book = bc.findBookByName("Tom Jones"); System.out.println("Tom Jones costs USD " + book.getPrice()); System.out.println("Tom Jones costs EUR " + book.getPrice().convert("EUR")); System.out.println("Tom Jones costs GBP " + book.getPrice().convert("GBP")); System.out.println("---END OF PROBLEM 3---"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/escapingReferences/exercise/Price.java b/src/main/java/nitin/escapingReferences/exercise/Price.java index 0d074e5a..fc7ec072 100644 --- a/src/main/java/nitin/escapingReferences/exercise/Price.java +++ b/src/main/java/nitin/escapingReferences/exercise/Price.java @@ -34,5 +34,4 @@ public String toString() { public Map getRates() { return rates; } - } diff --git a/src/main/java/nitin/exceptionHandling/E1BasicExceptions.java b/src/main/java/nitin/exceptionHandling/E1BasicExceptions.java index 1a9b6361..1b40404d 100644 --- a/src/main/java/nitin/exceptionHandling/E1BasicExceptions.java +++ b/src/main/java/nitin/exceptionHandling/E1BasicExceptions.java @@ -20,7 +20,7 @@ public static Integer divide(Integer divident, Integer divisor) { } catch (ArithmeticException ae) { System.out.println("Divisor cant be zero, thus returning null"); System.out.println("Exception Thrown message is : " + ae.getMessage()); - //throw new RuntimeException(ae); + // throw new RuntimeException(ae); } finally { System.out.println("This will always run"); } diff --git a/src/main/java/nitin/exceptionHandling/E2TwoCatchBlocks.java b/src/main/java/nitin/exceptionHandling/E2TwoCatchBlocks.java index ae742e34..1917e89b 100644 --- a/src/main/java/nitin/exceptionHandling/E2TwoCatchBlocks.java +++ b/src/main/java/nitin/exceptionHandling/E2TwoCatchBlocks.java @@ -1,13 +1,8 @@ package nitin.exceptionHandling; -/** - * Created by Nitin C on 11/27/2015. - */ - +/** Created by Nitin C on 11/27/2015. */ class X { - public void m1() { - - } + public void m1() {} } public class E2TwoCatchBlocks { @@ -15,7 +10,7 @@ public static void main(String[] args) { int x = 0; X obj = null; try { - obj.m1(); //This occurs first + obj.m1(); // This occurs first x = 5 / 0; x = 10 / 5; } @@ -25,7 +20,7 @@ public static void main(String[] args) { System.out.println("Parent Class should be below Child"); System.out.println(e); } - //Second catch is executed if the AE is not caught. + // Second catch is executed if the AE is not caught. catch (Exception e) { System.out.println(e + "\n" + "Parent Class should be below Child"); } @@ -40,5 +35,4 @@ public static void main(String[] args) { System.out.println("REST OF THE PROGRAM"); } - } diff --git a/src/main/java/nitin/exceptionHandling/E3FinallyMagic.java b/src/main/java/nitin/exceptionHandling/E3FinallyMagic.java index b7206d23..e29e8042 100644 --- a/src/main/java/nitin/exceptionHandling/E3FinallyMagic.java +++ b/src/main/java/nitin/exceptionHandling/E3FinallyMagic.java @@ -2,9 +2,8 @@ /** * Created by Nitin C on 11/27/2015. - *

- * Finally executes even after the return occurs from catch block - * Finally runs even after throws + * + *

Finally executes even after the return occurs from catch block Finally runs even after throws */ public class E3FinallyMagic { public static void main(String[] args) { @@ -13,10 +12,10 @@ public static void main(String[] args) { int i = 5 / 0; } catch (ArithmeticException e) { System.out.println(e); - e.printStackTrace();//behaves like coming from a separate thread + e.printStackTrace(); // behaves like coming from a separate thread // Finally happens even after the return } finally { System.out.println("It executes even after return from catch"); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/exceptionHandling/E4ThrowException.java b/src/main/java/nitin/exceptionHandling/E4ThrowException.java index 0ee6ed45..2e437f18 100644 --- a/src/main/java/nitin/exceptionHandling/E4ThrowException.java +++ b/src/main/java/nitin/exceptionHandling/E4ThrowException.java @@ -1,20 +1,17 @@ package nitin.exceptionHandling; -/** - * Created by Nitin C on 11/27/2015. - */ +/** Created by Nitin C on 11/27/2015. */ public class E4ThrowException { public static void main(String[] args) { try { - //Compiler forces to handle the "throw new exception" - throw new Exception();// Checked exception + // Compiler forces to handle the "throw new exception" + throw new Exception(); // Checked exception } catch (Exception e) { e.printStackTrace(); } - //Exception after this line will not happen + // Exception after this line will not happen System.out.println("AFTER TRY-CATCH"); - } } diff --git a/src/main/java/nitin/exceptionHandling/E5GracefulTermination.java b/src/main/java/nitin/exceptionHandling/E5GracefulTermination.java index 1cac5c5d..73a0400d 100644 --- a/src/main/java/nitin/exceptionHandling/E5GracefulTermination.java +++ b/src/main/java/nitin/exceptionHandling/E5GracefulTermination.java @@ -2,13 +2,9 @@ /** * Created by Nitin C on 11/27/2015. - *

- * User is taken to a LOGICAL Conclusion so that he is given some information + * + *

User is taken to a LOGICAL Conclusion so that he is given some information */ +class Y {} -class Y { - -} - -public class E5GracefulTermination { -} +public class E5GracefulTermination {} diff --git a/src/main/java/nitin/exceptionHandling/E6multicatch.java b/src/main/java/nitin/exceptionHandling/E6multicatch.java index 67cead84..190cc01e 100644 --- a/src/main/java/nitin/exceptionHandling/E6multicatch.java +++ b/src/main/java/nitin/exceptionHandling/E6multicatch.java @@ -10,20 +10,18 @@ import java.time.LocalDate; /** - * Created by Nitin C on 3/5/2016. - * multi-catch block - * In Java 7, they introduce the the ability to catch multiple exceptions in the same catch block. - * catch (FileNotFoundException | IOException e) redundant exceptions gives the error. - * Error MULTI-CATCH Must be disjoint - *

- * Multi-catch is effectively final + * Created by Nitin C on 3/5/2016. multi-catch block In Java 7, they introduce the the ability to + * catch multiple exceptions in the same catch block. catch (FileNotFoundException | IOException e) + * redundant exceptions gives the error. Error MULTI-CATCH Must be disjoint + * + *

Multi-catch is effectively final */ public class E6multicatch { public static void main(String[] args) { String filePath = "src/main/resources/test.txt"; String writeMe = "Testing"; readFile(filePath, writeMe); - //--------------- + // --------------- Path path = Paths.get("text.txt"); String text = null; try { @@ -37,8 +35,9 @@ public static void main(String[] args) { public static Integer readFile(String path, String writeMe) { - //Try with Resource - try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(path)))) { + // Try with Resource + try (ObjectOutputStream oos = + new ObjectOutputStream(new FileOutputStream(new File(path)))) { writeMe = writeMe + " :: " + 1; oos.writeObject(writeMe); diff --git a/src/main/java/nitin/exceptionHandling/E7TryWithResources.java b/src/main/java/nitin/exceptionHandling/E7TryWithResources.java index 727f26c3..9ad261ff 100644 --- a/src/main/java/nitin/exceptionHandling/E7TryWithResources.java +++ b/src/main/java/nitin/exceptionHandling/E7TryWithResources.java @@ -7,13 +7,14 @@ /** * Created by Nitin C on 11/27/2015. - *

- * The try-with-resources syntax was introduced in java 7, automatically closes all resources opened in the - * try clause. This feature is known as automatic resource management - *

- * REMEMBER: Only try-with-resources statement is permitted to omit both that catch and finally blocks - *

- * The resources created in the try clause are only in scope within the try block. + * + *

The try-with-resources syntax was introduced in java 7, automatically closes all resources + * opened in the try clause. This feature is known as automatic resource management + * + *

REMEMBER: Only try-with-resources statement is permitted to omit both that catch and finally + * blocks + * + *

The resources created in the try clause are only in scope within the try block. */ public class E7TryWithResources { public static final String P1 = "src/main/resources/p1.txt"; @@ -32,8 +33,9 @@ public static void main(String[] args) { public static Integer readFile(String path, String writeMe) { - //Try with Resource - try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(path)))) { + // Try with Resource + try (ObjectOutputStream oos = + new ObjectOutputStream(new FileOutputStream(new File(path)))) { oos.writeObject(writeMe); } catch (FileNotFoundException e) { e.printStackTrace(); @@ -45,7 +47,7 @@ public static Integer readFile(String path, String writeMe) { public static void newApproach(Path p1, Path p2) { try (BufferedReader in = Files.newBufferedReader(p1); - BufferedWriter out = Files.newBufferedWriter(p2)) { + BufferedWriter out = Files.newBufferedWriter(p2)) { out.write(in.readLine()); } catch (IOException e) { System.out.println(e.getMessage()); diff --git a/src/main/java/nitin/exceptionHandling/E8AutoCloseable.java b/src/main/java/nitin/exceptionHandling/E8AutoCloseable.java index 1fec57cf..eb93e1b9 100644 --- a/src/main/java/nitin/exceptionHandling/E8AutoCloseable.java +++ b/src/main/java/nitin/exceptionHandling/E8AutoCloseable.java @@ -2,23 +2,22 @@ /** * Created by Nitin Chaurasia on 3/6/16 at 1:15 AM. - *

- * Java Commits to closing automatically any resource opened in the try block. - * For this reason the resource must be closeable!! - *

- * Autocloseable interface has only one method to implement close()!! - *

- * Checked Exception thus have to give a catch block + * + *

Java Commits to closing automatically any resource opened in the try block. For this reason + * the resource must be closeable!! + * + *

Autocloseable interface has only one method to implement close()!! + * + *

Checked Exception thus have to give a catch block */ public class E8AutoCloseable { public static void main(String[] args) { - try (StuckInACage test = new StuckInACage()) {//Throws checked exceptions + try (StuckInACage test = new StuckInACage()) { // Throws checked exceptions System.out.println("Fear Holds you its prisoner!!"); - } catch (Exception e) {// Swollowing the Exception + } catch (Exception e) { // Swollowing the Exception } } - } class StuckInACage implements AutoCloseable { diff --git a/src/main/java/nitin/exceptionHandling/NestedException.java b/src/main/java/nitin/exceptionHandling/NestedException.java index b05fcfb5..4a002fd8 100644 --- a/src/main/java/nitin/exceptionHandling/NestedException.java +++ b/src/main/java/nitin/exceptionHandling/NestedException.java @@ -1,8 +1,6 @@ package nitin.exceptionHandling; -/** - * Created by nitin on Wednesday, September/25/2019 at 8:06 PM - */ +/** Created by nitin on Wednesday, September/25/2019 at 8:06 PM */ public class NestedException { public static void main(String[] args) { String s1 = "Nitin"; @@ -31,4 +29,4 @@ public static void main(String[] args) { e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/exceptionHandling/commonExceptions/E1DivideByZero.java b/src/main/java/nitin/exceptionHandling/commonExceptions/E1DivideByZero.java index 6365f03e..f8cea547 100644 --- a/src/main/java/nitin/exceptionHandling/commonExceptions/E1DivideByZero.java +++ b/src/main/java/nitin/exceptionHandling/commonExceptions/E1DivideByZero.java @@ -1,16 +1,14 @@ package nitin.exceptionHandling.commonExceptions; -/** - * Created by Nitin C on 11/27/2015. - */ +/** Created by Nitin C on 11/27/2015. */ public class E1DivideByZero { public static void main(String[] args) { int x = 0; try { x = 5 / 0; - //x = 10/5; + // x = 10/5; } catch (ArithmeticException e) { - //System.out.println(e.getMessage()); + // System.out.println(e.getMessage()); e.printStackTrace(); } finally { // Will always execute irrespective on the exception or not diff --git a/src/main/java/nitin/exceptionHandling/commonExceptions/E1UnsupportedOperationException.java b/src/main/java/nitin/exceptionHandling/commonExceptions/E1UnsupportedOperationException.java index 0970abba..2911f02e 100644 --- a/src/main/java/nitin/exceptionHandling/commonExceptions/E1UnsupportedOperationException.java +++ b/src/main/java/nitin/exceptionHandling/commonExceptions/E1UnsupportedOperationException.java @@ -2,18 +2,16 @@ import java.util.*; -/** - * Created by nitin on 1/13/16. - */ +/** Created by nitin on 1/13/16. */ public class E1UnsupportedOperationException { public static void main(String[] args) { List list = new ArrayList(); list.add(1); Collection collection = Collections.unmodifiableList(list); - list.add("123"); //Gets added Normally to the a_list + list.add("123"); // Gets added Normally to the a_list - collection.add(55);// Unsupported Operation Exception + collection.add(55); // Unsupported Operation Exception Iterator itr = list.iterator(); while (itr.hasNext()) { diff --git a/src/main/java/nitin/exceptionHandling/commonExceptions/E2ConcurrentModification.java b/src/main/java/nitin/exceptionHandling/commonExceptions/E2ConcurrentModification.java index 357fd03f..e09b6a93 100644 --- a/src/main/java/nitin/exceptionHandling/commonExceptions/E2ConcurrentModification.java +++ b/src/main/java/nitin/exceptionHandling/commonExceptions/E2ConcurrentModification.java @@ -4,10 +4,7 @@ import java.util.Iterator; import java.util.List; -/** - * Created by nitin on 1/13/16. - * While iterating the a_list, if the STRUCTURE IS modified. - */ +/** Created by nitin on 1/13/16. While iterating the a_list, if the STRUCTURE IS modified. */ public class E2ConcurrentModification { public static void main(String[] args) { List list = new ArrayList(); @@ -32,7 +29,7 @@ public static void main(String[] args) { for (int i = 0; i < list.size(); i++) { String currentString = list.get(i); if (currentString.equals("A")) { - String removed = list.remove(i);//No ConcurrentModificationException + String removed = list.remove(i); // No ConcurrentModificationException System.out.println("Removed :: " + removed + " List Size :: " + list.size()); i--; } @@ -60,10 +57,9 @@ public static void main(String[] args) { while (itr.hasNext()) { String currentString = itr.next(); if (currentString.equals("A")) { - //boolean remove = list.remove(currentString);//ConcurrentModificationException - itr.remove();//Will Work as its currently being pointed + // boolean remove = list.remove(currentString);//ConcurrentModificationException + itr.remove(); // Will Work as its currently being pointed System.out.println("Removed :: " + currentString + " List Size :: " + list.size()); - } } diff --git a/src/main/java/nitin/exceptionHandling/customizedExceptions/BusinessException.java b/src/main/java/nitin/exceptionHandling/customizedExceptions/BusinessException.java index 12c2c7c9..42c7cc68 100644 --- a/src/main/java/nitin/exceptionHandling/customizedExceptions/BusinessException.java +++ b/src/main/java/nitin/exceptionHandling/customizedExceptions/BusinessException.java @@ -1,6 +1,5 @@ package nitin.exceptionHandling.customizedExceptions; - public class BusinessException extends Exception { public BusinessException() { super(); diff --git a/src/main/java/nitin/exceptionHandling/customizedExceptions/CannotSwimException.java b/src/main/java/nitin/exceptionHandling/customizedExceptions/CannotSwimException.java index b2facea0..f23c5592 100644 --- a/src/main/java/nitin/exceptionHandling/customizedExceptions/CannotSwimException.java +++ b/src/main/java/nitin/exceptionHandling/customizedExceptions/CannotSwimException.java @@ -2,11 +2,9 @@ /** * Created by Nitin C on 11/27/2015. - *

- * User defined exceptions should ALWAYS be checked - * But you can extend any exception class - * 1. Exception for custom checked exception - * 2. RuntimeException for unchecked + * + *

User defined exceptions should ALWAYS be checked But you can extend any exception class 1. + * Exception for custom checked exception 2. RuntimeException for unchecked */ public class CannotSwimException extends Exception { public CannotSwimException() { diff --git a/src/main/java/nitin/exceptionHandling/customizedExceptions/Driver.java b/src/main/java/nitin/exceptionHandling/customizedExceptions/Driver.java index 42d3977e..de021de5 100644 --- a/src/main/java/nitin/exceptionHandling/customizedExceptions/Driver.java +++ b/src/main/java/nitin/exceptionHandling/customizedExceptions/Driver.java @@ -1,19 +1,16 @@ package nitin.exceptionHandling.customizedExceptions; -/** - * Created by Nitin C on 3/5/2016. - */ +/** Created by Nitin C on 3/5/2016. */ public class Driver { public static void main(String[] args) { - //Compiler wont let the program execute + // Compiler wont let the program execute // throw new CannotSwimException("Nitin"); try { - //throw new CannotSwimException("Nitin executes his custom Exception"); + // throw new CannotSwimException("Nitin executes his custom Exception"); throw new CannotSwimException(); } catch (CannotSwimException e) { e.printStackTrace(); } - } } diff --git a/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/E4ExceptionsAndFunctionalProgramming.java b/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/E4ExceptionsAndFunctionalProgramming.java index 3f2eb9e9..1da26e82 100644 --- a/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/E4ExceptionsAndFunctionalProgramming.java +++ b/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/E4ExceptionsAndFunctionalProgramming.java @@ -9,17 +9,19 @@ public static void main(String[] args) { List listDivisor = List.of(100, 34, 56, 78, 0, 98, 49); listDivisor.stream() - //.map(number -> divide(number, divisor))//try catch -> Incorrect as Functional Programming and Exception handling are mutually exclusive + // .map(number -> divide(number, divisor))//try catch -> Incorrect as Functional + // Programming and Exception handling are mutually exclusive .map(singleDivisor -> tryDivide(dividend, singleDivisor)) .map(result -> result.map(num -> num + 1)) - .map(result -> switch (result) { - case Success data -> data.getResult(); - case Failure err -> err.getError(); - }) + .map( + result -> + switch (result) { + case Success data -> data.getResult(); + case Failure err -> err.getError(); + }) .forEach(System.out::println); - - /*List updatedList = listDivisor.stream() + /*List updatedList = listDivisor.stream() //.map(number -> divide(number, divisor))//try catch -> Incorrect as Functional Programming and Exception handling are mutually exclusive .map(singleDivisor -> tryDivide(dividend, singleDivisor)) .map(result -> result.map(num -> num+1)) @@ -31,8 +33,7 @@ public static void main(String[] args) { System.out.println(updatedList);*/ } - - //If a method throws an IO exception and it has to be used in a Labmda, + // If a method throws an IO exception and it has to be used in a Labmda, public static Integer divide(Integer divident, Integer divisor) throws ArithmeticException { return divident / divisor; } @@ -40,5 +41,4 @@ public static Integer divide(Integer divident, Integer divisor) throws Arithmeti public static Try tryDivide(Integer dividend, Integer divisor) { return Try.of(() -> divide(dividend, divisor)); } - } diff --git a/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/GetHttpMessageFromCode.java b/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/GetHttpMessageFromCode.java index b8f511c0..0a3c8054 100644 --- a/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/GetHttpMessageFromCode.java +++ b/src/main/java/nitin/exceptionHandling/inFunctionalProgramming/GetHttpMessageFromCode.java @@ -12,23 +12,30 @@ public class GetHttpMessageFromCode { private static final String BASE_URL = "https://httpstat.us/"; public static void main(String[] args) throws IOException { - List codeList = Arrays.asList(301, 299, 410, 505, 200, 201, 300);//205 exception - //Imperative style + List codeList = Arrays.asList(301, 299, 410, 505, 200, 201, 300); // 205 exception + // Imperative style /*for(Integer code : codeList){ String httpCodeDef = getHttpCodeDef(Integer.toString(code)); System.out.println(httpCodeDef); }*/ - //Functional Style - codeList - .parallelStream() - .map(code -> tryGetHttpCodeDef(Integer.toString(code)))//If getHttpCodeDef throws an exception, should not use try catch in functional style - //.map(String::toUpperCase) + // Functional Style + codeList.parallelStream() + .map( + code -> + tryGetHttpCodeDef( + Integer.toString( + code))) // If getHttpCodeDef throws an exception, + // should not use try catch in functional + // style + // .map(String::toUpperCase) .map(result -> result.map(String::toUpperCase)) - .map(result -> switch (result) { - case Success data -> data.getResult(); - case Failure err -> err.getError(); - }) + .map( + result -> + switch (result) { + case Success data -> data.getResult(); + case Failure err -> err.getError(); + }) .forEach(code -> System.out.println("Response received from code : " + code)); } @@ -47,18 +54,19 @@ public static String getHttpCodeDef(String code) { HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection(); try { - connection.setRequestMethod("GET");// Set request method - connection.setRequestProperty("Accept", "text/plain");// "application/json" Set headers - connection.setInstanceFollowRedirects(true);// Set instance follow redirects + connection.setRequestMethod("GET"); // Set request method + connection.setRequestProperty( + "Accept", "text/plain"); // "application/json" Set headers + connection.setInstanceFollowRedirects(true); // Set instance follow redirects // Get the HTTP response code int responseCode = connection.getResponseCode(); - if (responseCode >= 300) {//For Status codes for which Exception were thrown + if (responseCode >= 300) { // For Status codes for which Exception were thrown readErrorResponse(connection, response); } else if (responseCode == Integer.parseInt(code)) { readSuccessResponse(connection, response); - } else {//If an irrelevant code is sent + } else { // If an irrelevant code is sent System.out.println("HTTP request code does not exist " + code); } } finally { @@ -73,8 +81,10 @@ public static String getHttpCodeDef(String code) { return response.toString(); } - private static void readErrorResponse(HttpURLConnection connection, StringBuilder response) throws IOException { - try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { + private static void readErrorResponse(HttpURLConnection connection, StringBuilder response) + throws IOException { + try (BufferedReader errorReader = + new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { String line; // Read the response while ((line = errorReader.readLine()) != null) { @@ -83,8 +93,10 @@ private static void readErrorResponse(HttpURLConnection connection, StringBuilde } } - private static void readSuccessResponse(HttpURLConnection connection, StringBuilder response) throws IOException { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + private static void readSuccessResponse(HttpURLConnection connection, StringBuilder response) + throws IOException { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; // Read the response while ((line = reader.readLine()) != null) { @@ -92,4 +104,4 @@ private static void readSuccessResponse(HttpURLConnection connection, StringBuil } } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/garbageCollection/HeapSize.java b/src/main/java/nitin/garbageCollection/HeapSize.java index 8aa2a701..1236eb01 100644 --- a/src/main/java/nitin/garbageCollection/HeapSize.java +++ b/src/main/java/nitin/garbageCollection/HeapSize.java @@ -1,8 +1,6 @@ package nitin.garbageCollection; -/** - * Created by nitin on Thu, 3/9/17 at 9:26 PM. - */ +/** Created by nitin on Thu, 3/9/17 at 9:26 PM. */ public class HeapSize { public static void main(String[] args) { System.out.println("CurrentJVMHeapSize:" + Runtime.getRuntime().totalMemory()); diff --git a/src/main/java/nitin/generic/boundedType/Box.java b/src/main/java/nitin/generic/boundedType/Box.java index 4ada2fee..64bdee9c 100644 --- a/src/main/java/nitin/generic/boundedType/Box.java +++ b/src/main/java/nitin/generic/boundedType/Box.java @@ -4,10 +4,8 @@ import lombok.Setter; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 2:28 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 2:28 AM */ - @Getter @Setter public class Box { diff --git a/src/main/java/nitin/generic/boundedType/Runner.java b/src/main/java/nitin/generic/boundedType/Runner.java index 5294b4fd..e599ae8e 100644 --- a/src/main/java/nitin/generic/boundedType/Runner.java +++ b/src/main/java/nitin/generic/boundedType/Runner.java @@ -1,17 +1,14 @@ package nitin.generic.boundedType; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 2:29 AM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 2:29 AM */ - public class Runner { public static void main(String[] args) { Box integerBox = new Box(); integerBox.setT(Integer.valueOf(10)); - //integerBox.inspect("some text"); // error: this is still String! + // integerBox.inspect("some text"); // error: this is still String! System.out.println("Test"); integerBox.inspect(Integer.valueOf(10)); - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/generic/examples/Calculator.java b/src/main/java/nitin/generic/examples/Calculator.java index 67e814e8..b4bd2dc8 100755 --- a/src/main/java/nitin/generic/examples/Calculator.java +++ b/src/main/java/nitin/generic/examples/Calculator.java @@ -1,6 +1,5 @@ package nitin.generic.examples; - public class Calculator { public static Integer addInteger(Integer a, Integer b) { return a + b; diff --git a/src/main/java/nitin/generic/examples/CalculatorExample.java b/src/main/java/nitin/generic/examples/CalculatorExample.java index 469d7ad9..27c3f9e6 100755 --- a/src/main/java/nitin/generic/examples/CalculatorExample.java +++ b/src/main/java/nitin/generic/examples/CalculatorExample.java @@ -17,6 +17,6 @@ public static void main(String[] args) { // Causes a ClassCastException because String is not a subtype of java.lang.Number // double genericValue3 = Calculator.add("Not valid", 3f); - //System.out.println("The invalid result: " + genericValue3); + // System.out.println("The invalid result: " + genericValue3); } } diff --git a/src/main/java/nitin/generic/examples/GenericNumberContainer.java b/src/main/java/nitin/generic/examples/GenericNumberContainer.java index 6ce1743b..7237fa93 100755 --- a/src/main/java/nitin/generic/examples/GenericNumberContainer.java +++ b/src/main/java/nitin/generic/examples/GenericNumberContainer.java @@ -1,11 +1,9 @@ package nitin.generic.examples; - public class GenericNumberContainer { private T obj; - public GenericNumberContainer() { - } + public GenericNumberContainer() {} public GenericNumberContainer(T t) { obj = t; @@ -15,9 +13,7 @@ public T getObj() { return obj; } - public void setObj(T t) { obj = t; } } - diff --git a/src/main/java/nitin/generic/examples/GenericNumberContainerExamples.java b/src/main/java/nitin/generic/examples/GenericNumberContainerExamples.java index f197d5c0..b51a6df2 100755 --- a/src/main/java/nitin/generic/examples/GenericNumberContainerExamples.java +++ b/src/main/java/nitin/generic/examples/GenericNumberContainerExamples.java @@ -8,6 +8,6 @@ public static void main(String[] args) { GenericNumberContainer gn = new GenericNumberContainer(); gn.setObj(3); // Type argument String is not within the upper bounds of type-variable T - //GenericNumberContainer gn2 = new GenericNumberContainer(); + // GenericNumberContainer gn2 = new GenericNumberContainer(); } } diff --git a/src/main/java/nitin/generic/examples/LambdaExample.java b/src/main/java/nitin/generic/examples/LambdaExample.java index 3cadf5d1..3df39872 100755 --- a/src/main/java/nitin/generic/examples/LambdaExample.java +++ b/src/main/java/nitin/generic/examples/LambdaExample.java @@ -19,9 +19,11 @@ public static void main(String[] args) { } public static void compareStrings(List list, Predicate predicate) { - list.stream().filter((n) -> (predicate.test(n))).forEach((n) -> { - System.out.println(n + " "); - }); + list.stream() + .filter((n) -> (predicate.test(n))) + .forEach( + (n) -> { + System.out.println(n + " "); + }); } - } diff --git a/src/main/java/nitin/generic/examples/MultiGenericContainer.java b/src/main/java/nitin/generic/examples/MultiGenericContainer.java index 9ee85249..61ab18c0 100755 --- a/src/main/java/nitin/generic/examples/MultiGenericContainer.java +++ b/src/main/java/nitin/generic/examples/MultiGenericContainer.java @@ -29,5 +29,4 @@ public S getSecondPosition() { public void setSecondPosition(S secondPosition) { this.secondPosition = secondPosition; } - } diff --git a/src/main/java/nitin/generic/examples/MultiGenericContainerExample.java b/src/main/java/nitin/generic/examples/MultiGenericContainerExample.java index 262966e2..ab233303 100755 --- a/src/main/java/nitin/generic/examples/MultiGenericContainerExample.java +++ b/src/main/java/nitin/generic/examples/MultiGenericContainerExample.java @@ -24,6 +24,5 @@ public static void main(String[] args) { // as the secondPosition will result in a compiler error // mondayWeather.setSecondPosition(80.0); - } } diff --git a/src/main/java/nitin/generic/examples/ObjectContainer.java b/src/main/java/nitin/generic/examples/ObjectContainer.java index 9033fb3a..d27a3cda 100755 --- a/src/main/java/nitin/generic/examples/ObjectContainer.java +++ b/src/main/java/nitin/generic/examples/ObjectContainer.java @@ -21,5 +21,4 @@ public Object getObj() { public void setObj(Object obj) { this.obj = obj; } - } diff --git a/src/main/java/nitin/generic/examples/ObjectExample.java b/src/main/java/nitin/generic/examples/ObjectExample.java index 12e96235..5e9d70d5 100755 --- a/src/main/java/nitin/generic/examples/ObjectExample.java +++ b/src/main/java/nitin/generic/examples/ObjectExample.java @@ -23,22 +23,23 @@ public static void testObject() { List objectList = new ArrayList(); objectList.add(myObj); // We have to cast...and we must be sure to cast the correct type! - // String myStr = (String) ((ObjectContainer)objectList.get(0)).getObj(); // ClassCastException + // String myStr = (String) ((ObjectContainer)objectList.get(0)).getObj(); // + // ClassCastException } /** - * Utilizing a container that uses generics allows us to store any type - * of data within the a5object in a type-safe manner + * Utilizing a container that uses generics allows us to store any type of data within the + * a5object in a type-safe manner */ public static void testGenerics() { GenericContainer stringContainer = new GenericContainer(); stringContainer.setObj("Test"); - //stringContainer.setObj(3); // will not compile...type error + // stringContainer.setObj(3); // will not compile...type error System.out.println("Value of stringContainer :" + stringContainer.getObj()); GenericContainer intContainer = new GenericContainer(); intContainer.setObj(3); intContainer.setObj(5); - //intContainer.setObj("Int"); // will not compile + // intContainer.setObj("Int"); // will not compile System.out.println("Value of intContainer: " + intContainer.getObj()); } diff --git a/src/main/java/nitin/generic/examples/WildcardExample.java b/src/main/java/nitin/generic/examples/WildcardExample.java index 2e48f638..9a1f17f6 100755 --- a/src/main/java/nitin/generic/examples/WildcardExample.java +++ b/src/main/java/nitin/generic/examples/WildcardExample.java @@ -38,7 +38,7 @@ public static void main(String[] args) { checkNumber(intList, 3); // The following will not work since strList is not a List of Number types - //checkNumber(strList, "three"); + // checkNumber(strList, "three"); } /** diff --git a/src/main/java/nitin/generic/examples/coffeehouse/CoffeeBag.java b/src/main/java/nitin/generic/examples/coffeehouse/CoffeeBag.java index 3bf0c6db..df31f53e 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/CoffeeBag.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/CoffeeBag.java @@ -1,6 +1,5 @@ package nitin.generic.examples.coffeehouse; - public class CoffeeBag implements Bag { private double ounces; @@ -33,5 +32,4 @@ public CoffeeType getType() { public void setType(CoffeeType type) { this.type = type; } - } diff --git a/src/main/java/nitin/generic/examples/coffeehouse/CoffeeCup.java b/src/main/java/nitin/generic/examples/coffeehouse/CoffeeCup.java index ece4f55d..18911dc6 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/CoffeeCup.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/CoffeeCup.java @@ -7,8 +7,7 @@ public class CoffeeCup implements Cup { private double cupSize; private CoffeeType type; - public CoffeeCup(CoffeeType type, - double cupSize) { + public CoffeeCup(CoffeeType type, double cupSize) { this.type = type; this.cupSize = cupSize; } @@ -40,6 +39,4 @@ public CoffeeType getType() { public void setType(CoffeeType type) { this.type = type; } - - } diff --git a/src/main/java/nitin/generic/examples/coffeehouse/Dark.java b/src/main/java/nitin/generic/examples/coffeehouse/Dark.java index 20cf018f..a50dc11f 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/Dark.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/Dark.java @@ -3,6 +3,4 @@ /** * @author Juneau */ -public interface Dark { - -} +public interface Dark {} diff --git a/src/main/java/nitin/generic/examples/coffeehouse/DoughnutRoast.java b/src/main/java/nitin/generic/examples/coffeehouse/DoughnutRoast.java index 3880099d..9cfa176e 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/DoughnutRoast.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/DoughnutRoast.java @@ -20,6 +20,4 @@ public DoughnutRoast() { public List getDescription() { return description; } - - } diff --git a/src/main/java/nitin/generic/examples/coffeehouse/FrenchRoast.java b/src/main/java/nitin/generic/examples/coffeehouse/FrenchRoast.java index 5715effe..ca4398a2 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/FrenchRoast.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/FrenchRoast.java @@ -20,6 +20,4 @@ public FrenchRoast() { public List getDescription() { return description; } - - } diff --git a/src/main/java/nitin/generic/examples/coffeehouse/HouseBlend.java b/src/main/java/nitin/generic/examples/coffeehouse/HouseBlend.java index d1cc4697..ba4a2d54 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/HouseBlend.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/HouseBlend.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; - /** * @author Juneau */ @@ -20,7 +19,4 @@ public HouseBlend() { public List getDescription() { return description; } - - } - diff --git a/src/main/java/nitin/generic/examples/coffeehouse/ItalianRoast.java b/src/main/java/nitin/generic/examples/coffeehouse/ItalianRoast.java index 50ebc139..2745e4d9 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/ItalianRoast.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/ItalianRoast.java @@ -27,5 +27,4 @@ public ItalianRoast() { public List getDescription() { return description; } - } diff --git a/src/main/java/nitin/generic/examples/coffeehouse/JavaHouse.java b/src/main/java/nitin/generic/examples/coffeehouse/JavaHouse.java index a9a76dc9..bb0c8e5e 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/JavaHouse.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/JavaHouse.java @@ -17,9 +17,7 @@ public class JavaHouse { List mediumTypes = new ArrayList<>(); List lightTypes = new ArrayList<>(); - public JavaHouse() { - - } + public JavaHouse() {} /** * Return the total purchase list @@ -75,8 +73,8 @@ public void addBags(List bags) { } /** - * Add a list of CoffeeSaleType objects to the purchase This List can - * consist of either bags or cups + * Add a list of CoffeeSaleType objects to the purchase This List can consist of either bags or + * cups * * @param * @param saleList @@ -88,8 +86,8 @@ public void addToPurchase(List saleList) { } /** - * A utility function to add all cups and bags purchased to the purchase - * list, and print out some useful labels. + * A utility function to add all cups and bags purchased to the purchase list, and print out + * some useful labels. */ public void checkout() { System.out.println("Cups Purchased"); @@ -103,8 +101,7 @@ public void checkout() { } /** - * Prints the purchase out. Accepts Lists of CoffeeSaleType objects (bags or - * cups). + * Prints the purchase out. Accepts Lists of CoffeeSaleType objects (bags or cups). * * @param input */ @@ -115,26 +112,25 @@ private void printPurchase(List input) { } /** - * Returns the number of purchase of type T. This method uses a stream on - * the purchase list, then filters upon the specified CoffeeType, and finally - * returns a count + * Returns the number of purchase of type T. This method uses a stream on the purchase list, + * then filters upon the specified CoffeeType, and finally returns a count * * @param * @param coffeeType * @return */ public long countTypes(T coffeeType) { - long count = purchase.stream().filter( - (sale) -> (sale.getType().getType().equals(coffeeType))) - .count(); + long count = + purchase.stream() + .filter((sale) -> (sale.getType().getType().equals(coffeeType))) + .count(); return count; } /** - * This method accepts a purchase list (List of CoffeeSaleTypes), and extracts - * the individual CoffeeType from each element within the purchase list. It - * then determines if the CoffeeType is an instance of Dark, Medium, or Light, - * and places it into the appropriate container. + * This method accepts a purchase list (List of CoffeeSaleTypes), and extracts the individual + * CoffeeType from each element within the purchase list. It then determines if the CoffeeType + * is an instance of Dark, Medium, or Light, and places it into the appropriate container. * * @param coffeeSale */ @@ -157,6 +153,5 @@ public void sortByCoffeeStrength(List coffeeSale) { System.out.println("Number of Dark Types: " + darkTypes.size()); System.out.println("Number of Medium Types: " + mediumTypes.size()); System.out.println("Number of Light Types: " + lightTypes.size()); - } } diff --git a/src/main/java/nitin/generic/examples/coffeehouse/JavaHouseVisit.java b/src/main/java/nitin/generic/examples/coffeehouse/JavaHouseVisit.java index 03a11abc..8f5cd360 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/JavaHouseVisit.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/JavaHouseVisit.java @@ -14,7 +14,7 @@ public static void main(String[] args) { javaHouse.addCup(new FrenchRoast(), 16); javaHouse.addBag(new ItalianRoast(), 12); javaHouse.addBag(new DoughnutRoast(), 6); - //javaHouse.addCup(Integer.valueOf(3), 3); Not a CoffeeType, so does not compile + // javaHouse.addCup(Integer.valueOf(3), 3); Not a CoffeeType, so does not compile javaHouse.checkout(); // Retrieve the current purchase list @@ -23,14 +23,17 @@ public static void main(String[] args) { // Print some further details on the purchased types to learn what our // customer enjoys - purchaseList.stream().forEach((coffeeSale) -> { - System.out.println(coffeeSale.getType().getType() + " Description - " + - coffeeSale.getType().getDescription()); - }); + purchaseList.stream() + .forEach( + (coffeeSale) -> { + System.out.println( + coffeeSale.getType().getType() + + " Description - " + + coffeeSale.getType().getDescription()); + }); // How many of the ItalianRoast are contained in this purchase - System.out.println("Number of Italian Roasts: " + - javaHouse.countTypes(ItalianRoast.class)); + System.out.println("Number of Italian Roasts: " + javaHouse.countTypes(ItalianRoast.class)); List coffeeList = new ArrayList(); coffeeList.add(new DoughnutRoast()); @@ -45,7 +48,6 @@ public static void main(String[] args) { compareCoffee(coffeeList, (n) -> n.getDescription().contains(CoffeeType.AROMATIC)); System.out.println("Ground"); compareCoffee(coffeeList, (n) -> n.getDescription().contains(CoffeeType.GROUND)); - } /** @@ -55,9 +57,11 @@ public static void main(String[] args) { * @param predicate */ public static void compareCoffee(List list, Predicate predicate) { - list.stream().filter((n) -> (predicate.test(n))).forEach((n) -> { - System.out.println(n + " "); - }); + list.stream() + .filter((n) -> (predicate.test(n))) + .forEach( + (n) -> { + System.out.println(n + " "); + }); } } - diff --git a/src/main/java/nitin/generic/examples/coffeehouse/Light.java b/src/main/java/nitin/generic/examples/coffeehouse/Light.java index a9fdd18f..d9e58135 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/Light.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/Light.java @@ -9,6 +9,4 @@ /** * @author Juneau */ -public interface Light { - -} +public interface Light {} diff --git a/src/main/java/nitin/generic/examples/coffeehouse/Medium.java b/src/main/java/nitin/generic/examples/coffeehouse/Medium.java index 81618307..ebf54614 100755 --- a/src/main/java/nitin/generic/examples/coffeehouse/Medium.java +++ b/src/main/java/nitin/generic/examples/coffeehouse/Medium.java @@ -9,6 +9,4 @@ /** * @author Juneau */ -public interface Medium { - -} +public interface Medium {} diff --git a/src/main/java/nitin/generic/oReilly/Why.java b/src/main/java/nitin/generic/oReilly/Why.java index c32f49e0..0a0eb1fb 100644 --- a/src/main/java/nitin/generic/oReilly/Why.java +++ b/src/main/java/nitin/generic/oReilly/Why.java @@ -1,8 +1,4 @@ package nitin.generic.oReilly; -/** - * Created by nichaurasia on Friday, May/15/2020 at 10:26 PM - */ - -public class Why { -} +/** Created by nichaurasia on Friday, May/15/2020 at 10:26 PM */ +public class Why {} diff --git a/src/main/java/nitin/generic/oReilly/a0raw/C0RawTypesVSGenerics.java b/src/main/java/nitin/generic/oReilly/a0raw/C0RawTypesVSGenerics.java index a5ae7901..efb12672 100644 --- a/src/main/java/nitin/generic/oReilly/a0raw/C0RawTypesVSGenerics.java +++ b/src/main/java/nitin/generic/oReilly/a0raw/C0RawTypesVSGenerics.java @@ -3,38 +3,35 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by Nitin C on 12/7/2015. - */ - -/** - * Created by nichaurasia on Friday, May/15/2020 at 10:26 PM - */ +/** Created by Nitin C on 12/7/2015. */ +/** Created by nichaurasia on Friday, May/15/2020 at 10:26 PM */ public class C0RawTypesVSGenerics { public static void main(String[] args) { rawCollection(); - /*With the help of Generics, the possible runtime Exceptions can be converted to + /*With the help of Generics, the possible runtime Exceptions can be converted to Compile time Exceptions */ - genericCollection();//Types Collection + genericCollection(); // Types Collection } private static void genericCollection() { List strings = new ArrayList(); strings.add("This"); strings.add("is a raw List"); - //Gives a compile time exception - java: incompatible types: java.time.LocalDate cannot be converted to java.lang.String - //strings.add(LocalDate.now()); + // Gives a compile time exception - java: incompatible types: java.time.LocalDate cannot be + // converted to java.lang.String + // strings.add(LocalDate.now()); - //Still a chance of Null pointer exception. Use null check before String operation of s.length() + // Still a chance of Null pointer exception. Use null check before String operation of + // s.length() strings.add(null); System.out.println("From Generic Collection"); -// for (String s : strings) { -// if (s != null) { -// System.out.printf("%s has %d characters \n", s, s.length()); -// } -// } + // for (String s : strings) { + // if (s != null) { + // System.out.printf("%s has %d characters \n", s, s.length()); + // } + // } System.out.println("***********************"); } @@ -42,24 +39,25 @@ private static void rawCollection() { List strings = new ArrayList(); strings.add("This"); strings.add("is a raw List"); - //This causes runtime exception if the instanceOF check is not performed. - //strings.add(LocalDate.now()); - //Invokes ClassCastException: class java.time.LocalDate cannot be cast to class java.lang.String + // This causes runtime exception if the instanceOF check is not performed. + // strings.add(LocalDate.now()); + // Invokes ClassCastException: class java.time.LocalDate cannot be cast to class + // java.lang.String - //Cause of null pointer exception + // Cause of null pointer exception // strings.add(null); - //Wrong data type accepted + // Wrong data type accepted strings.add(3); System.out.println("From rawCollection"); for (Object o : strings) { String s = (String) o; System.out.printf("%s has %d characters \n", s, s.length()); -// if(null != strings && o instanceof String){ -// String s = (String) o; -// System.out.printf("%s has %d characters \n",s,s.length()); -// } + // if(null != strings && o instanceof String){ + // String s = (String) o; + // System.out.printf("%s has %d characters \n",s,s.length()); + // } } System.out.println("***********************"); } diff --git a/src/main/java/nitin/generic/oReilly/a0raw/C1TypedAutoBoxingNUnboxing.java b/src/main/java/nitin/generic/oReilly/a0raw/C1TypedAutoBoxingNUnboxing.java index e85fc527..ae76b1cf 100644 --- a/src/main/java/nitin/generic/oReilly/a0raw/C1TypedAutoBoxingNUnboxing.java +++ b/src/main/java/nitin/generic/oReilly/a0raw/C1TypedAutoBoxingNUnboxing.java @@ -3,20 +3,17 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by Nitin C on 3/4/2016. - */ +/** Created by Nitin C on 3/4/2016. */ public class C1TypedAutoBoxingNUnboxing { public static void main(String[] args) { - //Generics do not accept primitive types - //Java does the auto boxing and unboxing + // Generics do not accept primitive types + // Java does the auto boxing and unboxing List intsList = new ArrayList<>(); - intsList.add(3);//Adding primitive - intsList.add(Integer.valueOf(4));//Unnecessasary Boxing + intsList.add(3); // Adding primitive + intsList.add(Integer.valueOf(4)); // Unnecessasary Boxing int x = intsList.get(0); - int y = intsList.get(1);//Auto unboxing performed and assigned to a primitive + int y = intsList.get(1); // Auto unboxing performed and assigned to a primitive } - } diff --git a/src/main/java/nitin/generic/oReilly/a1Inheritance/BasicInheritance.java b/src/main/java/nitin/generic/oReilly/a1Inheritance/BasicInheritance.java index e926c096..c31398a8 100644 --- a/src/main/java/nitin/generic/oReilly/a1Inheritance/BasicInheritance.java +++ b/src/main/java/nitin/generic/oReilly/a1Inheritance/BasicInheritance.java @@ -6,7 +6,7 @@ public class BasicInheritance { public static void main(String[] args) { - //Generic list of a5object that can have any type of Object + // Generic list of a5object that can have any type of Object List objects = new ArrayList<>(); objects.add("string"); objects.add(LocalDateTime.now()); @@ -16,15 +16,17 @@ public static void main(String[] args) { List strings = new ArrayList<>(); - //Compile time error - //incompatible types: java.util.List cannot be converted to java.util.List - //List objectsTest = strings;//eventhough Object is super class of strings + // Compile time error + // incompatible types: java.util.List cannot be converted to + // java.util.List + // List objectsTest = strings;//eventhough Object is super class of strings /* List of Strings is not a subclass of List of Objects */ - Object o = "anotherString"; //String is subclass of Object so this is Valid + Object o = "anotherString"; // String is subclass of Object so this is Valid - //Compile time error:Error:incompatible types: java.lang.Object cannot be converted to java.lang.String - //strings.add(o); + // Compile time error:Error:incompatible types: java.lang.Object cannot be converted to + // java.lang.String + // strings.add(o); strings.add((String) o); System.out.println(strings); diff --git a/src/main/java/nitin/generic/oReilly/a1Inheritance/C3GenericWRTInheritence.java b/src/main/java/nitin/generic/oReilly/a1Inheritance/C3GenericWRTInheritence.java index 21ccc2c5..b32e107a 100644 --- a/src/main/java/nitin/generic/oReilly/a1Inheritance/C3GenericWRTInheritence.java +++ b/src/main/java/nitin/generic/oReilly/a1Inheritance/C3GenericWRTInheritence.java @@ -3,28 +3,25 @@ import java.util.Arrays; import java.util.List; -/** - * Created by nichaurasia on Friday, May/15/2020 at 11:43 PM - */ - +/** Created by nichaurasia on Friday, May/15/2020 at 11:43 PM */ public class C3GenericWRTInheritence { public static void main(String[] args) { List numbers = Arrays.asList(1, 2, 3, 4, 5); System.out.println(sumList(numbers)); - //The Inheritance process is NOT LEGAL between the collections. + // The Inheritance process is NOT LEGAL between the collections. List ints = Arrays.asList(1, 2, 3, 4, 5); /* Even though Integer is Child class of Number, the below is illegal */ - //System.out.println(sumList(ints)); + // System.out.println(sumList(ints)); /* incompatible types: java.util.List cannot be converted to java.util.List */ - //THIS PROBLEM IS RESOLVED WITH WILDCARDS + // THIS PROBLEM IS RESOLVED WITH WILDCARDS } - //Sum List accepts a List of numbers whihc is a super class of all the numbers (see Read me) + // Sum List accepts a List of numbers whihc is a super class of all the numbers (see Read me) private static int sumList(List numbers) { return numbers.stream() - //.mapToInt(x -> x.intValue()) + // .mapToInt(x -> x.intValue()) .mapToInt(Number::intValue) .sum(); } diff --git a/src/main/java/nitin/generic/oReilly/a2Wildcards/B1Unbounded.java b/src/main/java/nitin/generic/oReilly/a2Wildcards/B1Unbounded.java index 75d8c16b..5316d7c3 100644 --- a/src/main/java/nitin/generic/oReilly/a2Wildcards/B1Unbounded.java +++ b/src/main/java/nitin/generic/oReilly/a2Wildcards/B1Unbounded.java @@ -4,22 +4,23 @@ import java.util.Arrays; import java.util.List; -//The idea behind the question mark operator is that when we declare a collection of that type, +// The idea behind the question mark operator is that when we declare a collection of that type, // we're saying we don't know what the underlying type is public class B1Unbounded { public static void main(String[] args) { List list = Arrays.asList((22 / 7), "test", LocalDate.now(), 'c'); - //size method is independent of underlying data type + // size method is independent of underlying data type System.out.println(list.size()); - //Invoking Lambda on the list + // Invoking Lambda on the list list.forEach((Object o) -> System.out.println(o)); // Cannot write to it. - //list.add("another String");//incompatible types: java.lang.String cannot be converted to capture#1 of ? + // list.add("another String");//incompatible types: java.lang.String cannot be converted to + // capture#1 of ? - //CHECK THE contailsAll() METHOD + // CHECK THE contailsAll() METHOD System.out.println(list.containsAll(Arrays.asList("test", (22 / 7)))); } } diff --git a/src/main/java/nitin/generic/oReilly/a2Wildcards/B2UpperBounds.java b/src/main/java/nitin/generic/oReilly/a2Wildcards/B2UpperBounds.java index af20c8e2..c2cdc94d 100644 --- a/src/main/java/nitin/generic/oReilly/a2Wildcards/B2UpperBounds.java +++ b/src/main/java/nitin/generic/oReilly/a2Wildcards/B2UpperBounds.java @@ -9,19 +9,19 @@ public class B2UpperBounds { public static void main(String[] args) { List numbers = new ArrayList<>(); - //Cannot be added into, like Unbounded + // Cannot be added into, like Unbounded // numbers.add(3); - //inheritanceProblemSolved(); + // inheritanceProblemSolved(); List list = Arrays.asList(3.14, (22 / 7), 1.00, 2); callMethodsOfBoundedClass(list); /* - * Generic java collections are covarient - * when extends is used with a wild card - * this means - if you declare a collection, with a bounded wildcard, - you can use methods from the Bound (AClass) - * Eg: ? extends Number, the methods of Number can also be used - * USING -> List each element Supports Number methods as well, along with ? */ + * Generic java collections are covarient + * when extends is used with a wild card + * this means - if you declare a collection, with a bounded wildcard, + you can use methods from the Bound (AClass) + * Eg: ? extends Number, the methods of Number can also be used + * USING -> List each element Supports Number methods as well, along with ? */ } private static void callMethodsOfBoundedClass(List list) { @@ -29,8 +29,7 @@ private static void callMethodsOfBoundedClass(List list) { // Function to convert Strings to Int, put 9999 as default value for other cases Function function = x -> x.toString(); - list.stream().map(function) - .forEach((x) -> System.out.println(x)); + list.stream().map(function).forEach((x) -> System.out.println(x)); } private static void inheritanceProblemSolved() { @@ -46,7 +45,7 @@ private static void inheritanceProblemSolved() { // Upper bounds solves the problem. Number and its child classes can be used (see ReadMe). private static Double sumList(List list) { return list.stream() - .mapToDouble(Number::doubleValue)//Using Number as the Upper Bound Class + .mapToDouble(Number::doubleValue) // Using Number as the Upper Bound Class .sum(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/generic/oReilly/a2Wildcards/B3LowerBounds.java b/src/main/java/nitin/generic/oReilly/a2Wildcards/B3LowerBounds.java index 2576c340..656f89cd 100644 --- a/src/main/java/nitin/generic/oReilly/a2Wildcards/B3LowerBounds.java +++ b/src/main/java/nitin/generic/oReilly/a2Wildcards/B3LowerBounds.java @@ -7,21 +7,39 @@ public class B3LowerBounds { public static void main(String[] args) { - List strings = Stream.of("a", "few", "strings") - .collect(Collectors.toList()); + List strings = Stream.of("a", "few", "strings").collect(Collectors.toList()); - strings.forEach((String s) -> System.out.printf("%s in all caps is %s%n", s, s.toUpperCase())); + strings.forEach( + (String s) -> System.out.printf("%s in all caps is %s%n", s, s.toUpperCase())); System.out.println("****************************"); strings.forEach((Object o) -> System.out.printf("%s has hashCode %d%n", o, o.hashCode())); System.out.println("****************************"); // Stream peek(Consumer action); // Using Methods of Integer and Above - List integers = Stream.of(3, 1, 4, 1, 5, 998) - .peek(i -> System.out.println(i + " as a binary string is " + Integer.toBinaryString(i))) - .peek((Number n) -> System.out.println("The double value of " + n + " is " + n.doubleValue())) - .peek((Object o) -> System.out.println("The default hashcode of " + o + " is " + o.hashCode())) - .collect(Collectors.toList()); + List integers = + Stream.of(3, 1, 4, 1, 5, 998) + .peek( + i -> + System.out.println( + i + + " as a binary string is " + + Integer.toBinaryString(i))) + .peek( + (Number n) -> + System.out.println( + "The double value of " + + n + + " is " + + n.doubleValue())) + .peek( + (Object o) -> + System.out.println( + "The default hashcode of " + + o + + " is " + + o.hashCode())) + .collect(Collectors.toList()); System.out.println("****************************"); System.out.println(integers); diff --git a/src/main/java/nitin/generic/oReilly/a3Max/MaxEmployeeRunner.java b/src/main/java/nitin/generic/oReilly/a3Max/MaxEmployeeRunner.java index 4b87c82a..b0e68c77 100644 --- a/src/main/java/nitin/generic/oReilly/a3Max/MaxEmployeeRunner.java +++ b/src/main/java/nitin/generic/oReilly/a3Max/MaxEmployeeRunner.java @@ -1,12 +1,12 @@ package nitin.generic.oReilly.a3Max; +import static java.util.Comparator.comparing; +import static java.util.Comparator.comparingInt; + import java.util.Arrays; import java.util.Comparator; import java.util.List; -import static java.util.Comparator.comparing; -import static java.util.Comparator.comparingInt; - public class MaxEmployeeRunner { private Employee maxId1; @@ -15,22 +15,26 @@ public static void main(String[] args) { List employees = createEmployees(); System.out.println("With Comparator of T, Employee"); - Employee maxId0 = employees.stream() - //Since no comparator is implemented by Employee class, we can still find max by providing the implementation here - .max(new Comparator() {// Anonymous Class - @Override - public int compare(Employee o1, Employee o2) { - return o1.getId() - o2.getId(); - } - }) - .orElse(Employee.DEFAULT_EMPLOYEE); + Employee maxId0 = + employees.stream() + // Since no comparator is implemented by Employee class, we can still find + // max by providing the implementation here + .max( + new Comparator() { // Anonymous Class + @Override + public int compare(Employee o1, Employee o2) { + return o1.getId() - o2.getId(); + } + }) + .orElse(Employee.DEFAULT_EMPLOYEE); System.out.println(maxId0); // LAMBDA-FICATION - Employee maxId = employees.stream() - .max((Employee e1, Employee e2) -> e1.getId() - e2.getId()) - .orElse(Employee.DEFAULT_EMPLOYEE); + Employee maxId = + employees.stream() + .max((Employee e1, Employee e2) -> e1.getId() - e2.getId()) + .orElse(Employee.DEFAULT_EMPLOYEE); System.out.println(maxId); @@ -39,36 +43,42 @@ public int compare(Employee o1, Employee o2) { System.out.println("With Comparator of Super T i.e Object"); // For Object Class only toString option is present - Employee maxId1 = employees.stream() - //Since no comparator is implemented by Employee class, we can still find max by providing the implementation here - .max(new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return o1.toString().compareTo(o2.toString()); - } - }) - .orElse(Employee.DEFAULT_EMPLOYEE); + Employee maxId1 = + employees.stream() + // Since no comparator is implemented by Employee class, we can still find + // max by providing the implementation here + .max( + new Comparator() { + @Override + public int compare(Object o1, Object o2) { + return o1.toString().compareTo(o2.toString()); + } + }) + .orElse(Employee.DEFAULT_EMPLOYEE); System.out.println(maxId1); - Employee maxName = employees.stream() - .max((Object o1, Object o2) -> o2.toString().compareTo(o1.toString())) - .orElse(Employee.DEFAULT_EMPLOYEE); - + Employee maxName = + employees.stream() + .max((Object o1, Object o2) -> o2.toString().compareTo(o1.toString())) + .orElse(Employee.DEFAULT_EMPLOYEE); System.out.println(maxName + " : Name has characters : " + maxName.getName().length()); - System.out.println("***************************** Using Static Method reference *****************************"); + System.out.println( + "***************************** Using Static Method reference *****************************"); // Using Static Method reference - maxId = employees.stream() - //Have a look at ComparingInt method - .max(comparingInt(Employee::getId)) - .orElse(Employee.DEFAULT_EMPLOYEE); - - maxName = employees.stream() - .max(comparing(Object::toString)) - .orElse(Employee.DEFAULT_EMPLOYEE); + maxId = + employees.stream() + // Have a look at ComparingInt method + .max(comparingInt(Employee::getId)) + .orElse(Employee.DEFAULT_EMPLOYEE); + + maxName = + employees.stream() + .max(comparing(Object::toString)) + .orElse(Employee.DEFAULT_EMPLOYEE); System.out.println(maxId); System.out.println(maxName); } @@ -78,7 +88,6 @@ public static List createEmployees() { new Employee(1, "Haradanahalli Doddegowda Deve Gowda"), new Employee(2, "Avul Pakir Jainulabdeen Abdul Kalam"), new Employee(3, "Dr. Sarvepalli Radhakrishnan"), - new Employee(4, "Kocheril Raman Narayanan") - ); + new Employee(4, "Kocheril Raman Narayanan")); } } diff --git a/src/main/java/nitin/generic/oReilly/a4sorting/Golfer.java b/src/main/java/nitin/generic/oReilly/a4sorting/Golfer.java index a97fe7e2..8ec0df02 100644 --- a/src/main/java/nitin/generic/oReilly/a4sorting/Golfer.java +++ b/src/main/java/nitin/generic/oReilly/a4sorting/Golfer.java @@ -2,8 +2,6 @@ import lombok.*; -import java.util.Objects; - @EqualsAndHashCode @ToString @RequiredArgsConstructor @@ -15,9 +13,8 @@ public class Golfer implements Comparable { private String last; private int score; - @Override public int compareTo(Golfer golfer) { return score - golfer.score; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/generic/oReilly/a4sorting/S1SortingDemo.java b/src/main/java/nitin/generic/oReilly/a4sorting/S1SortingDemo.java index 355a7f60..440bd53a 100644 --- a/src/main/java/nitin/generic/oReilly/a4sorting/S1SortingDemo.java +++ b/src/main/java/nitin/generic/oReilly/a4sorting/S1SortingDemo.java @@ -1,15 +1,16 @@ package nitin.generic.oReilly.a4sorting; +import static java.util.Comparator.*; +import static java.util.stream.Collectors.toList; + import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; -import static java.util.Comparator.*; -import static java.util.stream.Collectors.toList; - public class S1SortingDemo { - private final List sampleStrings = Arrays.asList("this", "is", "a", "list", "of", "strings"); + private final List sampleStrings = + Arrays.asList("this", "is", "a", "list", "of", "strings"); // Default sort from Java 7- public List alphaSort() { @@ -19,26 +20,25 @@ public List alphaSort() { // Java 7- using Comparator with anonymous inner class public List lengthReverseSortWithComparator() { - Collections.sort(sampleStrings, new Comparator() { - @Override - public int compare(String s1, String s2) { - return s2.length() - s1.length();// Reverse Sorting, due to s2-s1 - } - }); + Collections.sort( + sampleStrings, + new Comparator() { + @Override + public int compare(String s1, String s2) { + return s2.length() - s1.length(); // Reverse Sorting, due to s2-s1 + } + }); return sampleStrings; } // Default sort from Java 8+ public List alphaSortUsingStreams() { - return sampleStrings.stream() - .sorted() - .collect(toList()); + return sampleStrings.stream().sorted().collect(toList()); } // Using a lambda as a Comparator with a lambda public List lengthSortWithLambda() { - Collections.sort(sampleStrings, - (s1, s2) -> s1.length() - s2.length()); + Collections.sort(sampleStrings, (s1, s2) -> s1.length() - s2.length()); return sampleStrings; } @@ -51,24 +51,20 @@ public List lengthSortUsingSorted() { // Length sort with comparingInt public List lengthSortUsingComparator() { - return sampleStrings.stream() - .sorted(comparing(String::length)) - .collect(toList()); + return sampleStrings.stream().sorted(comparing(String::length)).collect(toList()); } // Sort by length then alpha using sorted public List lengthSortThenAlphaSortUsingSorted() { return sampleStrings.stream() - .sorted(comparingInt(String::length) - .thenComparing(naturalOrder())) + .sorted(comparingInt(String::length).thenComparing(naturalOrder())) .collect(toList()); } // Sort by length then reverse alpha using sorted public List lengthSortThenReverseAlphaUsingSorted() { return sampleStrings.stream() - .sorted(comparing(String::length) - .thenComparing(reverseOrder())) + .sorted(comparing(String::length).thenComparing(reverseOrder())) .collect(toList()); } } diff --git a/src/main/java/nitin/generic/oReilly/a4sorting/SortGolfers.java b/src/main/java/nitin/generic/oReilly/a4sorting/SortGolfers.java index 71f6b378..c471cbfb 100644 --- a/src/main/java/nitin/generic/oReilly/a4sorting/SortGolfers.java +++ b/src/main/java/nitin/generic/oReilly/a4sorting/SortGolfers.java @@ -7,54 +7,53 @@ import java.util.stream.Collectors; public class SortGolfers { - private final List golfers = Arrays.asList( - new Golfer("Jack", "Nicklaus", 68), - new Golfer("Tiger", "Woods", 70), - new Golfer("Tom", "Watson", 70), - new Golfer("Ty", "Webb", 68), - new Golfer("Bubba", "Watson", 70) - ); + private final List golfers = + Arrays.asList( + new Golfer("Jack", "Nicklaus", 68), + new Golfer("Tiger", "Woods", 70), + new Golfer("Tom", "Watson", 70), + new Golfer("Ty", "Webb", 68), + new Golfer("Bubba", "Watson", 70)); public static void main(String[] args) { SortGolfers sg = new SortGolfers(); -// sg.defaultSort(); -// sg.sortByScoreThenLast(); -// sg.sortByScoreThenLastThenFirst(); + // sg.defaultSort(); + // sg.sortByScoreThenLast(); + // sg.sortByScoreThenLastThenFirst(); sg.partitionByScore(); } // default sort is by score public void defaultSort() { - golfers.stream() - .sorted() - .forEach(System.out::println); + golfers.stream().sorted().forEach(System.out::println); } // sort by score, then by last name public void sortByScoreThenLast() { golfers.stream() - .sorted(Comparator.comparingInt(Golfer::getScore) - .thenComparing(Golfer::getLast)) + .sorted(Comparator.comparingInt(Golfer::getScore).thenComparing(Golfer::getLast)) .forEach(System.out::println); } // sort by score, then by last, then by first public void sortByScoreThenLastThenFirst() { golfers.stream() - .sorted(Comparator.comparingInt(Golfer::getScore) - .thenComparing(Golfer::getLast) - .thenComparing(Golfer::getFirst)) + .sorted( + Comparator.comparingInt(Golfer::getScore) + .thenComparing(Golfer::getLast) + .thenComparing(Golfer::getFirst)) .forEach(System.out::println); } public void partitionByScore() { - Map> map = golfers.stream() - .collect(Collectors.partitioningBy( - golfer -> golfer.getScore() < 70)); - - map.forEach((k, v) -> { - System.out.println(k); - v.forEach(System.out::println); - }); + Map> map = + golfers.stream() + .collect(Collectors.partitioningBy(golfer -> golfer.getScore() < 70)); + + map.forEach( + (k, v) -> { + System.out.println(k); + v.forEach(System.out::println); + }); } } diff --git a/src/main/java/nitin/generic/oReilly/a4sorting/SortingMaps.java b/src/main/java/nitin/generic/oReilly/a4sorting/SortingMaps.java index e01bedf6..d2f14e18 100644 --- a/src/main/java/nitin/generic/oReilly/a4sorting/SortingMaps.java +++ b/src/main/java/nitin/generic/oReilly/a4sorting/SortingMaps.java @@ -1,12 +1,12 @@ package nitin.generic.oReilly.a4sorting; +import static java.util.Comparator.reverseOrder; +import static java.util.stream.Collectors.toMap; + import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import static java.util.Comparator.reverseOrder; -import static java.util.stream.Collectors.toMap; - public class SortingMaps, V extends Comparable> { private Map map = new HashMap<>(); @@ -21,28 +21,44 @@ public void setMap(Map map) { public Map getMapSortedByKey() { return map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, - (e1, e2) -> e1, LinkedHashMap::new)); + .collect( + toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (e1, e2) -> e1, + LinkedHashMap::new)); } public Map getMapSortedByKeyDesc() { return map.entrySet().stream() .sorted(Map.Entry.comparingByKey(reverseOrder())) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, - (e1, e2) -> e1, LinkedHashMap::new)); + .collect( + toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (e1, e2) -> e1, + LinkedHashMap::new)); } public Map getMapSortedByValue() { return map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, - (e1, e2) -> e1, LinkedHashMap::new)); + .collect( + toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (e1, e2) -> e1, + LinkedHashMap::new)); } public Map getMapSortedByValueDesc() { return map.entrySet().stream() .sorted(Map.Entry.comparingByValue(reverseOrder())) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, - (e1, e2) -> e1, LinkedHashMap::new)); + .collect( + toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (e1, e2) -> e1, + LinkedHashMap::new)); } } diff --git a/src/main/java/nitin/generic/oReilly/a4sorting/WordMap.java b/src/main/java/nitin/generic/oReilly/a4sorting/WordMap.java index afddbb94..2d917e32 100644 --- a/src/main/java/nitin/generic/oReilly/a4sorting/WordMap.java +++ b/src/main/java/nitin/generic/oReilly/a4sorting/WordMap.java @@ -1,5 +1,8 @@ package nitin.generic.oReilly.a4sorting; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -9,9 +12,6 @@ import java.util.HashMap; import java.util.Map; -import static java.util.stream.Collectors.counting; -import static java.util.stream.Collectors.groupingBy; - public class WordMap { private final Path resourceDir = Paths.get("src/main/resources"); private String fileName = "simple_file.txt"; @@ -19,12 +19,15 @@ public class WordMap { public Map createWordMap() { Map map = new HashMap<>(); try { - String text = new String(Files.readAllBytes( - resourceDir.resolve(fileName)), StandardCharsets.UTF_8); + String text = + new String( + Files.readAllBytes(resourceDir.resolve(fileName)), + StandardCharsets.UTF_8); String[] words = text.split("\\W+"); - map = Arrays.stream(words) - .map(String::toLowerCase) - .collect(groupingBy(w -> w, counting())); + map = + Arrays.stream(words) + .map(String::toLowerCase) + .collect(groupingBy(w -> w, counting())); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/nitin/generic/oReilly/a5map/MapEmployees.java b/src/main/java/nitin/generic/oReilly/a5map/MapEmployees.java index be9abcce..a3733396 100644 --- a/src/main/java/nitin/generic/oReilly/a5map/MapEmployees.java +++ b/src/main/java/nitin/generic/oReilly/a5map/MapEmployees.java @@ -1,37 +1,37 @@ package nitin.generic.oReilly.a5map; - -import nitin.generic.oReilly.a3Max.Employee; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.function.Function; - -import static java.util.Comparator.comparing; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; +import nitin.generic.oReilly.a3Max.Employee; public class MapEmployees { public static void main(String[] args) { List employees = createEmployees(); - List names = employees.stream() - .map(Employee::getName) - .collect(toList()); + List names = employees.stream().map(Employee::getName).collect(toList()); - List ids = employees.stream() - .map(Employee::getId) - .collect(toList()); + List ids = employees.stream().map(Employee::getId).collect(toList()); - int totalLength = employees.stream() - .map(Employee::getName) - .mapToInt(String::length)//mapToInt has additional methods that can only be applied to integers, like sum, average etc - .sum(); + int totalLength = + employees.stream() + .map(Employee::getName) + .mapToInt(String::length) // mapToInt has additional methods that can only + // be applied to integers, like sum, average etc + .sum(); // Add employees to a map using id as key - Map employeeMap = employees.stream() - .collect(toMap(Employee::getId, Function.identity()));// Function.identity() means e -> e + Map employeeMap = + employees.stream() + .collect( + toMap( + Employee::getId, + Function.identity())); // Function.identity() means e -> e employeeMap.forEach((id, emp) -> System.out.println(id + ": " + emp)); @@ -39,26 +39,29 @@ public static void main(String[] args) { System.out.println("Sorted by key:"); employeeMap.entrySet().stream() .sorted(Map.Entry.comparingByKey()) - .forEach(entry -> { - System.out.println(entry.getKey() + ": " + entry.getValue()); - }); + .forEach( + entry -> { + System.out.println(entry.getKey() + ": " + entry.getValue()); + }); // Reverse sort employees by id and print them System.out.println("Reverse sorted by key:"); employeeMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) - .forEach(entry -> { - System.out.println(entry.getKey() + ": " + entry.getValue()); - }); + .forEach( + entry -> { + System.out.println(entry.getKey() + ": " + entry.getValue()); + }); // Sort employees by name and print them System.out.println("Sorted by name:"); employeeMap.entrySet().stream() .sorted(Map.Entry.comparingByValue(comparing(Employee::getName))) // .sorted(Map.Entry.comparingByValue()) - .forEach(entry -> { - System.out.println(entry.getKey() + ": " + entry.getValue()); - }); + .forEach( + entry -> { + System.out.println(entry.getKey() + ": " + entry.getValue()); + }); } public static List createEmployees() { @@ -66,7 +69,6 @@ public static List createEmployees() { new Employee(1, "Haradanahalli Doddegowda Deve Gowda"), new Employee(2, "Avul Pakir Jainulabdeen Abdul Kalam"), new Employee(3, "Dr. Sarvepalli Radhakrishnan"), - new Employee(4, "Kocheril Raman Narayanan") - ); + new Employee(4, "Kocheril Raman Narayanan")); } } diff --git a/src/main/java/nitin/generic/oReilly/a6erasure/ProcessColors.java b/src/main/java/nitin/generic/oReilly/a6erasure/ProcessColors.java index 02063003..02dc5ae5 100644 --- a/src/main/java/nitin/generic/oReilly/a6erasure/ProcessColors.java +++ b/src/main/java/nitin/generic/oReilly/a6erasure/ProcessColors.java @@ -18,8 +18,6 @@ public Color applyFilter(UnaryOperator filter) { @SafeVarargs public final Color applyFilters(Function... filters) { - return Arrays.stream(filters) - .reduce(Function.identity(), Function::andThen) - .apply(color); + return Arrays.stream(filters).reduce(Function.identity(), Function::andThen).apply(color); } } diff --git a/src/main/java/nitin/generic/oReilly/a6erasure/WildcardExample.java b/src/main/java/nitin/generic/oReilly/a6erasure/WildcardExample.java index 95c21e3d..2b84f41b 100644 --- a/src/main/java/nitin/generic/oReilly/a6erasure/WildcardExample.java +++ b/src/main/java/nitin/generic/oReilly/a6erasure/WildcardExample.java @@ -21,7 +21,6 @@ public static void main(String[] args) { public static void processList(List list) { // Compiler error: Cannot add elements to a list with an extends wildcard - //list.add(new Integer(10)); // This line would cause a compile-time error + // list.add(new Integer(10)); // This line would cause a compile-time error } } - diff --git a/src/main/java/nitin/generic/oReilly/types/Pair.java b/src/main/java/nitin/generic/oReilly/types/Pair.java index d2411c61..0ccb444d 100644 --- a/src/main/java/nitin/generic/oReilly/types/Pair.java +++ b/src/main/java/nitin/generic/oReilly/types/Pair.java @@ -16,13 +16,10 @@ public Pair reverse() { return new Pair<>(second, first); } - public Pair transform( - Function xfirst, - Function xsecond) { + public Pair transform(Function xfirst, Function xsecond) { return new Pair(xfirst.apply(first), xsecond.apply(second)); } - public F getFirst() { return first; } @@ -57,9 +54,6 @@ public int hashCode() { @Override public String toString() { - return "Pair{" + - "first=" + first + - ", second=" + second + - '}'; + return "Pair{" + "first=" + first + ", second=" + second + '}'; } } diff --git a/src/main/java/nitin/io/F1FileIO.java b/src/main/java/nitin/io/F1FileIO.java index 65dcd7b6..3fce4b1e 100644 --- a/src/main/java/nitin/io/F1FileIO.java +++ b/src/main/java/nitin/io/F1FileIO.java @@ -4,15 +4,13 @@ import java.io.IOException; /** - * Created by nitin on 1/2/16. - * Checking if the File Exists. If not Create - *

- * File class is used to represent DIRECTORIES as well as FILES + * Created by nitin on 1/2/16. Checking if the File Exists. If not Create + * + *

File class is used to represent DIRECTORIES as well as FILES */ - public class F1FileIO { - //FILE CLASS ACCEPTS FILE NAME + // FILE CLASS ACCEPTS FILE NAME public static void main(String[] args) { // Searches the file in the Project root Directory File f = new File("nitin.txt"); @@ -24,18 +22,17 @@ public static void main(String[] args) { // This cunstructor accepts directoy from Project root and file name File f2 = new File("src/com/nitin/a19IO", "nitin.txt"); - //Checking is exists + // Checking is exists System.out.println(f.exists()); - //Creatiomng of a new File - IN THE ROOT PROJECT FOLDER!! + // Creatiomng of a new File - IN THE ROOT PROJECT FOLDER!! try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } - //Checking is exists + // Checking is exists System.out.println(f2.exists()); - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/F2FileReaderWriter.java b/src/main/java/nitin/io/F2FileReaderWriter.java index 4996274c..511342cb 100644 --- a/src/main/java/nitin/io/F2FileReaderWriter.java +++ b/src/main/java/nitin/io/F2FileReaderWriter.java @@ -5,9 +5,7 @@ import java.io.FileWriter; import java.io.IOException; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class F2FileReaderWriter { public static void main(String[] args) throws IOException { File f = new File("nitin.txt"); @@ -17,7 +15,7 @@ public static void main(String[] args) throws IOException { // Reading character by character // We have the Unicode value of the Character - while (i != -1) { //unicode of null is -1 + while (i != -1) { // unicode of null is -1 System.out.println((char) i); i = fr.read(); } @@ -26,11 +24,9 @@ public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter(f, true); fw.write(" Nitin\n"); - //Good practise to use flush + // Good practise to use flush fw.flush(); fr.close(); fw.close(); - - } } diff --git a/src/main/java/nitin/io/F3BufferedReaderWriter.java b/src/main/java/nitin/io/F3BufferedReaderWriter.java index 9ad65133..e26ea753 100644 --- a/src/main/java/nitin/io/F3BufferedReaderWriter.java +++ b/src/main/java/nitin/io/F3BufferedReaderWriter.java @@ -2,9 +2,7 @@ import java.io.*; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class F3BufferedReaderWriter { public static void main(String[] args) throws IOException { @@ -21,7 +19,6 @@ public static void main(String[] args) throws IOException { bw.newLine(); bw.flush(); - // Reading the File FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); diff --git a/src/main/java/nitin/io/F4PrintReaderWriter.java b/src/main/java/nitin/io/F4PrintReaderWriter.java index 28ff3056..cb86e153 100644 --- a/src/main/java/nitin/io/F4PrintReaderWriter.java +++ b/src/main/java/nitin/io/F4PrintReaderWriter.java @@ -5,9 +5,7 @@ import java.io.IOException; import java.io.PrintWriter; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class F4PrintReaderWriter { public static void main(String[] args) throws IOException { @@ -19,15 +17,14 @@ public static void main(String[] args) throws IOException { pw.append("TESTING"); pw.write("Sangram\n"); - pw.write(100);// This will put 'd' - pw.println(100);// this will put the int 100 + pw.write(100); // This will put 'd' + pw.println(100); // this will put the int 100 pw.println('c'); // DIFFERENDE between append, write and Print (Print can write primity type into the File) // TO DO: Find a way to iterate to the EOF using PrintFWriter - //while(pw.something == EOF) + // while(pw.something == EOF) pw.flush(); pw.close(); - } } diff --git a/src/main/java/nitin/io/F5ScannerFromConsole.java b/src/main/java/nitin/io/F5ScannerFromConsole.java index 4a65c297..c6042aeb 100644 --- a/src/main/java/nitin/io/F5ScannerFromConsole.java +++ b/src/main/java/nitin/io/F5ScannerFromConsole.java @@ -3,33 +3,30 @@ import java.io.FileNotFoundException; import java.util.Scanner; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class F5ScannerFromConsole { public static void main(String[] args) throws FileNotFoundException { /* READING THE DATA FROM CONSOLE */ Scanner fromConsole = new Scanner(System.in); - //Reading an integer + // Reading an integer System.out.print("Enter an Integer: "); int a = fromConsole.nextInt(); System.out.println(a); - //Reading a String + // Reading a String System.out.print("Enter a String: "); String b = fromConsole.next(); System.out.println(b); // Read a character System.out.print("Enter an Character: "); - char c = fromConsole.next().charAt(0);//This is how Character is read + char c = fromConsole.next().charAt(0); // This is how Character is read System.out.println(c); // Read a character System.out.print("Enter an Double: "); - double d = fromConsole.nextDouble();//This is how Character is read + double d = fromConsole.nextDouble(); // This is how Character is read System.out.println(d); - } } diff --git a/src/main/java/nitin/io/F6ScannerFromFile.java b/src/main/java/nitin/io/F6ScannerFromFile.java index df8a3092..cecacda3 100644 --- a/src/main/java/nitin/io/F6ScannerFromFile.java +++ b/src/main/java/nitin/io/F6ScannerFromFile.java @@ -4,9 +4,7 @@ import java.io.FileNotFoundException; import java.util.Scanner; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class F6ScannerFromFile { public static void main(String[] args) throws FileNotFoundException { /* READING THE DATA FROM THE FILE */ @@ -14,14 +12,14 @@ public static void main(String[] args) throws FileNotFoundException { Scanner toFile = new Scanner(f); while (toFile.hasNext()) { - //Every line is treated as String + // Every line is treated as String System.out.println(toFile.next()); } - //TO DO: DIFFERENCE Between next() and nextLine() - //nextLine -> READS THE ENTIRE LINE (Including the \n)(of the keyboard/file input) - //next() -> Reads the characters upto (but not including) space - //Resetting the pointer to the Start of the File + // TO DO: DIFFERENCE Between next() and nextLine() + // nextLine -> READS THE ENTIRE LINE (Including the \n)(of the keyboard/file input) + // next() -> Reads the characters upto (but not including) space + // Resetting the pointer to the Start of the File toFile = new Scanner(f); while (toFile.hasNext()) { System.out.println(toFile.nextLine()); diff --git a/src/main/java/nitin/io/F7ScannerInputProblem.java b/src/main/java/nitin/io/F7ScannerInputProblem.java index 14dd684f..44f8283f 100644 --- a/src/main/java/nitin/io/F7ScannerInputProblem.java +++ b/src/main/java/nitin/io/F7ScannerInputProblem.java @@ -2,9 +2,7 @@ import java.util.Scanner; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class F7ScannerInputProblem { public static void main(String[] args) { @@ -12,35 +10,34 @@ public static void main(String[] args) { Scanner fromConsole = new Scanner(System.in); - //Reading a String + // Reading a String System.out.print("Enter a String: "); - //next will not pick up space separated values, thus nextLine is used + // next will not pick up space separated values, thus nextLine is used String b = fromConsole.nextLine(); - //INPUT PROBLEM 1: To eat up the next string token (ONLY TO CONSUME EXTRA STRING TOKEN FROM NEXT!!) - //fromConsole.next();// Replace by nextLine to solve the Problem + // INPUT PROBLEM 1: To eat up the next string token (ONLY TO CONSUME EXTRA STRING TOKEN FROM + // NEXT!!) + // fromConsole.next();// Replace by nextLine to solve the Problem System.out.println(b); - - //Reading an integer + // Reading an integer System.out.print("Enter an Integer: "); int a = fromConsole.nextInt(); System.out.println(a); // Read a double. nextInd and nextDouble ignored the ENTER THAT IS PRESSED after inputting System.out.print("Enter an Double: "); - double d = fromConsole.nextDouble();//This is how Character is read + double d = fromConsole.nextDouble(); // This is how Character is read System.out.println(d); + // INPUT PROBLEM 2: This statement is consuming the EXTRA ENTER (\n) that is given after + // imputing the double vlaue + fromConsole.nextLine(); // HAVE TO USE TO CONSUNE ANY LEADING/TRAILING \n - // INPUT PROBLEM 2: This statement is consuming the EXTRA ENTER (\n) that is given after imputing the double vlaue - fromConsole.nextLine();// HAVE TO USE TO CONSUNE ANY LEADING/TRAILING \n - - //Reading a String + // Reading a String System.out.print("Enter another String: "); String b1 = fromConsole.nextLine(); System.out.println(b1); } - } diff --git a/src/main/java/nitin/io/ReadFileFromURL.java b/src/main/java/nitin/io/ReadFileFromURL.java index 9771bddd..0f59e3c8 100644 --- a/src/main/java/nitin/io/ReadFileFromURL.java +++ b/src/main/java/nitin/io/ReadFileFromURL.java @@ -9,7 +9,7 @@ public static void main(String[] args) { Scanner s = null; List list = new ArrayList<>(); try { - //The Project Gutenberg EBook of Pride and Prejudice, by Jane Austen + // The Project Gutenberg EBook of Pride and Prejudice, by Jane Austen URL url = new URL("https://www.gutenberg.org/files/1342/1342-0.txt"); s = new Scanner(url.openStream()); } catch (IOException ex) { @@ -23,7 +23,7 @@ public static void main(String[] args) { } for (Map.Entry entry : map.entrySet()) { - //System.out.println("Key = " + entry.getKey() + " Value = " + entry.getValue()); + // System.out.println("Key = " + entry.getKey() + " Value = " + entry.getValue()); if (entry.getValue() > 4) { list.add(entry.getKey()); } diff --git a/src/main/java/nitin/io/ReadLine.java b/src/main/java/nitin/io/ReadLine.java index ef5e5aac..f04d5ca0 100644 --- a/src/main/java/nitin/io/ReadLine.java +++ b/src/main/java/nitin/io/ReadLine.java @@ -17,5 +17,4 @@ public static void main(String[] args) throws IOException { String sample = br.readLine(); System.out.println(sample); } - } diff --git a/src/main/java/nitin/io/fileIO/fileIOEx1/FileIoExamples.java b/src/main/java/nitin/io/fileIO/fileIOEx1/FileIoExamples.java index 84b17dbe..f8a652d1 100755 --- a/src/main/java/nitin/io/fileIO/fileIOEx1/FileIoExamples.java +++ b/src/main/java/nitin/io/fileIO/fileIOEx1/FileIoExamples.java @@ -1,7 +1,6 @@ package nitin.io.fileIO.fileIOEx1; import com.config.Configs; - import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; @@ -13,15 +12,13 @@ import java.util.stream.Collectors; /** - * Solutions to first set of File I/O exercises from Java 8 tutorial at coreservlets.com. - * These solutions use the overly simplistic approach where main throws Exception, because we - * have not yet seen how to fix this without repeating code from problem to problem. - * We will use a better approach in the second set of exercises. + * Solutions to first set of File I/O exercises from Java 8 tutorial at coreservlets.com. These + * solutions use the overly simplistic approach where main throws Exception, because we have not yet + * seen how to fix this without repeating code from problem to problem. We will use a better + * approach in the second set of exercises. */ - public class FileIoExamples { - private FileIoExamples() { - } // Uninstantiatable class + private FileIoExamples() {} // Uninstantiatable class public static void main(String[] args) throws Exception { String inputFile = Configs.ENABLE1_WORD_LIST_PATH; @@ -67,18 +64,22 @@ public static void abcWordMixedCase(String inputFile) throws Exception { .filter(word -> word.contains("c")) .findFirst() .orElse("No 8-letter word containing a, b, and c"); - System.out.printf("First 8-letter word containing a, b, and c in any case is '%s'.%n", result); + System.out.printf( + "First 8-letter word containing a, b, and c in any case is '%s'.%n", result); } - public static void longestWordWithout(String inputFile, String letter1, String letter2) throws Exception { - String errorMessage = String.format("There is no word that lacks both %s and %s", letter1, letter2); + public static void longestWordWithout(String inputFile, String letter1, String letter2) + throws Exception { + String errorMessage = + String.format("There is no word that lacks both %s and %s", letter1, letter2); String result = Files.lines(Paths.get(inputFile)) .filter(word -> !word.contains(letter1)) .filter(word -> !word.contains(letter2)) .max(Comparator.comparing(String::length)) .orElse(errorMessage); - System.out.printf("The longest word that lacks both %s and %s is '%s'.%n", letter1, letter2, result); + System.out.printf( + "The longest word that lacks both %s and %s is '%s'.%n", letter1, letter2, result); } public static void shortestWordWith(String inputFile, String letter) throws Exception { @@ -101,7 +102,8 @@ public static void storeTwitterList(String inputFile, String outputFile) throws .collect(Collectors.toList()); Path outputPath = Paths.get(outputFile); Files.write(outputPath, twitterWords, Charset.defaultCharset()); - System.out.printf("Wrote %s words to %s.%n", twitterWords.size(), outputPath.toAbsolutePath()); + System.out.printf( + "Wrote %s words to %s.%n", twitterWords.size(), outputPath.toAbsolutePath()); } public static void numPathsInProject() throws Exception { @@ -112,12 +114,12 @@ public static void numPathsInProject() throws Exception { public static void storeNums(int n, int range, String outputFile) { Charset characterSet = Charset.defaultCharset(); Path path = Paths.get(outputFile); - try (PrintWriter writer = - new PrintWriter(Files.newBufferedWriter(path, characterSet))) { + try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(path, characterSet))) { for (int i = 0; i < n; i++) { writer.printf("%.2f%n", 10 * Math.random()); } - System.out.printf("Wrote %s numbers between 0 and %s to %s.%n", n, range, path.toAbsolutePath()); + System.out.printf( + "Wrote %s numbers between 0 and %s to %s.%n", n, range, path.toAbsolutePath()); } catch (IOException ioe) { System.err.println("IOException: " + ioe); } diff --git a/src/main/java/nitin/io/fileIO/fileIOEx2/FileIOExamples.java b/src/main/java/nitin/io/fileIO/fileIOEx2/FileIOExamples.java index ac7f53dc..5eaa57b6 100755 --- a/src/main/java/nitin/io/fileIO/fileIOEx2/FileIOExamples.java +++ b/src/main/java/nitin/io/fileIO/fileIOEx2/FileIOExamples.java @@ -1,19 +1,14 @@ package nitin.io.fileIO.fileIOEx2; import com.config.Configs; - import java.util.Arrays; import java.util.List; -/** - * Solutions to second set of file I/O exercises from Java 8 tutorial at coreservlets.com. - */ - +/** Solutions to second set of file I/O exercises from Java 8 tutorial at coreservlets.com. */ public class FileIOExamples { public static void main(String[] args) { String filename = Configs.ENABLE1_WORD_LIST_PATH; - List testWords = - Arrays.asList("foo", "bar", "baz12345678", "boo1234567"); + List testWords = Arrays.asList("foo", "bar", "baz12345678", "boo1234567"); WordUtils.print10LetterWord(testWords.stream()); WordUtils.print10LetterWord(filename); @@ -40,15 +35,23 @@ public static void main(String[] args) { Arrays.asList("quit", "squid", "book", "bookkeeper", "keep", "steep"); long qsInList = WordUtils.numWordsContaining(testWords2.stream(), "q"); long jsInList = WordUtils.numWordsContaining(testWords2.stream(), "j"); - System.out.printf("In list, there are %,d words containing 'q' and %,d words containing 'j'.%n", qsInList, jsInList); + System.out.printf( + "In list, there are %,d words containing 'q' and %,d words containing 'j'.%n", + qsInList, jsInList); long qsInFile = WordUtils.numWordsContaining(filename, "q"); long jsInFile = WordUtils.numWordsContaining(filename, "j"); - System.out.printf("In file, there are %,d words containing 'q' and %,d words containing 'j'.%n", qsInFile, jsInFile); + System.out.printf( + "In file, there are %,d words containing 'q' and %,d words containing 'j'.%n", + qsInFile, jsInFile); long doubleOsInList = WordUtils.numWordsContaining(testWords2.stream(), "oo"); long doubleEsInList = WordUtils.numWordsContaining(testWords2.stream(), "ee"); - System.out.printf("In list, there are %,d words containing 'oo' and %,d words containing 'ee'.%n", doubleOsInList, doubleEsInList); + System.out.printf( + "In list, there are %,d words containing 'oo' and %,d words containing 'ee'.%n", + doubleOsInList, doubleEsInList); long doubleOsInFile = WordUtils.numWordsContaining(filename, "oo"); long doubleEsInFile = WordUtils.numWordsContaining(filename, "ee"); - System.out.printf("In file, there are %,d words containing 'oo' and %,d words containing 'ee'.%n", doubleOsInFile, doubleEsInFile); + System.out.printf( + "In file, there are %,d words containing 'oo' and %,d words containing 'ee'.%n", + doubleOsInFile, doubleEsInFile); } } diff --git a/src/main/java/nitin/io/fileIO/fileIOEx2/WordUtils.java b/src/main/java/nitin/io/fileIO/fileIOEx2/WordUtils.java index d99602a5..86413ab5 100755 --- a/src/main/java/nitin/io/fileIO/fileIOEx2/WordUtils.java +++ b/src/main/java/nitin/io/fileIO/fileIOEx2/WordUtils.java @@ -2,12 +2,9 @@ import java.util.stream.Stream; -/** - * Some Stream-based static methods for finding words in files. - */ +/** Some Stream-based static methods for finding words in files. */ public class WordUtils { - private WordUtils() { - } // Uninstantiatable class + private WordUtils() {} // Uninstantiatable class public static void print10LetterWord(Stream words) { String result = @@ -24,9 +21,7 @@ public static void print10LetterWord(String filename) { public static void printNLetterWord(Stream words, int wordLength) { String errorMessage = String.format("No %s-letter word found", wordLength); String result = - words.filter(word -> word.length() == wordLength) - .findFirst() - .orElse(errorMessage); + words.filter(word -> word.length() == wordLength).findFirst().orElse(errorMessage); System.out.printf("First %s-letter word is '%s'.%n", wordLength, result); } @@ -35,9 +30,7 @@ public static void printNLetterWord(String filename, int wordLength) { } public static String nLetterWord(Stream words, int wordLength) { - return (words.filter(word -> word.length() == wordLength) - .findFirst() - .orElse(null)); + return (words.filter(word -> word.length() == wordLength).findFirst().orElse(null)); } public static String nLetterWord(String filename, int wordLength) { @@ -45,11 +38,11 @@ public static String nLetterWord(String filename, int wordLength) { } public static long numWordsContaining(Stream words, String subString) { - return (words.filter(word -> word.contains(subString)) - .count()); + return (words.filter(word -> word.contains(subString)).count()); } public static long numWordsContaining(String filename, String subString) { - return (StreamAnalyzer.analyzeFile(filename, lines -> numWordsContaining(lines, subString))); + return (StreamAnalyzer.analyzeFile( + filename, lines -> numWordsContaining(lines, subString))); } } diff --git a/src/main/java/nitin/io/fileIO/folders/FolderExamples.java b/src/main/java/nitin/io/fileIO/folders/FolderExamples.java index 67505a4a..49e83bd0 100755 --- a/src/main/java/nitin/io/fileIO/folders/FolderExamples.java +++ b/src/main/java/nitin/io/fileIO/folders/FolderExamples.java @@ -1,12 +1,10 @@ package nitin.io.fileIO.folders; -/** - * Some examples of exploring folders and searching for files. - */ +/** Some examples of exploring folders and searching for files. */ public class FolderExamples { public static void main(String[] args) { - //listExamples(); - //walkExamples(); + // listExamples(); + // walkExamples(); findExamples(); } @@ -14,27 +12,22 @@ public static void listExamples() { System.out.println("All files in project root"); FolderUtils.printAllPathsInFolder("."); System.out.println("Text files in project root"); - FolderUtils.printPathsInFolder(".", - p -> p.toString().endsWith(".txt")); + FolderUtils.printPathsInFolder(".", p -> p.toString().endsWith(".txt")); } public static void walkExamples() { System.out.println("All files under project root"); FolderUtils.printAllPathsInTree("."); System.out.println("Java files under project root"); - FolderUtils.printPathsInTree(".", - p -> p.toString().endsWith(".java")); + FolderUtils.printPathsInTree(".", p -> p.toString().endsWith(".java")); } public static void findExamples() { System.out.println("Java files under project root"); - FolderUtils.findPathsInTree(".", - (path, attrs) -> path.toString().endsWith(".java")); + FolderUtils.findPathsInTree(".", (path, attrs) -> path.toString().endsWith(".java")); System.out.println("Folders under project root"); - FolderUtils.findPathsInTree(".", - (path, attrs) -> attrs.isDirectory()); + FolderUtils.findPathsInTree(".", (path, attrs) -> attrs.isDirectory()); System.out.println("Large files under project root"); - FolderUtils.findPathsInTree(".", - (path, attrs) -> attrs.size() > 10000); + FolderUtils.findPathsInTree(".", (path, attrs) -> attrs.size() > 10000); } } diff --git a/src/main/java/nitin/io/fileIO/folders/FolderUtils.java b/src/main/java/nitin/io/fileIO/folders/FolderUtils.java index fb4729b0..32820352 100755 --- a/src/main/java/nitin/io/fileIO/folders/FolderUtils.java +++ b/src/main/java/nitin/io/fileIO/folders/FolderUtils.java @@ -9,13 +9,9 @@ import java.util.function.Predicate; import java.util.stream.Stream; -/** - * Some Stream-based static methods for using with folders and paths. - */ - +/** Some Stream-based static methods for using with folders and paths. */ public class FolderUtils { - private FolderUtils() { - } // Uninstantiatable class + private FolderUtils() {} // Uninstantiatable class public static void printAllPaths(Stream paths) { paths.forEach(System.out::println); @@ -30,8 +26,7 @@ public static void printAllPathsInFolder(String folder) { } public static void printPaths(Stream paths, Predicate test) { - paths.filter(test) - .forEach(System.out::println); + paths.filter(test).forEach(System.out::println); } public static void printPathsInFolder(String folder, Predicate test) { @@ -58,7 +53,8 @@ public static void printPathsInTree(String rootFolder, Predicate test) { } } - public static void findPathsInTree(String rootFolder, BiPredicate test) { + public static void findPathsInTree( + String rootFolder, BiPredicate test) { try (Stream paths = Files.find(Paths.get(rootFolder), 10, test)) { printAllPaths(paths); } catch (IOException ioe) { diff --git a/src/main/java/nitin/io/fileIO/java7/FileUtils.java b/src/main/java/nitin/io/fileIO/java7/FileUtils.java index 7fb17e1b..dcc4661a 100755 --- a/src/main/java/nitin/io/fileIO/java7/FileUtils.java +++ b/src/main/java/nitin/io/fileIO/java7/FileUtils.java @@ -8,8 +8,7 @@ import java.util.List; public class FileUtils { - private FileUtils() { - } // Uninstantiatable class + private FileUtils() {} // Uninstantiatable class public static List getLines(String file) throws IOException { Path path = Paths.get(file); diff --git a/src/main/java/nitin/io/fileIO/java7/ReadFile1.java b/src/main/java/nitin/io/fileIO/java7/ReadFile1.java index 54c08eac..463c298e 100755 --- a/src/main/java/nitin/io/fileIO/java7/ReadFile1.java +++ b/src/main/java/nitin/io/fileIO/java7/ReadFile1.java @@ -7,18 +7,17 @@ import java.util.List; /** - * Reads from file into a List in one fell swoop. Uses - * the Java-7 approach with Files.readAllLines, which is much less efficient - * than the Java 8 approach with Files.lines. + * Reads from file into a List in one fell swoop. Uses the Java-7 approach with Files.readAllLines, + * which is much less efficient than the Java 8 approach with Files.lines. */ - public class ReadFile1 { public static void main(String[] args) throws Exception { - String file = "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/input-file.txt"; + String file = + "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/input-file.txt"; Charset characterSet = Charset.defaultCharset(); - //The Paths.get method is shorthand for the following code: - //Path path = FileSystems.getDefault().getPath(file); + // The Paths.get method is shorthand for the following code: + // Path path = FileSystems.getDefault().getPath(file); Path path = Paths.get(file); List lines = Files.readAllLines(path, characterSet); System.out.printf("Lines from %s: %s%n", file, lines); diff --git a/src/main/java/nitin/io/fileIO/java7/ReadFile1A.java b/src/main/java/nitin/io/fileIO/java7/ReadFile1A.java index 52ac33be..ca9e3d72 100755 --- a/src/main/java/nitin/io/fileIO/java7/ReadFile1A.java +++ b/src/main/java/nitin/io/fileIO/java7/ReadFile1A.java @@ -2,13 +2,11 @@ import java.util.List; -/** - * Similar to ReadFile1, but uses a method from FileUtils to simplify the code. - */ - +/** Similar to ReadFile1, but uses a method from FileUtils to simplify the code. */ public class ReadFile1A { public static void main(String[] args) throws Exception { - String file = "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/input-file.txt"; + String file = + "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/input-file.txt"; List lines = FileUtils.getLines(file); System.out.printf("Lines from %s: %s%n", file, lines); } diff --git a/src/main/java/nitin/io/fileIO/java7/ReadFile2.java b/src/main/java/nitin/io/fileIO/java7/ReadFile2.java index 49eebef5..37d06183 100755 --- a/src/main/java/nitin/io/fileIO/java7/ReadFile2.java +++ b/src/main/java/nitin/io/fileIO/java7/ReadFile2.java @@ -7,18 +7,14 @@ import java.nio.file.Path; import java.nio.file.Paths; -/** - * Reads one line at a time, rather than using Files.readAllLines - * as in ReadFile1. - */ - +/** Reads one line at a time, rather than using Files.readAllLines as in ReadFile1. */ public class ReadFile2 { public static void main(String[] args) { - String file = "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/input-file.txt"; + String file = + "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/input-file.txt"; Charset characterSet = Charset.defaultCharset(); Path path = Paths.get(file); - try (BufferedReader reader = - Files.newBufferedReader(path, characterSet)) { + try (BufferedReader reader = Files.newBufferedReader(path, characterSet)) { System.out.printf("Lines from %s:%n", file); String line; while ((line = reader.readLine()) != null) { diff --git a/src/main/java/nitin/io/fileIO/java7/WriteFile1A.java b/src/main/java/nitin/io/fileIO/java7/WriteFile1A.java index 9f061cdf..ec5fb9d9 100755 --- a/src/main/java/nitin/io/fileIO/java7/WriteFile1A.java +++ b/src/main/java/nitin/io/fileIO/java7/WriteFile1A.java @@ -6,10 +6,10 @@ public class WriteFile1A { public static void main(String[] args) throws IOException { - String file = "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/OutputFile1.txt"; + String file = + "Java8/src/main/java/com/nitin/zCoreServletsTraining/t4FileIO/fileIO/OutputFile1.txt"; - List lines = - Arrays.asList("Line One", "Line Two", "Final Line"); + List lines = Arrays.asList("Line One", "Line Two", "Final Line"); FileUtils.writeLines(file, lines); } } diff --git a/src/main/java/nitin/io/fileIO/paths/PathExamples.java b/src/main/java/nitin/io/fileIO/paths/PathExamples.java index b6c6cd4c..31b3b67e 100755 --- a/src/main/java/nitin/io/fileIO/paths/PathExamples.java +++ b/src/main/java/nitin/io/fileIO/paths/PathExamples.java @@ -1,14 +1,10 @@ package nitin.io.fileIO.paths; import com.config.Configs; - import java.nio.file.Path; import java.nio.file.Paths; -/** - * Some examples of simple Path methods - */ - +/** Some examples of simple Path methods */ public class PathExamples { public static void main(String[] args) { diff --git a/src/main/java/nitin/io/fileIO/readfiles1/AllPalindromes.java b/src/main/java/nitin/io/fileIO/readfiles1/AllPalindromes.java index 9d479beb..4975d036 100755 --- a/src/main/java/nitin/io/fileIO/readfiles1/AllPalindromes.java +++ b/src/main/java/nitin/io/fileIO/readfiles1/AllPalindromes.java @@ -1,18 +1,15 @@ package nitin.io.fileIO.readfiles1; - import com.config.Configs; -import nitin.io.fileIO.strings.StringUtils; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import nitin.io.fileIO.strings.StringUtils; /** - * Prints all palindromes. Uses the first, simplest, and least flexible - * file-reading variation, where code is placed directly in "main". + * Prints all palindromes. Uses the first, simplest, and least flexible file-reading variation, + * where code is placed directly in "main". */ - public class AllPalindromes { public static void main(String[] args) { String inputFile = Configs.ENABLE1_WORD_LIST_PATH; diff --git a/src/main/java/nitin/io/fileIO/readfiles1/First6LetterPalindrome.java b/src/main/java/nitin/io/fileIO/readfiles1/First6LetterPalindrome.java index 35bf48f0..d900163b 100755 --- a/src/main/java/nitin/io/fileIO/readfiles1/First6LetterPalindrome.java +++ b/src/main/java/nitin/io/fileIO/readfiles1/First6LetterPalindrome.java @@ -1,11 +1,9 @@ package nitin.io.fileIO.readfiles1; - import com.config.Configs; -import nitin.io.fileIO.strings.StringUtils; - import java.nio.file.Files; import java.nio.file.Paths; +import nitin.io.fileIO.strings.StringUtils; public class First6LetterPalindrome { public static void main(String[] args) throws Exception { diff --git a/src/main/java/nitin/io/fileIO/readfiles1/FourLetterWords.java b/src/main/java/nitin/io/fileIO/readfiles1/FourLetterWords.java index 9e5005fd..b69cb980 100755 --- a/src/main/java/nitin/io/fileIO/readfiles1/FourLetterWords.java +++ b/src/main/java/nitin/io/fileIO/readfiles1/FourLetterWords.java @@ -1,7 +1,6 @@ package nitin.io.fileIO.readfiles1; import com.config.Configs; - import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; @@ -9,23 +8,21 @@ import java.util.stream.Collectors; /** - * The enable1 word list is a public-domain file containing over - * 175,000 supposed words accepted by many US Scrabble clubs. - * The name comes from Enhanced North American Benchmark LExicon (ENABLE). - * It is almost twice as large as the Official Scrabble Player's Dictionary, - * and contains slang, offensive words, and many obscure or questionable words. - * It contains no one-letter words and no super-long words, and is not endorsed - * in any way by Hasbro (maker of Scrabble) or Merriam Webster (publisher of - * The Official Scrabble Player's Dictionary). - * Details at http://www.puzzlers.org/dokuwiki/doku.php?id=solving:wordlists:about:enable_readme - *

- * Two repeated words in mixed case (Extra and EXTRA) were added to the end of the file - * to verify that the code can handle repeats, mixed case, and out-of-order entries. - *

- * The project also contains additional word lists for you to experiment with. + * The enable1 word list is a public-domain file containing over 175,000 supposed words accepted by + * many US Scrabble clubs. The name comes from Enhanced North American Benchmark LExicon (ENABLE). + * It is almost twice as large as the Official Scrabble Player's Dictionary, and contains slang, + * offensive words, and many obscure or questionable words. It contains no one-letter words and no + * super-long words, and is not endorsed in any way by Hasbro (maker of Scrabble) or Merriam Webster + * (publisher of The Official Scrabble Player's Dictionary). Details at + * http://www.puzzlers.org/dokuwiki/doku.php?id=solving:wordlists:about:enable_readme + * + *

Two repeated words in mixed case (Extra and EXTRA) were added to the end of the file to verify + * that the code can handle repeats, mixed case, and out-of-order entries. + * + *

The project also contains additional word lists for you to experiment with. + * *

*/ - public class FourLetterWords { public static void main(String[] args) throws Exception { String inputFile = Configs.ENABLE1_WORD_LIST_PATH; diff --git a/src/main/java/nitin/io/fileIO/readfiles1/QsWithoutUs.java b/src/main/java/nitin/io/fileIO/readfiles1/QsWithoutUs.java index 4493de4a..7abf1618 100755 --- a/src/main/java/nitin/io/fileIO/readfiles1/QsWithoutUs.java +++ b/src/main/java/nitin/io/fileIO/readfiles1/QsWithoutUs.java @@ -1,7 +1,6 @@ package nitin.io.fileIO.readfiles1; import com.config.Configs; - import java.nio.file.Files; import java.nio.file.Paths; diff --git a/src/main/java/nitin/io/fileIO/readfiles1/XsAndYs.java b/src/main/java/nitin/io/fileIO/readfiles1/XsAndYs.java index fbe0008f..76f5ecd9 100755 --- a/src/main/java/nitin/io/fileIO/readfiles1/XsAndYs.java +++ b/src/main/java/nitin/io/fileIO/readfiles1/XsAndYs.java @@ -1,7 +1,6 @@ package nitin.io.fileIO.readfiles1; import com.config.Configs; - import java.nio.file.Files; import java.nio.file.Paths; @@ -14,7 +13,6 @@ public static void main(String[] args) throws Exception { .filter(word -> word.contains("y")) .mapToInt(String::length) .sum(); - System.out.printf("%,d total letters in words with " + - "both x and y.%n", letterCount); + System.out.printf("%,d total letters in words with " + "both x and y.%n", letterCount); } } diff --git a/src/main/java/nitin/io/fileIO/readfiles2/FileReadingExamples.java b/src/main/java/nitin/io/fileIO/readfiles2/FileReadingExamples.java index 49f015cc..2a700a56 100755 --- a/src/main/java/nitin/io/fileIO/readfiles2/FileReadingExamples.java +++ b/src/main/java/nitin/io/fileIO/readfiles2/FileReadingExamples.java @@ -1,7 +1,6 @@ package nitin.io.fileIO.readfiles2; import com.config.Configs; - import java.util.Arrays; import java.util.List; diff --git a/src/main/java/nitin/io/fileIO/readfiles2/FileUtils.java b/src/main/java/nitin/io/fileIO/readfiles2/FileUtils.java index 0019a406..c3e5c1b7 100755 --- a/src/main/java/nitin/io/fileIO/readfiles2/FileUtils.java +++ b/src/main/java/nitin/io/fileIO/readfiles2/FileUtils.java @@ -1,35 +1,24 @@ package nitin.io.fileIO.readfiles2; - -import nitin.io.fileIO.strings.StringUtils; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; +import nitin.io.fileIO.strings.StringUtils; /** - * Prints all palindromes and all n-length palindromes. Uses the second - * file-reading variation, where the code is split into a file-processing method - * and a stream-processing method, but code in the file-processing method is - * repeated from example to example. + * Prints all palindromes and all n-length palindromes. Uses the second file-reading variation, + * where the code is split into a file-processing method and a stream-processing method, but code in + * the file-processing method is repeated from example to example. */ - public class FileUtils { - /** - * Prints all palindromes in the Stream. - */ - + /** Prints all palindromes in the Stream. */ public static void printAllPalindromes(Stream words) { - words.filter(StringUtils::isPalindrome) - .forEach(System.out::println); + words.filter(StringUtils::isPalindrome).forEach(System.out::println); } - /** - * Prints all palindromes in the file. - */ - + /** Prints all palindromes in the file. */ public static void printAllPalindromes(String filename) { try (Stream words = Files.lines(Paths.get(filename))) { printAllPalindromes(words); @@ -38,20 +27,14 @@ public static void printAllPalindromes(String filename) { } } - /** - * Prints the n-length palindromes in the Stream. - */ - + /** Prints the n-length palindromes in the Stream. */ public static void printPalindromes(Stream words, int length) { words.filter(word -> word.length() == length) .filter(StringUtils::isPalindrome) .forEach(System.out::println); } - /** - * Prints the n-length palindromes in the file. - */ - + /** Prints the n-length palindromes in the file. */ public static void printPalindromes(String filename, int length) { try (Stream words = Files.lines(Paths.get(filename))) { printPalindromes(words, length); diff --git a/src/main/java/nitin/io/fileIO/readfiles3/FileReadingExamples.java b/src/main/java/nitin/io/fileIO/readfiles3/FileReadingExamples.java index 73678a19..adec154e 100755 --- a/src/main/java/nitin/io/fileIO/readfiles3/FileReadingExamples.java +++ b/src/main/java/nitin/io/fileIO/readfiles3/FileReadingExamples.java @@ -1,50 +1,43 @@ package nitin.io.fileIO.readfiles3; - import com.config.Configs; -import nitin.io.fileIO.strings.StringUtils; - import java.util.Arrays; import java.util.List; +import nitin.io.fileIO.strings.StringUtils; public class FileReadingExamples { - private FileReadingExamples() { - } // Uninstantiatable class: static methods only + private FileReadingExamples() {} // Uninstantiatable class: static methods only /** - * The enable1 word list is a public-domain file containing over - * 175,000 supposed words accepted by many US Scrabble clubs. - * The name comes from Enhanced North American Benchmark LExicon (ENABLE). - * It is almost twice as large as the Official Scrabble Player's Dictionary, - * and contains slang, offensive words, and many obscure or questionable words. - * It contains no one-letter words and no super-long words, and is not endorsed - * in any way by Hasbro (maker of Scrabble) or Merriam Webster (publisher of - * The Official Scrabble Player's Dictionary). + * The enable1 word list is a public-domain file containing over 175,000 supposed words accepted + * by many US Scrabble clubs. The name comes from Enhanced North American Benchmark LExicon + * (ENABLE). It is almost twice as large as the Official Scrabble Player's Dictionary, and + * contains slang, offensive words, and many obscure or questionable words. It contains no + * one-letter words and no super-long words, and is not endorsed in any way by Hasbro (maker of + * Scrabble) or Merriam Webster (publisher of The Official Scrabble Player's Dictionary). * Details at http://www.puzzlers.org/dokuwiki/doku.php?id=solving:wordlists:about:enable_readme - *

- * Two repeated words in mixed case (Extra and EXTRA) were added to the end of the file - * to verify that the code can handle repeats, mixed case, and out-of-order entries. - *

- * The project also contains additional word lists for you to experiment with. + * + *

Two repeated words in mixed case (Extra and EXTRA) were added to the end of the file to + * verify that the code can handle repeats, mixed case, and out-of-order entries. + * + *

The project also contains additional word lists for you to experiment with. */ - public static void main(String[] args) { String filename = Configs.ENABLE1_WORD_LIST_PATH; if (args.length > 0) { filename = args[0]; } - //testAllPalindromes(filename); - //testPalindromes(filename, 3, 4, 7); - //testFirstPalindrome(filename); - //testLetterCount(filename); - //testFirstMatch(filename); + // testAllPalindromes(filename); + // testPalindromes(filename, 3, 4, 7); + // testFirstPalindrome(filename); + // testLetterCount(filename); + // testFirstMatch(filename); testAllMatches(filename); } public static void testAllPalindromes(String filename) { - List testWords = - Arrays.asList("bog", "bob", "dam", "dad"); + List testWords = Arrays.asList("bog", "bob", "dam", "dad"); System.out.printf("All palindromes in list %s:%n", testWords); FileUtils.printAllPalindromes(testWords.stream()); System.out.printf("All palindromes in file %s:%n", filename); @@ -52,8 +45,7 @@ public static void testAllPalindromes(String filename) { } public static void testPalindromes(String filename, int... lengths) { - List testWords = - Arrays.asList("rob", "bob", "reed", "deed"); + List testWords = Arrays.asList("rob", "bob", "reed", "deed"); for (int length : lengths) { System.out.printf("%s-letter palindromes in list %s:%n", length, testWords); FileUtils.printPalindromes(testWords.stream(), length); @@ -63,10 +55,8 @@ public static void testPalindromes(String filename, int... lengths) { } public static void testFirstPalindrome(String filename) { - List testWords = - Arrays.asList("bog", "bob", "dam", "dad"); - String firstPalindrome = - FileUtils.firstPalindrome(testWords.stream()); + List testWords = Arrays.asList("bog", "bob", "dam", "dad"); + String firstPalindrome = FileUtils.firstPalindrome(testWords.stream()); System.out.printf("First palindrome in list %s is %s.%n", testWords, firstPalindrome); firstPalindrome = FileUtils.firstPalindrome(filename); System.out.printf("First palindrome in file %s is %s.%n", filename, firstPalindrome); @@ -75,20 +65,20 @@ public static void testFirstPalindrome(String filename) { public static void testLetterCount(String filename) { List testWords = Arrays.asList("hi", "hello", "hola"); System.out.printf("In list %s:%n", testWords); - int sum1 = FileUtils.letterCount(testWords.stream(), - word -> word.contains("h"), - word -> !word.contains("i")); + int sum1 = + FileUtils.letterCount( + testWords.stream(), + word -> word.contains("h"), + word -> !word.contains("i")); printLetterCountResult(sum1, "contain h but not i"); System.out.printf("In file %s:%n", filename); - int sum2 = FileUtils.letterCount(filename, - StringUtils::isPalindrome); + int sum2 = FileUtils.letterCount(filename, StringUtils::isPalindrome); printLetterCountResult(sum2, "are palindromes"); - int sum3 = FileUtils.letterCount(filename, - word -> word.contains("q"), - word -> !word.contains("qu")); + int sum3 = + FileUtils.letterCount( + filename, word -> word.contains("q"), word -> !word.contains("qu")); printLetterCountResult(sum3, "contain q not followed by u"); - int sum4 = FileUtils.letterCount(filename, - word -> true); + int sum4 = FileUtils.letterCount(filename, word -> true); printLetterCountResult(sum4, "are in English language"); } @@ -98,27 +88,28 @@ private static void printLetterCountResult(int sum, String message) { public static void testFirstMatch(String filename) { List testNums = Arrays.asList(1, 10, 2, 20, 3, 30); - Integer match1 = FileUtils.firstMatch(testNums.stream(), - n -> n > 2, - n -> n < 10, - n -> n % 2 == 1); - System.out.printf("First word in list %s that is greater than 2, less than 10, and odd is %s.%n", testNums, match1); - String match2 = FileUtils.firstMatch(filename, - word -> word.contains("q"), - word -> !word.contains("qu")); - System.out.printf("First word in file %s with q not followed by u is %s.%n", filename, match2); + Integer match1 = + FileUtils.firstMatch(testNums.stream(), n -> n > 2, n -> n < 10, n -> n % 2 == 1); + System.out.printf( + "First word in list %s that is greater than 2, less than 10, and odd is %s.%n", + testNums, match1); + String match2 = + FileUtils.firstMatch( + filename, word -> word.contains("q"), word -> !word.contains("qu")); + System.out.printf( + "First word in file %s with q not followed by u is %s.%n", filename, match2); } public static void testAllMatches(String filename) { List testNums = Arrays.asList(2, 4, 6, 8, 10, 12); - List matches1 = - FileUtils.allMatches(testNums.stream(), - n -> n > 5, - n -> n < 10); - System.out.printf("All numbers in list %s that are greater than 5 and less than 10: %s.%n", testNums, matches1); - List matches2 = FileUtils.allMatches(filename, - word -> word.contains("q"), - word -> !word.contains("qu")); - System.out.printf("All words in file %s with q not followed by u: %s.%n", filename, matches2); + List matches1 = FileUtils.allMatches(testNums.stream(), n -> n > 5, n -> n < 10); + System.out.printf( + "All numbers in list %s that are greater than 5 and less than 10: %s.%n", + testNums, matches1); + List matches2 = + FileUtils.allMatches( + filename, word -> word.contains("q"), word -> !word.contains("qu")); + System.out.printf( + "All words in file %s with q not followed by u: %s.%n", filename, matches2); } } diff --git a/src/main/java/nitin/io/fileIO/readfiles3/FileUtils.java b/src/main/java/nitin/io/fileIO/readfiles3/FileUtils.java index 2dfb5562..f318393d 100755 --- a/src/main/java/nitin/io/fileIO/readfiles3/FileUtils.java +++ b/src/main/java/nitin/io/fileIO/readfiles3/FileUtils.java @@ -1,92 +1,64 @@ package nitin.io.fileIO.readfiles3; - -import nitin.io.fileIO.strings.StringUtils; - import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; +import nitin.io.fileIO.strings.StringUtils; /** - * Finds various information about the word list. Uses the third and fourth - * file-reading variations, where the code is split into a file-processing method - * and a stream-processing method, and code in the file-processing method is - * NOT repeated from example to example. + * Finds various information about the word list. Uses the third and fourth file-reading variations, + * where the code is split into a file-processing method and a stream-processing method, and code in + * the file-processing method is NOT repeated from example to example. */ - public class FileUtils { - private FileUtils() { - } // Uninstantiatable class: static methods only - - /** - * Prints all palindromes in the Stream. - */ + private FileUtils() {} // Uninstantiatable class: static methods only + /** Prints all palindromes in the Stream. */ public static void printAllPalindromes(Stream words) { - words.filter(StringUtils::isPalindrome) - .forEach(System.out::println); + words.filter(StringUtils::isPalindrome).forEach(System.out::println); } - /** - * Prints all palindromes in the file. - */ - + /** Prints all palindromes in the file. */ public static void printAllPalindromes(String filename) { StreamProcessor.processFile(filename, FileUtils::printAllPalindromes); } - /** - * Prints the n-length palindromes in the Stream. - */ - + /** Prints the n-length palindromes in the Stream. */ public static void printPalindromes(Stream words, int length) { words.filter(word -> word.length() == length) .filter(StringUtils::isPalindrome) .forEach(System.out::println); } - /** - * Prints the n-length palindromes in the file. - */ - + /** Prints the n-length palindromes in the file. */ public static void printPalindromes(String filename, int length) { StreamProcessor.processFile(filename, lines -> printPalindromes(lines, length)); } - /** - * Returns the first palindrome in the Stream. - * Returns null if there is no match. - */ - + /** Returns the first palindrome in the Stream. Returns null if there is no match. */ public static String firstPalindrome(Stream words) { - return (words.filter(StringUtils::isPalindrome) - .findFirst() - .orElse(null)); + return (words.filter(StringUtils::isPalindrome).findFirst().orElse(null)); } - // @SafeVarargs is difficult to understand. The issue is that it is not always safe to use varargs for generic types: + // @SafeVarargs is difficult to understand. The issue is that it is not always safe to use + // varargs for generic types: // the resultant array can have runtime type problems if you modify entries in it. // But, if you only read the values and never modify them, varargs is perfectly safe. // @SafeVarargs says "I am not doing anything dangerous, please suppress the compiler warnings". - // For details, see http://docs.oracle.com/javase/8/docs/technotes/guides/language/non-reifiable-varargs.html - - /** - * Returns the first palindrome in the file. - * Returns null if there is no match. - */ + // For details, see + // http://docs.oracle.com/javase/8/docs/technotes/guides/language/non-reifiable-varargs.html + /** Returns the first palindrome in the file. Returns null if there is no match. */ public static String firstPalindrome(String filename) { return (StreamAnalyzer.analyzeFile(filename, FileUtils::firstPalindrome)); } /** - * Returns a Predicate that is the result of ANDing all the argument Predicates. - * If no Predicates are supplied, it returns a Predicate that always returns - * true. + * Returns a Predicate that is the result of ANDing all the argument Predicates. If no + * Predicates are supplied, it returns a Predicate that always returns true. */ - @SafeVarargs public static Predicate combinedPredicate(Predicate... tests) { Predicate result = e -> true; @@ -97,16 +69,13 @@ public static Predicate combinedPredicate(Predicate... tests) { } /** - * Returns first element in Stream that passes all of the tests. - * Returns null if there is no match. + * Returns first element in Stream that passes all of the tests. Returns null if there is no + * match. */ - @SafeVarargs public static T firstMatch(Stream elements, Predicate... tests) { Predicate combinedTest = FileUtils.combinedPredicate(tests); - return (elements.filter(combinedTest) - .findFirst() - .orElse(null)); + return (elements.filter(combinedTest).findFirst().orElse(null)); } /* Returns a List of all elements in Stream that pass all of the tests. @@ -114,10 +83,8 @@ public static T firstMatch(Stream elements, Predicate... tests) { */ /** - * Returns first line in file that passes all of the tests. - * Returns null if there is no match. + * Returns first line in file that passes all of the tests. Returns null if there is no match. */ - @SafeVarargs public static String firstMatch(String filename, Predicate... tests) { return (StreamAnalyzer.analyzeFile(filename, stream -> firstMatch(stream, tests))); @@ -130,8 +97,7 @@ public static String firstMatch(String filename, Predicate... tests) { @SafeVarargs public static List allMatches(Stream elements, Predicate... tests) { Predicate combinedTest = FileUtils.combinedPredicate(tests); - return (elements.filter(combinedTest) - .collect(Collectors.toList())); + return (elements.filter(combinedTest).collect(Collectors.toList())); } @SafeVarargs @@ -140,20 +106,18 @@ public static List allMatches(String filename, Predicate... test } /** - * Returns sum of the lengths of all words in the Stream that pass the tests. - * Returns 0 in no words pass all the tests. + * Returns sum of the lengths of all words in the Stream that pass the tests. Returns 0 in no + * words pass all the tests. */ @SafeVarargs public static int letterCount(Stream words, Predicate... tests) { Predicate combinedTest = FileUtils.combinedPredicate(tests); - return (words.filter(combinedTest) - .mapToInt(String::length) - .sum()); + return (words.filter(combinedTest).mapToInt(String::length).sum()); } /** - * Returns sum of the lengths of all lines in the file that pass the tests. - * Returns 0 in no lines pass all the tests. + * Returns sum of the lengths of all lines in the file that pass the tests. Returns 0 in no + * lines pass all the tests. */ @SafeVarargs public static Integer letterCount(String filename, Predicate... tests) { diff --git a/src/main/java/nitin/io/fileIO/strings/StringUtils.java b/src/main/java/nitin/io/fileIO/strings/StringUtils.java index 43d37213..c27496ca 100755 --- a/src/main/java/nitin/io/fileIO/strings/StringUtils.java +++ b/src/main/java/nitin/io/fileIO/strings/StringUtils.java @@ -2,20 +2,15 @@ public class StringUtils { - private StringUtils() { - } // Uninstantiatable class: static methods only - - /** - * Returns a reversed copy of a non-null String. - */ + private StringUtils() {} // Uninstantiatable class: static methods only + /** Returns a reversed copy of a non-null String. */ public static String reverseString(String s) { return (new StringBuilder(s).reverse().toString()); } /** - * Checks if a String is a palindrome. Accepts - * zero-length or one-length strings, but not null. + * Checks if a String is a palindrome. Accepts zero-length or one-length strings, but not null. */ public static boolean isPalindrome(String s) { return (s.equalsIgnoreCase(reverseString(s))); diff --git a/src/main/java/nitin/io/fileIO/strings/StringUtilsTester.java b/src/main/java/nitin/io/fileIO/strings/StringUtilsTester.java index a3aed99f..deab1ae5 100755 --- a/src/main/java/nitin/io/fileIO/strings/StringUtilsTester.java +++ b/src/main/java/nitin/io/fileIO/strings/StringUtilsTester.java @@ -1,16 +1,14 @@ package nitin.io.fileIO.strings; -import org.junit.Test; - import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +import org.junit.Test; + /** - * Some unit tests using the newer assertThat style. - * See StringUtilsTester for a variation that uses the - * more traditional assertEquals, assertTrue, and - * assertFalse methods. + * Some unit tests using the newer assertThat style. See StringUtilsTester for a variation that uses + * the more traditional assertEquals, assertTrue, and assertFalse methods. */ // Note that under some Eclipse settings, Eclipse will make @@ -28,10 +26,10 @@ public void testReverse() { @Test public void testPalindromes() { - String[] matches = - {"a", "aba", "Aba", "abba", "AbBa", "abcdeffedcba", "abcdEffedcba"}; - String[] misMatches = - {"ax", "axba", "Axba", "abbax", "xAbBa", "abcdeffedcdax", "axbcdEffedcda"}; + String[] matches = {"a", "aba", "Aba", "abba", "AbBa", "abcdeffedcba", "abcdEffedcba"}; + String[] misMatches = { + "ax", "axba", "Axba", "abbax", "xAbBa", "abcdeffedcdax", "axbcdEffedcda" + }; for (String s : matches) { assertThat(StringUtils.isPalindrome(s), is(true)); } diff --git a/src/main/java/nitin/io/fileIO/writefiles/WriteFile1.java b/src/main/java/nitin/io/fileIO/writefiles/WriteFile1.java index ec4b214c..23676b6a 100755 --- a/src/main/java/nitin/io/fileIO/writefiles/WriteFile1.java +++ b/src/main/java/nitin/io/fileIO/writefiles/WriteFile1.java @@ -9,15 +9,15 @@ import java.util.List; /** - * Writes to a file from a List in one fell swoop. Works in either - * Java 7 or Java 8, unlike the file reading examples that used - * Files.lines, which work only in Java 8. + * Writes to a file from a List in one fell swoop. Works in either Java 7 or Java 8, unlike the file + * reading examples that used Files.lines, which work only in Java 8. */ - public class WriteFile1 { public static void main(String[] args) throws IOException { Charset characterSet = Charset.defaultCharset(); - Path path = Paths.get("src/main/java/nitin/zCoreServletsTraining/t4FileIO/fileIO/file-write-test.txt"); + Path path = + Paths.get( + "src/main/java/nitin/zCoreServletsTraining/t4FileIO/fileIO/file-write-test.txt"); List lines = Arrays.asList("Line One", "Line Two", "Final Line"); Files.write(path, lines, characterSet); } diff --git a/src/main/java/nitin/io/fileIO/writefiles/WriteFile2.java b/src/main/java/nitin/io/fileIO/writefiles/WriteFile2.java index 02429af4..da52823f 100755 --- a/src/main/java/nitin/io/fileIO/writefiles/WriteFile2.java +++ b/src/main/java/nitin/io/fileIO/writefiles/WriteFile2.java @@ -9,21 +9,20 @@ /** * Writes to file without having to make List first. Uses BufferedWriter directly. - *

- * From the - * coreservlets.com tutorials on JSF 2, PrimeFaces, Ajax, JavaScript, jQuery, GWT, Android, - * Spring, Hibernate, JPA, RESTful Web Services, Hadoop, Spring MVC, - * servlets, JSP, Java 8 lambdas and streams (for those that know Java already), - * and Java 8 programming (for those new to Java). + * + *

From the coreservlets.com + * tutorials on JSF 2, PrimeFaces, Ajax, JavaScript, jQuery, GWT, Android, Spring, Hibernate, JPA, + * RESTful Web Services, Hadoop, Spring MVC, servlets, JSP, Java 8 lambdas and streams (for those + * that know Java already), and Java 8 programming (for those new to Java). */ - public class WriteFile2 { public static void main(String[] args) { Charset characterSet = Charset.defaultCharset(); int numLines = 10; - Path path = Paths.get("src/main/java/nitin/zCoreServletsTraining/t4FileIO/fileIO/output-file-2.txt"); - try (BufferedWriter writer = - Files.newBufferedWriter(path, characterSet)) { + Path path = + Paths.get( + "src/main/java/nitin/zCoreServletsTraining/t4FileIO/fileIO/output-file-2.txt"); + try (BufferedWriter writer = Files.newBufferedWriter(path, characterSet)) { for (int i = 0; i < numLines; i++) { writer.write("Number is " + 100 * Math.random()); writer.newLine(); diff --git a/src/main/java/nitin/io/fileIO/writefiles/WriteFile3.java b/src/main/java/nitin/io/fileIO/writefiles/WriteFile3.java index 99d90443..a61bfc55 100755 --- a/src/main/java/nitin/io/fileIO/writefiles/WriteFile3.java +++ b/src/main/java/nitin/io/fileIO/writefiles/WriteFile3.java @@ -7,18 +7,15 @@ import java.nio.file.Path; import java.nio.file.Paths; -/** - * Writes to file without having to make List first. Wraps - * the BufferedWriter in a PrintWriter. - */ - +/** Writes to file without having to make List first. Wraps the BufferedWriter in a PrintWriter. */ public class WriteFile3 { public static void main(String[] args) { Charset characterSet = Charset.defaultCharset(); int numLines = 10; - Path path = Paths.get("src/main/java/nitin/zCoreServletsTraining/t4FileIO/fileIO/output-file-3.txt"); - try (PrintWriter out = - new PrintWriter(Files.newBufferedWriter(path, characterSet))) { + Path path = + Paths.get( + "src/main/java/nitin/zCoreServletsTraining/t4FileIO/fileIO/output-file-3.txt"); + try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(path, characterSet))) { for (int i = 0; i < numLines; i++) { out.printf("Number is %5.2f%n", 100 * Math.random()); } diff --git a/src/main/java/nitin/io/fileOperations/FileReadWrite.java b/src/main/java/nitin/io/fileOperations/FileReadWrite.java index eb1fcf3f..f96bcc98 100644 --- a/src/main/java/nitin/io/fileOperations/FileReadWrite.java +++ b/src/main/java/nitin/io/fileOperations/FileReadWrite.java @@ -5,10 +5,8 @@ import java.nio.file.Path; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 7:34 PM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 7:34 PM */ - public class FileReadWrite { public static void main(String[] args) throws IOException { Path path = Files.writeString(Files.createTempFile("test", ".txt"), "Temporary text data"); @@ -16,6 +14,5 @@ public static void main(String[] args) throws IOException { String s = Files.readString(path); System.out.println(s); - } } diff --git a/src/main/java/nitin/io/fileOperations/N1PathFileTest.java b/src/main/java/nitin/io/fileOperations/N1PathFileTest.java index de94ae0f..943210fb 100644 --- a/src/main/java/nitin/io/fileOperations/N1PathFileTest.java +++ b/src/main/java/nitin/io/fileOperations/N1PathFileTest.java @@ -3,9 +3,7 @@ import java.nio.file.Path; import java.nio.file.Paths; -/** - * Created by Nitin C on 3/4/2016. - */ +/** Created by Nitin C on 3/4/2016. */ public class N1PathFileTest { public static void main(String[] args) { printPathInformation(Paths.get("/src/nitin.txt")); diff --git a/src/main/java/nitin/io/fileOperations/N2App.java b/src/main/java/nitin/io/fileOperations/N2App.java index d454612f..b468d353 100644 --- a/src/main/java/nitin/io/fileOperations/N2App.java +++ b/src/main/java/nitin/io/fileOperations/N2App.java @@ -29,17 +29,18 @@ public static void main(String[] args) { } } - private static List compareAndPrepareWriteLines(List configFileStr, List inputStr) { + private static List compareAndPrepareWriteLines( + List configFileStr, List inputStr) { List writeLine = new ArrayList<>(); for (String str : inputStr) { StringBuilder sb = new StringBuilder(); sb.append(str); if (configFileStr.contains(str)) { sb.append(" ").append("Verified"); - writeLine.add(sb.toString());//.replaceAll("\\s", "")); + writeLine.add(sb.toString()); // .replaceAll("\\s", "")); } else { sb.append(" ").append("NotVerified"); - writeLine.add(sb.toString());//.replaceAll("\\s", "")); + writeLine.add(sb.toString()); // .replaceAll("\\s", "")); } } return writeLine; @@ -72,10 +73,7 @@ private static List getStringsFromEachFileInFolder(List filesInFol private static List getInputStrings(Path input) { List inputStr = new ArrayList<>(); try { - inputStr = Files - .readAllLines(input) - .stream() - .collect(Collectors.toList()); + inputStr = Files.readAllLines(input).stream().collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } @@ -85,40 +83,47 @@ private static List getInputStrings(Path input) { private static List getAllFilesFromFolder(Path path) { List filesInFolder = new ArrayList<>(); try { - filesInFolder = Files.walk(path) - .filter(Files::isRegularFile) - .map(Path::toFile) - .filter(filename -> filename.getName().endsWith("yaml")) - //.peek(file -> System.out.println(file)) - .collect(Collectors.toList()); + filesInFolder = + Files.walk(path) + .filter(Files::isRegularFile) + .map(Path::toFile) + .filter(filename -> filename.getName().endsWith("yaml")) + // .peek(file -> System.out.println(file)) + .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } return filesInFolder; } - private static void extracted(List filesInFolder, List inputStr, List writeLine) { + private static void extracted( + List filesInFolder, List inputStr, List writeLine) { for (File f : filesInFolder) { StringBuilder sb = new StringBuilder(); sb.append(f.getName(), 0, f.getName().length() - 5).append(" "); try { Files.lines(f.toPath()) - .filter(line -> line.contains("tag")) // this line filters any line out which does not meet the condition - .forEach(line -> { - //System.out.println(line); - sb.append(line.substring(11)); - });//print each line + .filter( + line -> + line.contains( + "tag")) // this line filters any line out which does + // not meet the condition + .forEach( + line -> { + // System.out.println(line); + sb.append(line.substring(11)); + }); // print each line } catch (IOException e) { e.printStackTrace(); } if (inputStr.contains(sb.toString())) { sb.append(" ").append("Verified"); - writeLine.add(sb.toString());//.replaceAll("\\s", "")); + writeLine.add(sb.toString()); // .replaceAll("\\s", "")); } else { sb.append(" ").append("NotVerified"); - writeLine.add(sb.toString());//.replaceAll("\\s", "")); + writeLine.add(sb.toString()); // .replaceAll("\\s", "")); } } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/ReadTransactionsCsv.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/ReadTransactionsCsv.java index 9005ed7c..c976f3dc 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/ReadTransactionsCsv.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/ReadTransactionsCsv.java @@ -1,25 +1,23 @@ package nitin.io.fileOperations.csvDataReadOperations.bills; -import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Currency; -import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transaction; -import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transactions; -import org.apache.commons.lang3.math.NumberUtils; - import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; +import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Currency; +import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transaction; +import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transactions; +import org.apache.commons.lang3.math.NumberUtils; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 11:23 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 11:23 PM */ - public class ReadTransactionsCsv { public static List getData() { - String file = "JavaLatest/src/main/java/com/fileOperations/csvDataReadOperations/bills/transactions.csv"; + String file = + "JavaLatest/src/main/java/com/fileOperations/csvDataReadOperations/bills/transactions.csv"; return readFileNreturnList(file); } @@ -32,11 +30,13 @@ private static List readFileNreturnList(String file) { e.printStackTrace(); } - List entityList = reader.lines().skip(1) - //.limit(200) - .map(line -> line.split(",")) - .map(ReadTransactionsCsv::makeObjects) - .collect(Collectors.toList()); + List entityList = + reader.lines() + .skip(1) + // .limit(200) + .map(line -> line.split(",")) + .map(ReadTransactionsCsv::makeObjects) + .collect(Collectors.toList()); try { reader.close(); @@ -46,19 +46,18 @@ private static List readFileNreturnList(String file) { return entityList; } - private static Transaction makeObjects(String[] line) { Transaction e = null; - //int id, double value, Currency currency, Transactions type, String city - e = new Transaction( - NumberUtils.toInt(line[0]), - NumberUtils.toDouble(line[1]), - Currency.valueOf(line[2]), - Transactions.valueOf(line[3]), - line[4] - ); - - //System.out.println(e); + // int id, double value, Currency currency, Transactions type, String city + e = + new Transaction( + NumberUtils.toInt(line[0]), + NumberUtils.toDouble(line[1]), + Currency.valueOf(line[2]), + Transactions.valueOf(line[3]), + line[4]); + + // System.out.println(e); return e; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Currency.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Currency.java index 94bbbf32..7584d4d0 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Currency.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Currency.java @@ -1,10 +1,10 @@ package nitin.io.fileOperations.csvDataReadOperations.bills.entity; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 10:12 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 10:12 PM */ - public enum Currency { - USD, GBP, INR + USD, + GBP, + INR } diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transaction.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transaction.java index 905e71d7..eddeb28e 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transaction.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transaction.java @@ -5,10 +5,8 @@ import lombok.ToString; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 6:46 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 6:46 PM */ - @Getter @Setter @ToString @@ -27,4 +25,3 @@ public Transaction(int id, double value, Currency currency, Transactions type, S this.city = city; } } - diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transactions.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transactions.java index 3c629331..d77faecd 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transactions.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/entity/Transactions.java @@ -1,11 +1,11 @@ package nitin.io.fileOperations.csvDataReadOperations.bills.entity; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 10:13 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 10:13 PM */ - public enum Transactions { - GROCERY, INSURANCE, FUEL, RENT + GROCERY, + INSURANCE, + FUEL, + RENT } - diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionGroup.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionGroup.java index 2f53f087..8c4b732e 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionGroup.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionGroup.java @@ -1,60 +1,71 @@ package nitin.io.fileOperations.csvDataReadOperations.bills.runner; -import nitin.io.fileOperations.csvDataReadOperations.bills.ReadTransactionsCsv; -import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transaction; - import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; +import nitin.io.fileOperations.csvDataReadOperations.bills.ReadTransactionsCsv; +import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transaction; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 10:26 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 10:26 PM */ -//https://www.oracle.com/technical-resources/articles/java/architect-streams-pt2.html +// https://www.oracle.com/technical-resources/articles/java/architect-streams-pt2.html public class TransactionGroup { - private static final Comparator> valueOrder = Map.Entry.comparingByValue(); - private static final Comparator> reversedValueOrder = valueOrder.reversed(); + private static final Comparator> valueOrder = + Map.Entry.comparingByValue(); + private static final Comparator> reversedValueOrder = + valueOrder.reversed(); public static void main(String[] args) { List transactions = ReadTransactionsCsv.getData(); System.out.println("**************************************************************"); System.out.println("Get sum of all the Tx's in each city using maptoDouble"); - //Map mapCitySum = + // Map mapCitySum = transactions.stream() - .collect(Collectors.groupingBy(Transaction::getCity, - Collectors.summingDouble(Transaction::getValue))) - .entrySet().forEach(System.out::println); + .collect( + Collectors.groupingBy( + Transaction::getCity, + Collectors.summingDouble(Transaction::getValue))) + .entrySet() + .forEach(System.out::println); System.out.println("**************************************************************"); System.out.println("Get sum of all the Tx's in each currency"); - //Map mapCitySum = + // Map mapCitySum = transactions.stream() - .collect(Collectors.groupingBy(Transaction::getCurrency, - Collectors.summingDouble(Transaction::getValue))) - .entrySet().forEach(System.out::println); + .collect( + Collectors.groupingBy( + Transaction::getCurrency, + Collectors.summingDouble(Transaction::getValue))) + .entrySet() + .forEach(System.out::println); System.out.println("**************************************************************"); System.out.println("Get sum of all the Tx's of each type"); - //Map mapCitySum = + // Map mapCitySum = transactions.stream() - .collect(Collectors.groupingBy(Transaction::getType, - Collectors.summingDouble(Transaction::getValue))) - .entrySet().forEach(System.out::println); + .collect( + Collectors.groupingBy( + Transaction::getType, + Collectors.summingDouble(Transaction::getValue))) + .entrySet() + .forEach(System.out::println); System.out.println("**************************************************************"); System.out.println("Get max amount by each City"); getMaxAmountByCity(transactions); - transactions.stream() - .collect(Collectors.groupingBy(Transaction::getCity, - Collectors.maxBy(Comparator.comparingDouble(Transaction::getValue)))) + .collect( + Collectors.groupingBy( + Transaction::getCity, + Collectors.maxBy( + Comparator.comparingDouble(Transaction::getValue)))) .values() .stream() .filter(Optional::isPresent) @@ -68,9 +79,12 @@ private static void getMaxAmountByCity(List transactions) { transactions.stream() // .collect(Collectors.groupingBy(Transaction::getCity, // Collectors.maxBy(Comparator.comparing(Transaction::getValue)))) - .collect(Collectors.groupingBy(Transaction::getCity, - Collectors.collectingAndThen - (Collectors.maxBy(Comparator.comparing(Transaction::getValue)), + .collect( + Collectors.groupingBy( + Transaction::getCity, + Collectors.collectingAndThen( + Collectors.maxBy( + Comparator.comparing(Transaction::getValue)), optional -> optional.get().getValue()))) .entrySet() .stream() diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionService.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionService.java index 435efb6e..99356db7 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionService.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/bills/runner/TransactionService.java @@ -1,16 +1,14 @@ package nitin.io.fileOperations.csvDataReadOperations.bills.runner; -import nitin.io.fileOperations.csvDataReadOperations.bills.ReadTransactionsCsv; -import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transaction; -import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transactions; - import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; +import nitin.io.fileOperations.csvDataReadOperations.bills.ReadTransactionsCsv; +import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transaction; +import nitin.io.fileOperations.csvDataReadOperations.bills.entity.Transactions; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 7:43 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 7:43 PM */ // https://www.oracle.com/technical-resources/articles/java/architect-streams-pt2.html @@ -21,27 +19,22 @@ public static void main(String[] args) { System.out.println("**************************************************************"); System.out.println("Get id's all Groceries types"); - List transactionsIds = - getTransIdGroceries(transactions); + List transactionsIds = getTransIdGroceries(transactions); System.out.println(transactionsIds); System.out.println("**************************************************************"); System.out.println("Get id's all Groceries types"); - boolean expensive = - transactions.stream() - .allMatch(t -> t.getValue() > 100); + boolean expensive = transactions.stream().allMatch(t -> t.getValue() > 100); System.out.println("**************************************************************"); System.out.println("Get sum of all the Tx's in Delhi using maptoDouble"); - Double statementSum = - getSumCity(transactions); + Double statementSum = getSumCity(transactions); System.out.println(statementSum); System.out.println("**************************************************************"); System.out.println("Get sum of all the Tx's in Delhi using maptoDouble"); - Double statementSumReduce = - getSumCityReduce(transactions); + Double statementSumReduce = getSumCityReduce(transactions); System.out.println(statementSumReduce); } diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPost.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPost.java index 306d0b19..4c64d7f3 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPost.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPost.java @@ -5,10 +5,8 @@ import lombok.ToString; /** - * @author Created by nichaurasia - * Created on Thursday, October/01/2020 at 1:20 AM + * @author Created by nichaurasia Created on Thursday, October/01/2020 at 1:20 AM */ - @Getter @Setter @ToString @@ -24,4 +22,4 @@ public BlogPost(String title, String author, BlogPostType type, int likes) { this.type = type; this.likes = likes; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPostType.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPostType.java index 7bbbde45..559490ac 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPostType.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/BlogPostType.java @@ -1,10 +1,10 @@ package nitin.io.fileOperations.csvDataReadOperations.blogs; /** - * @author Created by nichaurasia - * Created on Thursday, October/01/2020 at 1:20 AM + * @author Created by nichaurasia Created on Thursday, October/01/2020 at 1:20 AM */ - public enum BlogPostType { - NEWS, REVIEW, GUIDE + NEWS, + REVIEW, + GUIDE } diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Runner.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Runner.java index 931ae6c9..43ae29c4 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Runner.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Runner.java @@ -5,8 +5,7 @@ import java.util.stream.Collectors; /** - * @author Created by nichaurasia - * Created on Thursday, October/01/2020 at 1:24 AM + * @author Created by nichaurasia Created on Thursday, October/01/2020 at 1:24 AM */ // https://github.com/eugenp/tutorials/blob/master/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java @@ -14,12 +13,13 @@ public class Runner { public static void main(String[] args) { - final List posts = Arrays.asList( - new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), - new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), - new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), - new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), - new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + final List posts = + Arrays.asList( + new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), + new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), + new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), + new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); System.out.println("********************************************************************"); System.out.println("getPostsByType"); @@ -29,7 +29,6 @@ public static void main(String[] args) { System.out.println("getPostTitleByType"); getPostTitleByType(posts); - /*posts.stream() .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))) @@ -47,22 +46,20 @@ public static void main(String[] args) { private static void getPostTitleByType(List posts) { posts.stream() // BlogPostType : BlogPost - .collect(Collectors - .groupingBy(BlogPost::getAuthor, - Collectors.mapping(BlogPost::getTitle, - //Create a stream consisting the Title,Like tuple - Collectors.joining("|| ", "Post titles: [", "]") - ) - ) - ).entrySet() + .collect( + Collectors.groupingBy( + BlogPost::getAuthor, + Collectors.mapping( + BlogPost::getTitle, + // Create a stream consisting the Title,Like tuple + Collectors.joining("|| ", "Post titles: [", "]")))) + .entrySet() .stream() .forEach(System.out::println); } private static void getPostsByType(List posts) { - posts.stream() - .collect(Collectors.groupingBy(BlogPost::getType)) - .entrySet().stream().forEach(System.out::println); + posts.stream().collect(Collectors.groupingBy(BlogPost::getType)).entrySet().stream() + .forEach(System.out::println); } - } diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Tuple.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Tuple.java index b635682c..09897510 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Tuple.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/blogs/Tuple.java @@ -5,10 +5,8 @@ import lombok.ToString; /** - * @author Created by nichaurasia - * Created on Thursday, October/01/2020 at 1:22 AM + * @author Created by nichaurasia Created on Thursday, October/01/2020 at 1:22 AM */ - @Getter @ToString @EqualsAndHashCode @@ -20,4 +18,4 @@ public Tuple(BlogPostType type, String author) { this.type = type; this.author = author; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/CoronaServices.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/CoronaServices.java index 6fcecd0f..52783589 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/CoronaServices.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/CoronaServices.java @@ -1,19 +1,15 @@ package nitin.io.fileOperations.csvDataReadOperations.corona; -import org.apache.commons.lang3.time.StopWatch; - import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; - +import org.apache.commons.lang3.time.StopWatch; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 11:22 AM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 11:22 AM */ - public class CoronaServices { - private final static Logger LOGGER = Logger.getLogger(CoronaServices.class.getName()); + private static final Logger LOGGER = Logger.getLogger(CoronaServices.class.getName()); public static void main(String[] args) { List list = ReadCsv.getData(); @@ -21,13 +17,14 @@ public static void main(String[] args) { final StopWatch stopwatch = new StopWatch(); stopwatch.start(); - int totalDeaths = list.stream() - //.parallel() - .filter(entity -> entity.getDeaths() > 0) - .mapToInt(entity -> entity.getDeaths()) - .sum(); + int totalDeaths = + list.stream() + // .parallel() + .filter(entity -> entity.getDeaths() > 0) + .mapToInt(entity -> entity.getDeaths()) + .sum(); LOGGER.info("Starting long calculations: " + stopwatch); LOGGER.log(Level.WARNING, "Total Deaths : " + totalDeaths); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/Entity.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/Entity.java index 20385339..bad9013b 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/Entity.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/Entity.java @@ -1,16 +1,13 @@ package nitin.io.fileOperations.csvDataReadOperations.corona; +import java.util.Date; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.Date; - /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 9:38 AM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 9:38 AM */ - @Getter @Setter @ToString @@ -24,7 +21,15 @@ public class Entity { private int population; private String country; - public Entity(Date date, Integer FIPS, String county, String state, Integer confirmed, Integer deaths, Integer population, String country) { + public Entity( + Date date, + Integer FIPS, + String county, + String state, + Integer confirmed, + Integer deaths, + Integer population, + String country) { this.date = date; this.FIPS = FIPS; this.county = county; diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/ReadCsv.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/ReadCsv.java index 0996943c..5bc23a7c 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/ReadCsv.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/corona/ReadCsv.java @@ -1,7 +1,5 @@ package nitin.io.fileOperations.csvDataReadOperations.corona; -import org.apache.commons.lang3.math.NumberUtils; - import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; @@ -10,15 +8,15 @@ import java.text.SimpleDateFormat; import java.util.List; import java.util.stream.Collectors; +import org.apache.commons.lang3.math.NumberUtils; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 11:23 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 11:23 PM */ - public class ReadCsv { public static List getData() { - String file = "JavaLatest/src/main/java/com/fileOperations/csvDataReadOperations/corona/us_simplified.csv"; + String file = + "JavaLatest/src/main/java/com/fileOperations/csvDataReadOperations/corona/us_simplified.csv"; return readFileNreturnList(file); } @@ -31,11 +29,13 @@ private static List readFileNreturnList(String file) { e.printStackTrace(); } - List entityList = reader.lines().skip(1) - //.limit(200) - .map(line -> line.split(",")) - .map(ReadCsv::makeObjects) - .collect(Collectors.toList()); + List entityList = + reader.lines() + .skip(1) + // .limit(200) + .map(line -> line.split(",")) + .map(ReadCsv::makeObjects) + .collect(Collectors.toList()); try { reader.close(); @@ -45,23 +45,24 @@ private static List readFileNreturnList(String file) { return entityList; } - private static Entity makeObjects(String[] line) { Entity e = null; try { - e = new Entity(new SimpleDateFormat("yyyy-MM-dd").parse(line[0]), - NumberUtils.toInt(line[1], 0), - line[2], - line[3], - Integer.parseInt(line[4]), - Integer.parseInt(line[5]), - Integer.parseInt(line[6]), - line[7]); + e = + new Entity( + new SimpleDateFormat("yyyy-MM-dd").parse(line[0]), + NumberUtils.toInt(line[1], 0), + line[2], + line[3], + Integer.parseInt(line[4]), + Integer.parseInt(line[5]), + Integer.parseInt(line[6]), + line[7]); } catch (ParseException parseException) { parseException.printStackTrace(); } - //System.out.println(e); + // System.out.println(e); return e; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionGroups.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionGroups.java index e8a238f8..ff6a67f6 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionGroups.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionGroups.java @@ -1,20 +1,19 @@ package nitin.io.fileOperations.csvDataReadOperations.election; -import nitin.io.fileOperations.csvDataReadOperations.election.election.ElectionEntity; - import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import nitin.io.fileOperations.csvDataReadOperations.election.election.ElectionEntity; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 11:22 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 11:22 PM */ - public class ElectionGroups { - private static final Comparator> valueOrder = Map.Entry.comparingByValue().reversed(); - private static final Comparator> reversedValueOrder = valueOrder.reversed(); + private static final Comparator> valueOrder = + Map.Entry.comparingByValue().reversed(); + private static final Comparator> reversedValueOrder = + valueOrder.reversed(); public static void main(String[] args) { List list = ReadElectionCsv.getData(); @@ -28,8 +27,10 @@ public static void main(String[] args) { private static void sumVotesByParty(List list) { list.stream() - .collect(Collectors.groupingBy(ElectionEntity::getParty, - Collectors.summingInt(ElectionEntity::getVotes))) + .collect( + Collectors.groupingBy( + ElectionEntity::getParty, + Collectors.summingInt(ElectionEntity::getVotes))) .entrySet() .stream() .sorted(reversedValueOrder) diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionService.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionService.java index dcf1ae54..6f4aa333 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionService.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ElectionService.java @@ -1,19 +1,16 @@ package nitin.io.fileOperations.csvDataReadOperations.election; -import nitin.io.fileOperations.csvDataReadOperations.election.election.ElectionEntity; -import org.apache.commons.lang3.time.StopWatch; - import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; +import nitin.io.fileOperations.csvDataReadOperations.election.election.ElectionEntity; +import org.apache.commons.lang3.time.StopWatch; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 5:41 PM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 5:41 PM */ - public class ElectionService { - private final static Logger LOGGER = Logger.getLogger(ElectionService.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ElectionService.class.getName()); public static void main(String[] args) { List list = ReadElectionCsv.getData(); @@ -24,7 +21,7 @@ public static void main(String[] args) { stopwatch.start(); System.out.println("***********************************************************"); System.out.println("Votes Casted in Indore"); - //votesInIndore(list); + // votesInIndore(list); LOGGER.log(Level.INFO, "Starting long calculations: " + stopwatch); LOGGER.log(Level.OFF, "Starting long calculations: " + stopwatch); @@ -33,7 +30,6 @@ public static void main(String[] args) { int countAAPinMP = countAAPinMP(list, "Madhya Pradesh", "Aam Aadmi Party"); System.out.println(countAAPinMP); - System.out.println("***********************************************************"); System.out.println("Total Votes received by Modi"); list.stream() @@ -42,8 +38,8 @@ public static void main(String[] args) { System.out.println("***********************************************************"); System.out.println("Total Votes by each party in MP"); - //list.stream() - //.flatMap() + // list.stream() + // .flatMap() } private static Integer countAAPinMP(List list, String state, String party) { diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ReadElectionCsv.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ReadElectionCsv.java index 679a78f6..ee297d6c 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ReadElectionCsv.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/ReadElectionCsv.java @@ -1,23 +1,21 @@ package nitin.io.fileOperations.csvDataReadOperations.election; -import nitin.io.fileOperations.csvDataReadOperations.election.election.ElectionEntity; -import org.apache.commons.lang3.math.NumberUtils; - import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; +import nitin.io.fileOperations.csvDataReadOperations.election.election.ElectionEntity; +import org.apache.commons.lang3.math.NumberUtils; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 11:23 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 11:23 PM */ - public class ReadElectionCsv { public static List getData() { - String file = "JavaLatest/src/main/java/com/fileOperations/csvDataReadOperations/election/india_general_election_2014.csv"; + String file = + "JavaLatest/src/main/java/com/fileOperations/csvDataReadOperations/election/india_general_election_2014.csv"; return readFileNreturnList(file); } @@ -30,11 +28,13 @@ private static List readFileNreturnList(String file) { e.printStackTrace(); } - List entityList = reader.lines().skip(1) - //.limit(200) - .map(line -> line.split(",")) - .map(ReadElectionCsv::makeObjects) - .collect(Collectors.toList()); + List entityList = + reader.lines() + .skip(1) + // .limit(200) + .map(line -> line.split(",")) + .map(ReadElectionCsv::makeObjects) + .collect(Collectors.toList()); try { reader.close(); @@ -44,18 +44,12 @@ private static List readFileNreturnList(String file) { return entityList; } - private static ElectionEntity makeObjects(String[] line) { ElectionEntity e = null; - //State,Assembly,Candidate,Party,Votes - e = new ElectionEntity(line[0], - line[1], - line[2], - line[3], - NumberUtils.toInt(line[4], 0) - ); - - //System.out.println(e); + // State,Assembly,Candidate,Party,Votes + e = new ElectionEntity(line[0], line[1], line[2], line[3], NumberUtils.toInt(line[4], 0)); + + // System.out.println(e); return e; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/election/ElectionEntity.java b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/election/ElectionEntity.java index 9b723f9c..edaac983 100644 --- a/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/election/ElectionEntity.java +++ b/src/main/java/nitin/io/fileOperations/csvDataReadOperations/election/election/ElectionEntity.java @@ -5,10 +5,8 @@ import lombok.ToString; /** - * @author Created by nichaurasia - * Created on Wednesday, September/30/2020 at 9:38 AM + * @author Created by nichaurasia Created on Wednesday, September/30/2020 at 9:38 AM */ - @Getter @Setter @ToString @@ -19,12 +17,12 @@ public class ElectionEntity { private String party; private int votes; - public ElectionEntity(String state, String assembly, String candidate, String party, int votes) { + public ElectionEntity( + String state, String assembly, String candidate, String party, int votes) { this.state = state; this.assembly = assembly; this.candidate = candidate; this.party = party; this.votes = votes; } - } diff --git a/src/main/java/nitin/io/google/FileWrite.java b/src/main/java/nitin/io/google/FileWrite.java index 7b71d149..cb569939 100644 --- a/src/main/java/nitin/io/google/FileWrite.java +++ b/src/main/java/nitin/io/google/FileWrite.java @@ -13,8 +13,9 @@ public static void doSomethingParallely(String singleString) { Charset characterSet = Charset.defaultCharset(); Path path = Paths.get("src/main/resources/output.txt"); try { - //System.out.println("Writing into file the word :: " + singleString); - //Files.write(path, Collections.singleton(singleString), characterSet, StandardOpenOption.APPEND); + // System.out.println("Writing into file the word :: " + singleString); + // Files.write(path, Collections.singleton(singleString), characterSet, + // StandardOpenOption.APPEND); Files.write(path, Collections.singleton(singleString), characterSet); } catch (IOException e) { diff --git a/src/main/java/nitin/io/google/PartitionTest.java b/src/main/java/nitin/io/google/PartitionTest.java index aae33132..d81b5b3a 100644 --- a/src/main/java/nitin/io/google/PartitionTest.java +++ b/src/main/java/nitin/io/google/PartitionTest.java @@ -1,13 +1,13 @@ package nitin.io.google; import com.google.common.collect.Lists; - import java.util.Arrays; import java.util.List; public class PartitionTest { public static void main(String[] args) { - List> partition = Lists.partition(Arrays.asList(1, 2, 3, 4, 5, 6, 78, 8, 9, 10, 234), 3); + List> partition = + Lists.partition(Arrays.asList(1, 2, 3, 4, 5, 6, 78, 8, 9, 10, 234), 3); System.out.println(partition); } diff --git a/src/main/java/nitin/io/google/PartitionWriteCsv.java b/src/main/java/nitin/io/google/PartitionWriteCsv.java index 85f468ee..3085edfe 100644 --- a/src/main/java/nitin/io/google/PartitionWriteCsv.java +++ b/src/main/java/nitin/io/google/PartitionWriteCsv.java @@ -2,7 +2,6 @@ import com.config.Configs; import com.google.common.collect.Lists; - import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; @@ -17,7 +16,7 @@ public class PartitionWriteCsv { public static void main(String[] args) { final int BATCH_SIZE = 1000; - //Read from a CSV file and Write into another + // Read from a CSV file and Write into another String inputFile = Configs.ENABLE1_WORD_LIST_PATH; List stringList = new ArrayList<>(); try { @@ -29,10 +28,11 @@ public static void main(String[] args) { List> partition = Lists.partition(stringList, BATCH_SIZE); long startP = System.currentTimeMillis(); - partition.forEach(singleStringList -> { - singleStringList.parallelStream() - .forEach(singleString -> FileWrite.doSomethingParallely(singleString)); - }); + partition.forEach( + singleStringList -> { + singleStringList.parallelStream() + .forEach(singleString -> FileWrite.doSomethingParallely(singleString)); + }); long endP = System.currentTimeMillis(); long startS = System.currentTimeMillis(); @@ -43,7 +43,8 @@ public static void main(String[] args) { System.out.println("Processing Ended"); } - private static void results(int size, int partitionSize, int BATCH_SIZE, long parallelTime, long sequentialTime) { + private static void results( + int size, int partitionSize, int BATCH_SIZE, long parallelTime, long sequentialTime) { final String FILENAME = "src/main/resources/nitin.txt"; PrintWriter output = null; // Erasing files if already exist @@ -53,9 +54,11 @@ private static void results(int size, int partitionSize, int BATCH_SIZE, long pa e.printStackTrace(); } - output.println("###########################################################################"); + output.println( + "###########################################################################"); output.println(LocalDateTime.now()); - output.println("Total # of Strings " + size + " with total # Partition is " + partitionSize); + output.println( + "Total # of Strings " + size + " with total # Partition is " + partitionSize); output.println("Batch Size : " + BATCH_SIZE); output.println("Total Time Taken in parallel : " + parallelTime); output.println("Total Time Taken in sequential : " + sequentialTime); diff --git a/src/main/java/nitin/io/interactingWithUsers/ConsoleTest.java b/src/main/java/nitin/io/interactingWithUsers/ConsoleTest.java index 0d72b036..4ac6c6b4 100644 --- a/src/main/java/nitin/io/interactingWithUsers/ConsoleTest.java +++ b/src/main/java/nitin/io/interactingWithUsers/ConsoleTest.java @@ -7,17 +7,13 @@ /** * Created by Nitin Chaurasia on 3/6/16 at 2:10 AM. - *

- * Using Console to read input(usable only outside IDE) - * System.console() returns null in an IDE - * reader() and writer() - * format() and printf() - * flush() : forced any buffered output to be written immediately - * readLine() : - * readPassword() : like readLine BUT echoing is disabled. RETURNS a char ARRAY!! - * Reading password : String values are kept in shared memory pool for performance reasons in java. - * If the memory in application is ever dumped to the disk, the password could be recovered. Thus keep the - * password in the char[] using the readPassword(). + * + *

Using Console to read input(usable only outside IDE) System.console() returns null in an IDE + * reader() and writer() format() and printf() flush() : forced any buffered output to be written + * immediately readLine() : readPassword() : like readLine BUT echoing is disabled. RETURNS a char + * ARRAY!! Reading password : String values are kept in shared memory pool for performance reasons + * in java. If the memory in application is ever dumped to the disk, the password could be + * recovered. Thus keep the password in the char[] using the readPassword(). */ public class ConsoleTest { public static void main(String[] args) { @@ -76,8 +72,8 @@ public static void main(String[] args) { console.printf("Your password level is: " + password); String userInput = console.readLine(); - console.writer().println("You have entered from ..I did it so am recommending: " + userInput); + console.writer() + .println("You have entered from ..I did it so am recommending: " + userInput); } - } } diff --git a/src/main/java/nitin/io/interactingWithUsers/OldBufferedReader.java b/src/main/java/nitin/io/interactingWithUsers/OldBufferedReader.java index 08cf3b8c..102e7714 100644 --- a/src/main/java/nitin/io/interactingWithUsers/OldBufferedReader.java +++ b/src/main/java/nitin/io/interactingWithUsers/OldBufferedReader.java @@ -4,9 +4,7 @@ import java.io.IOException; import java.io.InputStreamReader; -/** - * Created by Nitin C on 3/6/2016. - */ +/** Created by Nitin C on 3/6/2016. */ public class OldBufferedReader { public static void main(String[] args) { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); @@ -20,6 +18,5 @@ public static void main(String[] args) { } System.out.println("You Entered " + input); - } } diff --git a/src/main/java/nitin/io/streams/BufferedIOStreams/CopyClassUsingBuffIO.java b/src/main/java/nitin/io/streams/BufferedIOStreams/CopyClassUsingBuffIO.java index eebfe256..dd26b3dd 100644 --- a/src/main/java/nitin/io/streams/BufferedIOStreams/CopyClassUsingBuffIO.java +++ b/src/main/java/nitin/io/streams/BufferedIOStreams/CopyClassUsingBuffIO.java @@ -3,26 +3,25 @@ import java.io.*; /** - * Created by Nitin C on 3/6/2016. - * instead of writing one byte at a time, read(byte[]) return number of bytes read into the array provided - * if the value returned is zero = EOF OR - * if value returned is less than the size of byte array, that was the last read from the file!! - *

- * for BOS write(byte[],int,int), input byte array, offset and length value - * offset is the number of values to skip before writing characters, and is often b_set to zero. - * the length is the number of characters from the byte array to write - *

- * WHY Buffered Classes Preferred? The buffered classes contains numerous performance improvements for - * managing stream data in memory - *

- * Buffer size tuning : + * Created by Nitin C on 3/6/2016. instead of writing one byte at a time, read(byte[]) return number + * of bytes read into the array provided if the value returned is zero = EOF OR if value returned is + * less than the size of byte array, that was the last read from the file!! + * + *

for BOS write(byte[],int,int), input byte array, offset and length value offset is the number + * of values to skip before writing characters, and is often b_set to zero. the length is the number + * of characters from the byte array to write + * + *

WHY Buffered Classes Preferred? The buffered classes contains numerous performance + * improvements for managing stream data in memory + * + *

Buffer size tuning : */ public class CopyClassUsingBuffIO { public static void main(String[] args) { // Binary File (Serialized file) to read binary data - //File source = new File("s.out"); + // File source = new File("s.out"); File source = new File("src/main/resources/s.out"); - File destination = new File("src/main/resources/s_copy.out");//Override mode + File destination = new File("src/main/resources/s_copy.out"); // Override mode try { copy(source, destination); @@ -34,17 +33,18 @@ public static void main(String[] args) { } private static void copy(File source, File destination) throws IOException { - try ( //try-with-resource keep the resources within () - InputStream in = new BufferedInputStream(new FileInputStream(source)); - OutputStream out = new BufferedOutputStream(new FileOutputStream(destination)) - )//try keeping the resources + try ( // try-with-resource keep the resources within () + InputStream in = new BufferedInputStream(new FileInputStream(source)); + OutputStream out = + new BufferedOutputStream( + new FileOutputStream(destination))) // try keeping the resources { - byte[] buffer = new byte[1024];//1 Kb Buffer + byte[] buffer = new byte[1024]; // 1 Kb Buffer int lenghtRead; while ((lenghtRead = in.read(buffer)) > 0) { out.write(buffer, 0, lenghtRead); out.flush(); } - }//try with resource ends here + } // try with resource ends here } } diff --git a/src/main/java/nitin/io/streams/FileIOStream/CopyClass.java b/src/main/java/nitin/io/streams/FileIOStream/CopyClass.java index 1046ee2a..09592fab 100644 --- a/src/main/java/nitin/io/streams/FileIOStream/CopyClass.java +++ b/src/main/java/nitin/io/streams/FileIOStream/CopyClass.java @@ -3,19 +3,19 @@ import java.io.*; /** - * Created by Nitin C on 3/6/2016. - * A class file is a - *

- * While reading a single value of a file input stream instance, the read method returns a primitive int value - * rather than a byte value. If the class does return a byte instead of an int, then there no is no way to know EOF. - * For compatibility, the file output stream also uses int instead of byte for writing a single byte to a file. + * Created by Nitin C on 3/6/2016. A class file is a + * + *

While reading a single value of a file input stream instance, the read method returns a + * primitive int value rather than a byte value. If the class does return a byte instead of an int, + * then there no is no way to know EOF. For compatibility, the file output stream also uses int + * instead of byte for writing a single byte to a file. */ public class CopyClass { public static void main(String[] args) { // Binary File (Serialized file) to read binary data - //File source = new File("s.out"); + // File source = new File("s.out"); File source = new File("N1PathFileTest.class"); - File destination = new File("s_copy.out");//Override mode + File destination = new File("s_copy.out"); // Override mode try { copy(source, destination); @@ -34,10 +34,9 @@ private static void copy(File source, File destination) throws IOException { int b; // The performance for large files would not be good as as it does not use any byte arrays - while ((b = in.read()) != -1) {//-1 is the EOF + while ((b = in.read()) != -1) { // -1 is the EOF out.write(b); System.out.println(b); } } - } diff --git a/src/main/java/nitin/io/streams/S1InputStream.java b/src/main/java/nitin/io/streams/S1InputStream.java index 091ff16e..193c49bb 100644 --- a/src/main/java/nitin/io/streams/S1InputStream.java +++ b/src/main/java/nitin/io/streams/S1InputStream.java @@ -7,8 +7,8 @@ /** * Created by Nitin C on 3/6/2016. - *

- * markSupported() : not all java io input stream classes support this operation + * + *

markSupported() : not all java io input stream classes support this operation */ public class S1InputStream { public static void main(String[] args) { @@ -21,19 +21,19 @@ public static void main(String[] args) { e.printStackTrace(); } - //Reading the stream + // Reading the stream try { - //Reads the forst charactr of the file. + // Reads the forst charactr of the file. System.out.println((char) inputstream.read()); // If no type casting, the return ASCII int nunmber System.out.println(inputstream.read()); if (inputstream.markSupported()) { - inputstream.mark(100); //Calling mark with read ahead limit + inputstream.mark(100); // Calling mark with read ahead limit System.out.println((char) inputstream.read()); inputstream.skip(2); System.out.println(inputstream.read()); - inputstream.reset();//resets to an earlier state + inputstream.reset(); // resets to an earlier state } else { System.out.println("Mark not supported"); diff --git a/src/main/java/nitin/mappers/jackson/EmployeeListMapper.java b/src/main/java/nitin/mappers/jackson/EmployeeListMapper.java index 393e5def..06071506 100644 --- a/src/main/java/nitin/mappers/jackson/EmployeeListMapper.java +++ b/src/main/java/nitin/mappers/jackson/EmployeeListMapper.java @@ -2,14 +2,13 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import nitin.mappers.jackson.model.Address; -import nitin.mappers.jackson.model.Employee; - import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; +import nitin.mappers.jackson.model.Address; +import nitin.mappers.jackson.model.Employee; public class EmployeeListMapper { public static void main(String[] args) throws IOException { @@ -17,58 +16,57 @@ public static void main(String[] args) throws IOException { URL url = new URL("file:src/main/resources/json/array-object-mapper.json"); - //typeRefForArray(objectMapper, url); + // typeRefForArray(objectMapper, url); typeRefForListOfMap(objectMapper, url); - - } private static void typeRefForListOfMap(ObjectMapper objectMapper, URL url) throws IOException { - //File from = new File("src/main/resources/json/array-a5object-mapper.json"); - //File from = new File("src/main/resources/json/single-a5object-mapper.json"); + // File from = new File("src/main/resources/json/array-a5object-mapper.json"); + // File from = new File("src/main/resources/json/single-a5object-mapper.json"); - TypeReference>> typeRef - = new TypeReference>>() { - }; + TypeReference>> typeRef = + new TypeReference>>() {}; List> employees = objectMapper.readValue(url, typeRef); -// for(Employee employee : employees){ -// //Removing the empty addresses -// employee.setAddresses(filterEmptyObjects(employee.getAddresses())); -// } + // for(Employee employee : employees){ + // //Removing the empty addresses + // employee.setAddresses(filterEmptyObjects(employee.getAddresses())); + // } - String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); + String jsonString = + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); System.out.println(jsonString); } private static void typeRefForArray(ObjectMapper objectMapper, URL url) throws IOException { - final List employees = objectMapper.readValue(url, new TypeReference>() { - }); + final List employees = + objectMapper.readValue(url, new TypeReference>() {}); for (Employee employee : employees) { - //Removing the empty addresses + // Removing the empty addresses employee.setAddresses(filterEmptyObjects(employee.getAddresses())); } - String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); + String jsonString = + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); System.out.println(jsonString); } private static List

filterEmptyObjects(List
addresses) { - addresses = addresses.stream() - .filter(singleAddress -> { - return nullAddressFilter(singleAddress); - }) - .collect(Collectors.toList()); + addresses = + addresses.stream() + .filter( + singleAddress -> { + return nullAddressFilter(singleAddress); + }) + .collect(Collectors.toList()); return addresses; } private static boolean nullAddressFilter(Address singleAddress) { - return (null != singleAddress.getAddressLine1() || - null != singleAddress.getAddressLine2() || - null != singleAddress.getCity() || - null != singleAddress.getState() || - null != singleAddress.getZip() - ); + return (null != singleAddress.getAddressLine1() + || null != singleAddress.getAddressLine2() + || null != singleAddress.getCity() + || null != singleAddress.getState() + || null != singleAddress.getZip()); } - } diff --git a/src/main/java/nitin/mappers/jackson/EmployeeMapperRunner.java b/src/main/java/nitin/mappers/jackson/EmployeeMapperRunner.java index 8d6948fc..f2ee90f0 100755 --- a/src/main/java/nitin/mappers/jackson/EmployeeMapperRunner.java +++ b/src/main/java/nitin/mappers/jackson/EmployeeMapperRunner.java @@ -4,9 +4,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import nitin.mappers.jackson.model.Address; -import nitin.mappers.jackson.model.Employee; - import java.io.IOException; import java.net.URL; import java.time.LocalDateTime; @@ -14,6 +11,8 @@ import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; +import nitin.mappers.jackson.model.Address; +import nitin.mappers.jackson.model.Employee; public class EmployeeMapperRunner { static ObjectMapper objectMapper; @@ -24,72 +23,80 @@ public class EmployeeMapperRunner { objectMapper.findAndRegisterModules(); } - public static void main(String[] args) throws IOException { URL resource = new URL("file:src/main/resources/json/single-object-mapper.json"); - //NOT USING DTO's. Thus there are no convertors or mappers or transformers. + // NOT USING DTO's. Thus there are no convertors or mappers or transformers. jsonFromFile(); -// directJavaObject(); -// typeRefForMap(objectMapper,resource); + // directJavaObject(); + // typeRefForMap(objectMapper,resource); } private static void jsonFromFile() throws IOException { URL resource = new URL("file:src/main/resources/json/single-object-mapper.json"); - List employees = objectMapper.readValue(resource, new TypeReference>() { - }); + List employees = + objectMapper.readValue(resource, new TypeReference>() {}); - //Removing the empty addresses - employees.forEach(eachEmployee -> eachEmployee.setAddresses(filterEmptyObjects(eachEmployee.getAddresses()))); + // Removing the empty addresses + employees.forEach( + eachEmployee -> + eachEmployee.setAddresses(filterEmptyObjects(eachEmployee.getAddresses()))); Collections.sort(employees, Comparator.comparing(Employee::getDatelocaltzdt).reversed()); - String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); + String jsonString = + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); System.out.println(jsonString); } private static List
filterEmptyObjects(List
addresses) { - addresses = addresses.stream() - .filter(singleAddress -> { - return nullAddressFilter(singleAddress); - }) - .collect(Collectors.toList()); + addresses = + addresses.stream() + .filter( + singleAddress -> { + return nullAddressFilter(singleAddress); + }) + .collect(Collectors.toList()); return addresses; } private static boolean nullAddressFilter(Address singleAddress) { - return (null != singleAddress.getAddressLine1() || - null != singleAddress.getAddressLine2() || - null != singleAddress.getCity() || - null != singleAddress.getState() || - null != singleAddress.getZip() - ); + return (null != singleAddress.getAddressLine1() + || null != singleAddress.getAddressLine2() + || null != singleAddress.getCity() + || null != singleAddress.getState() + || null != singleAddress.getZip()); } private static void directJavaObject() throws JsonProcessingException { - Employee employee = Employee.builder() - .name("Jane") - .dob(Date.from(ZonedDateTime.now().plusDays(1).toInstant())) - .datelocaltzdt(LocalDateTime.parse("2023-08-04T12:15:00", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))) - .phones(Map.of("Mobile", "123-456-7890", "Work", "(222) 222 2222")) - .addresses(List.of(Address.builder().build())) - .build(); - - //String jsonString = om.writeValueAsString(employee); - String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee); + Employee employee = + Employee.builder() + .name("Jane") + .dob(Date.from(ZonedDateTime.now().plusDays(1).toInstant())) + .datelocaltzdt( + LocalDateTime.parse( + "2023-08-04T12:15:00", + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))) + .phones(Map.of("Mobile", "123-456-7890", "Work", "(222) 222 2222")) + .addresses(List.of(Address.builder().build())) + .build(); + + // String jsonString = om.writeValueAsString(employee); + String jsonString = + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee); System.out.println(jsonString); } private static void typeRefForMap(ObjectMapper objectMapper, URL url) throws IOException { - TypeReference>> typeRef - = new TypeReference>>() { - }; + TypeReference>> typeRef = + new TypeReference>>() {}; List> employees = objectMapper.readValue(url, typeRef); - String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); + String jsonString = + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employees); System.out.println(jsonString); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/jackson/JacksonMapperTypes.java b/src/main/java/nitin/mappers/jackson/JacksonMapperTypes.java index 0f17160d..1f90e46f 100644 --- a/src/main/java/nitin/mappers/jackson/JacksonMapperTypes.java +++ b/src/main/java/nitin/mappers/jackson/JacksonMapperTypes.java @@ -2,21 +2,21 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import nitin.mappers.jackson.model.RandomVehicle; - import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; +import nitin.mappers.jackson.model.RandomVehicle; public class JacksonMapperTypes { - private static final String VEHICLE_URL = "https://random-data-api.com/api/vehicle/random_vehicle?size="; + private static final String VEHICLE_URL = + "https://random-data-api.com/api/vehicle/random_vehicle?size="; ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws IOException { - //List randomVehicles = getFewRandomVehicles(10); - //System.out.println(randomVehicles.size()); - //System.out.println(randomVehicles.get(0).toString()); + // List randomVehicles = getFewRandomVehicles(10); + // System.out.println(randomVehicles.size()); + // System.out.println(randomVehicles.get(0).toString()); RandomVehicle randomVehicle = getSingleJsonFromFile(); } @@ -26,13 +26,14 @@ public static List getFewRandomVehicles(int size) { List randomVehicleList = new ArrayList<>(); try { - randomVehicleList = mapper.readValue(new URL(VEHICLE_URL + size), new TypeReference>() { - }); + randomVehicleList = + mapper.readValue( + new URL(VEHICLE_URL + size), + new TypeReference>() {}); } catch (IOException e) { e.printStackTrace(); } return randomVehicleList; - } private static RandomVehicle getSingleJsonFromFile() throws IOException { @@ -45,4 +46,4 @@ private static RandomVehicle getSingleJsonFromFile() throws IOException { System.out.println(convertedJson); return vehicle; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/jackson/filter/DateOfBirthFilter.java b/src/main/java/nitin/mappers/jackson/filter/DateOfBirthFilter.java index 78589eca..35cfdd67 100755 --- a/src/main/java/nitin/mappers/jackson/filter/DateOfBirthFilter.java +++ b/src/main/java/nitin/mappers/jackson/filter/DateOfBirthFilter.java @@ -11,7 +11,7 @@ public boolean equals(Object obj) { if (obj == null || !(obj instanceof Date date)) { return false; } - //date should be in the past + // date should be in the past return date.before(new Date()); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/jackson/filter/DoorFilter.java b/src/main/java/nitin/mappers/jackson/filter/DoorFilter.java index 107983a7..47994c38 100644 --- a/src/main/java/nitin/mappers/jackson/filter/DoorFilter.java +++ b/src/main/java/nitin/mappers/jackson/filter/DoorFilter.java @@ -7,7 +7,7 @@ public boolean equals(Object obj) { if (obj == null || !(obj instanceof Integer doors)) { return false; } - //date should be in the past + // date should be in the past System.out.println(doors); return doors == 3; } diff --git a/src/main/java/nitin/mappers/jackson/filter/EmptyListFilter.java b/src/main/java/nitin/mappers/jackson/filter/EmptyListFilter.java index 0576d1db..be301ea4 100644 --- a/src/main/java/nitin/mappers/jackson/filter/EmptyListFilter.java +++ b/src/main/java/nitin/mappers/jackson/filter/EmptyListFilter.java @@ -11,18 +11,39 @@ public boolean equals(Object obj) { if (obj == null || !(obj instanceof List)) { return false; } - Optional result = ((List) obj).stream().filter( - eachObj -> Arrays.asList(eachObj.getClass().getDeclaredFields()).stream().filter(eachField -> { - try { - eachField.setAccessible(true); - if (eachField.get(eachObj) != null && !eachField.get(eachObj).toString().isEmpty()) { - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - }).count() > 0).findAny(); + Optional result = + ((List) obj) + .stream() + .filter( + eachObj -> + Arrays.asList( + eachObj.getClass() + .getDeclaredFields()) + .stream() + .filter( + eachField -> { + try { + eachField + .setAccessible( + true); + if (eachField.get( + eachObj) + != null + && !eachField + .get( + eachObj) + .toString() + .isEmpty()) { + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + }) + .count() + > 0) + .findAny(); return !result.isPresent(); } } diff --git a/src/main/java/nitin/mappers/jackson/filter/LicenseFilter.java b/src/main/java/nitin/mappers/jackson/filter/LicenseFilter.java index f9cafc9c..43d70d51 100644 --- a/src/main/java/nitin/mappers/jackson/filter/LicenseFilter.java +++ b/src/main/java/nitin/mappers/jackson/filter/LicenseFilter.java @@ -12,7 +12,7 @@ public boolean equals(Object obj) { if (obj == null || !(obj instanceof String)) { return false; } - //phone must match the regex pattern + // phone must match the regex pattern return !licensePattern.matcher(obj.toString()).matches(); } } diff --git a/src/main/java/nitin/mappers/jackson/filter/PhoneFilter.java b/src/main/java/nitin/mappers/jackson/filter/PhoneFilter.java index 4bd8ff95..a196c3fd 100755 --- a/src/main/java/nitin/mappers/jackson/filter/PhoneFilter.java +++ b/src/main/java/nitin/mappers/jackson/filter/PhoneFilter.java @@ -12,7 +12,7 @@ public boolean equals(Object obj) { if (obj == null || !(obj instanceof String)) { return false; } - //phone must match the regex pattern + // phone must match the regex pattern return !phonePattern.matcher(obj.toString()).matches(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/jackson/model/Address.java b/src/main/java/nitin/mappers/jackson/model/Address.java index cb9acfab..4a240edd 100644 --- a/src/main/java/nitin/mappers/jackson/model/Address.java +++ b/src/main/java/nitin/mappers/jackson/model/Address.java @@ -15,4 +15,4 @@ public class Address { private String city; private String state; private String zip; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/jackson/model/Employee.java b/src/main/java/nitin/mappers/jackson/model/Employee.java index eba11f3c..b9939514 100755 --- a/src/main/java/nitin/mappers/jackson/model/Employee.java +++ b/src/main/java/nitin/mappers/jackson/model/Employee.java @@ -5,15 +5,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; -import lombok.*; -import nitin.mappers.jackson.filter.DateOfBirthFilter; -import nitin.mappers.jackson.filter.EmptyListFilter; -import nitin.mappers.jackson.filter.PhoneFilter; - import java.time.LocalDateTime; import java.util.Date; import java.util.List; import java.util.Map; +import lombok.*; +import nitin.mappers.jackson.filter.DateOfBirthFilter; +import nitin.mappers.jackson.filter.EmptyListFilter; +import nitin.mappers.jackson.filter.PhoneFilter; @NoArgsConstructor @Getter @@ -40,6 +39,6 @@ public class Employee { @JsonProperty("addresses") @JsonInclude(value = JsonInclude.Include.CUSTOM, contentFilter = EmptyListFilter.class) - //@JsonInclude(JsonInclude.Include.NON_EMPTY) + // @JsonInclude(JsonInclude.Include.NON_EMPTY) private List
addresses; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/jackson/model/RandomVehicle.java b/src/main/java/nitin/mappers/jackson/model/RandomVehicle.java index 50e67350..f28b7736 100644 --- a/src/main/java/nitin/mappers/jackson/model/RandomVehicle.java +++ b/src/main/java/nitin/mappers/jackson/model/RandomVehicle.java @@ -2,14 +2,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import lombok.*; import nitin.mappers.jackson.filter.DoorFilter; import nitin.mappers.jackson.filter.EmptyListFilter; import nitin.mappers.jackson.filter.LicenseFilter; import nitin.mappers.jackson.filter.PhoneFilter; -import java.util.List; - @Getter @Setter @AllArgsConstructor @@ -18,40 +17,54 @@ public class RandomVehicle { @JsonProperty("id") private Integer id; + @JsonProperty("uid") private String uid; + @JsonProperty("vin") private String vin; + @JsonProperty("make_and_model") @JsonInclude(content = JsonInclude.Include.CUSTOM, contentFilter = PhoneFilter.class) private String makeAndModel; + @JsonProperty("color") @JsonInclude(JsonInclude.Include.NON_NULL) private String color; + @JsonProperty("transmission") private String transmission; + @JsonProperty("drive_type") private String driveType; + @JsonProperty("fuel_type") @JsonInclude(JsonInclude.Include.NON_NULL) private String fuelType; + @JsonProperty("car_type") private String carType; + @JsonProperty("car_options") @JsonInclude(JsonInclude.Include.NON_NULL) private List carOptions; + @JsonProperty("specs") @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = EmptyListFilter.class) private List specs; + @JsonProperty("doors") @JsonInclude(content = JsonInclude.Include.CUSTOM, valueFilter = DoorFilter.class) private Integer doors; + @JsonProperty("mileage") private Integer mileage; + @JsonProperty("kilometrage") private Integer kilometer_range; + @JsonProperty("license_plate") - //@JsonInclude(content = JsonInclude.Include.CUSTOM, contentFilter = LicenseFilter.class) + // @JsonInclude(content = JsonInclude.Include.CUSTOM, contentFilter = LicenseFilter.class) @JsonInclude(content = JsonInclude.Include.CUSTOM, valueFilter = LicenseFilter.class) private String licensePlate; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/mapstruct/MapStructTestRunner.java b/src/main/java/nitin/mappers/mapstruct/MapStructTestRunner.java index 8f6e9ba0..8e5ef11a 100644 --- a/src/main/java/nitin/mappers/mapstruct/MapStructTestRunner.java +++ b/src/main/java/nitin/mappers/mapstruct/MapStructTestRunner.java @@ -1,14 +1,13 @@ package nitin.mappers.mapstruct; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URL; import nitin.mappers.mapstruct.dto.TesterDto; import nitin.mappers.mapstruct.mapper.TestMapper; import nitin.mappers.mapstruct.model.Tester; import org.mapstruct.factory.Mappers; -import java.io.IOException; -import java.net.URL; - public class MapStructTestRunner { public static void main(String[] args) throws IOException { final TestMapper mapper = Mappers.getMapper(TestMapper.class); @@ -21,12 +20,12 @@ public static void main(String[] args) throws IOException { TesterDto testerDto = mapper.testMapper(tester); System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(testerDto)); -/* - Map map = om.readValue(resource, new TypeReference>() {}); - TesterDto testerDto2 = mapper.testMapperFromMap(map); - System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(testerDto2)); + /* + Map map = om.readValue(resource, new TypeReference>() {}); + TesterDto testerDto2 = mapper.testMapperFromMap(map); + System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(testerDto2)); - */ + */ } diff --git a/src/main/java/nitin/mappers/mapstruct/MultiMapperRunner.java b/src/main/java/nitin/mappers/mapstruct/MultiMapperRunner.java index 43ea4c23..f1c55611 100644 --- a/src/main/java/nitin/mappers/mapstruct/MultiMapperRunner.java +++ b/src/main/java/nitin/mappers/mapstruct/MultiMapperRunner.java @@ -5,16 +5,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.utilities.InternetUtilities; import com.utilities.RestGETReadUtility; -import nitin.mappers.mapstruct.dto.PersonDto; -import nitin.mappers.mapstruct.mapper.PersonMapper; -import nitin.mappers.mapstruct.model.Employee; -import org.mapstruct.factory.Mappers; - import java.io.IOException; import java.net.URL; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; +import nitin.mappers.mapstruct.dto.PersonDto; +import nitin.mappers.mapstruct.mapper.PersonMapper; +import nitin.mappers.mapstruct.model.Employee; +import org.mapstruct.factory.Mappers; public class MultiMapperRunner { public static void main(String[] args) throws IOException { @@ -23,12 +22,16 @@ public static void main(String[] args) throws IOException { URL resource = new URL("file:src/main/resources/json/single-a5object-mapper.json"); ObjectMapper om = new ObjectMapper(); - //Convert this to CompletableFuturesSingleMapperRunner - CompletableFuture employee = CompletableFuture.supplyAsync(() -> getEmployee(resource, om)); - CompletableFuture> beers = CompletableFuture.supplyAsync(() -> InternetUtilities.getBeers(2)); - CompletableFuture> vehicles = CompletableFuture.supplyAsync(() -> RestGETReadUtility.getRandomVehicles(2)); + // Convert this to CompletableFuturesSingleMapperRunner + CompletableFuture employee = + CompletableFuture.supplyAsync(() -> getEmployee(resource, om)); + CompletableFuture> beers = + CompletableFuture.supplyAsync(() -> InternetUtilities.getBeers(2)); + CompletableFuture> vehicles = + CompletableFuture.supplyAsync(() -> RestGETReadUtility.getRandomVehicles(2)); - PersonDto personDto = mapper.personMapper(employee.join(), beers.join().get(0), vehicles.join().get(0)); + PersonDto personDto = + mapper.personMapper(employee.join(), beers.join().get(0), vehicles.join().get(0)); System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(personDto)); } @@ -44,17 +47,19 @@ private static Employee getEmployee(URL resource, ObjectMapper om) { } private static void checkIfNeeded(Employee employee) { - //Removing the empty addresses - employee.setAddresses(employee.getAddresses().stream() - .filter(singleAddress -> ( - null != singleAddress.getAddressLine1() || - null != singleAddress.getAddressLine2() || - null != singleAddress.getCity() || - null != singleAddress.getState() || - null != singleAddress.getZip() - )).collect(Collectors.toList())); - - //String jsonString = om.writerWithDefaultPrettyPrinter().writeValueAsString(employee); - //System.out.println(jsonString); + // Removing the empty addresses + employee.setAddresses( + employee.getAddresses().stream() + .filter( + singleAddress -> + (null != singleAddress.getAddressLine1() + || null != singleAddress.getAddressLine2() + || null != singleAddress.getCity() + || null != singleAddress.getState() + || null != singleAddress.getZip())) + .collect(Collectors.toList())); + + // String jsonString = om.writerWithDefaultPrettyPrinter().writeValueAsString(employee); + // System.out.println(jsonString); } } diff --git a/src/main/java/nitin/mappers/mapstruct/SingleMapperRunner.java b/src/main/java/nitin/mappers/mapstruct/SingleMapperRunner.java index b92abdd5..3a55e435 100644 --- a/src/main/java/nitin/mappers/mapstruct/SingleMapperRunner.java +++ b/src/main/java/nitin/mappers/mapstruct/SingleMapperRunner.java @@ -1,15 +1,14 @@ package nitin.mappers.mapstruct; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URL; +import java.util.stream.Collectors; import nitin.mappers.mapstruct.dto.EmployeeDto; import nitin.mappers.mapstruct.mapper.EmployeeMapper; import nitin.mappers.mapstruct.model.Employee; import org.mapstruct.factory.Mappers; -import java.io.IOException; -import java.net.URL; -import java.util.stream.Collectors; - public class SingleMapperRunner { public static void main(String[] args) throws IOException { final EmployeeMapper mapper = Mappers.getMapper(EmployeeMapper.class); @@ -17,7 +16,7 @@ public static void main(String[] args) throws IOException { URL resource = new URL("file:src/main/resources/json/single-a5object-mapper.json"); ObjectMapper om = new ObjectMapper(); - //Convert this to CompletableFuturesSingleMapperRunner + // Convert this to CompletableFuturesSingleMapperRunner Employee employee = om.readValue(resource, Employee.class); checkIfNeeded(employee); @@ -26,17 +25,19 @@ public static void main(String[] args) throws IOException { } private static void checkIfNeeded(Employee employee) { - //Removing the empty addresses - employee.setAddresses(employee.getAddresses().stream() - .filter(singleAddress -> ( - null != singleAddress.getAddressLine1() || - null != singleAddress.getAddressLine2() || - null != singleAddress.getCity() || - null != singleAddress.getState() || - null != singleAddress.getZip() - )).collect(Collectors.toList())); - - //String jsonString = om.writerWithDefaultPrettyPrinter().writeValueAsString(employee); - //System.out.println(jsonString); + // Removing the empty addresses + employee.setAddresses( + employee.getAddresses().stream() + .filter( + singleAddress -> + (null != singleAddress.getAddressLine1() + || null != singleAddress.getAddressLine2() + || null != singleAddress.getCity() + || null != singleAddress.getState() + || null != singleAddress.getZip())) + .collect(Collectors.toList())); + + // String jsonString = om.writerWithDefaultPrettyPrinter().writeValueAsString(employee); + // System.out.println(jsonString); } } diff --git a/src/main/java/nitin/mappers/mapstruct/dto/EmployeeDto.java b/src/main/java/nitin/mappers/mapstruct/dto/EmployeeDto.java index 25086e3d..e5b4298b 100644 --- a/src/main/java/nitin/mappers/mapstruct/dto/EmployeeDto.java +++ b/src/main/java/nitin/mappers/mapstruct/dto/EmployeeDto.java @@ -1,11 +1,10 @@ package nitin.mappers.mapstruct.dto; -import lombok.*; -import nitin.mappers.mapstruct.model.Address; - import java.util.Date; import java.util.List; import java.util.Map; +import lombok.*; +import nitin.mappers.mapstruct.model.Address; @NoArgsConstructor @Getter diff --git a/src/main/java/nitin/mappers/mapstruct/dto/PersonDto.java b/src/main/java/nitin/mappers/mapstruct/dto/PersonDto.java index d29a3c7f..14b667a2 100644 --- a/src/main/java/nitin/mappers/mapstruct/dto/PersonDto.java +++ b/src/main/java/nitin/mappers/mapstruct/dto/PersonDto.java @@ -1,8 +1,7 @@ package nitin.mappers.mapstruct.dto; -import lombok.*; - import java.util.List; +import lombok.*; @NoArgsConstructor @Getter @@ -14,12 +13,12 @@ public class PersonDto { private String employeeFirstName; private String employeeLastName; private String birthDate; - private List phones;//From Map to List - //Beer + private List phones; // From Map to List + // Beer private String beerBrand; private String beerName; private String alcohol; - //Vehicle + // Vehicle private String carMakeAndModel; private String carColor; private String driveType; @@ -27,7 +26,6 @@ public class PersonDto { private List specs; private Integer doors; private String licensePlate; - //Testing Null Field + // Testing Null Field private String extraField; } - diff --git a/src/main/java/nitin/mappers/mapstruct/dto/TesterDto.java b/src/main/java/nitin/mappers/mapstruct/dto/TesterDto.java index 0d9b9ef8..9b6d6464 100644 --- a/src/main/java/nitin/mappers/mapstruct/dto/TesterDto.java +++ b/src/main/java/nitin/mappers/mapstruct/dto/TesterDto.java @@ -1,8 +1,7 @@ package nitin.mappers.mapstruct.dto; -import lombok.*; - import java.util.List; +import lombok.*; @NoArgsConstructor @Getter diff --git a/src/main/java/nitin/mappers/mapstruct/mapper/EmployeeMapper.java b/src/main/java/nitin/mappers/mapstruct/mapper/EmployeeMapper.java index ae1567c3..d3044b20 100644 --- a/src/main/java/nitin/mappers/mapstruct/mapper/EmployeeMapper.java +++ b/src/main/java/nitin/mappers/mapstruct/mapper/EmployeeMapper.java @@ -11,7 +11,7 @@ public interface EmployeeMapper { @Mapping(target = "dateOfBirth", source = "entity.dob") @Mapping(target = "phones", source = "entity.phones") @Mapping(target = "addresses", source = "entity.addresses") - EmployeeDto employeeToEmployeeDto(Employee entity);//This will be implemented by MapStruct + EmployeeDto employeeToEmployeeDto(Employee entity); // This will be implemented by MapStruct /* Employee employeeDTOtoEmployee(EmployeeDto dto); diff --git a/src/main/java/nitin/mappers/mapstruct/mapper/PersonMapper.java b/src/main/java/nitin/mappers/mapstruct/mapper/PersonMapper.java index a32587ce..207c82ba 100644 --- a/src/main/java/nitin/mappers/mapstruct/mapper/PersonMapper.java +++ b/src/main/java/nitin/mappers/mapstruct/mapper/PersonMapper.java @@ -2,22 +2,24 @@ import com.entity.Beer; import com.entity.Vehicle; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import nitin.mappers.mapstruct.dto.PersonDto; import nitin.mappers.mapstruct.model.Employee; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - @Mapper public interface PersonMapper { @Mapping(target = "employeeFirstName", source = "employee.name") @Mapping(target = "employeeLastName", source = "employee.name") @Mapping(target = "birthDate", source = "employee.dob", dateFormat = "dd-MM-yyyy HH:mm:ss") - @Mapping(target = "phones", source = "employee.phones", qualifiedByName = "processPhoneMap")//Map to List + @Mapping( + target = "phones", + source = "employee.phones", + qualifiedByName = "processPhoneMap") // Map to List @Mapping(target = "beerBrand", source = "beer.brand") @Mapping(target = "beerName", source = "beer.name") @Mapping(target = "alcohol", source = "beer.alcohol") @@ -28,10 +30,12 @@ public interface PersonMapper { @Mapping(target = "specs", source = "vehicle.specs") @Mapping(target = "doors", source = "vehicle.doors") @Mapping(target = "licensePlate", source = "vehicle.licensePlate") - @Mapping(target = "extraField", source = "employee.nullTester", defaultExpression = "java(com.github.javafaker.Faker.instance().chuckNorris().fact())") + @Mapping( + target = "extraField", + source = "employee.nullTester", + defaultExpression = "java(com.github.javafaker.Faker.instance().chuckNorris().fact())") PersonDto personMapper(Employee employee, Beer beer, Vehicle vehicle); - @Named("processPhoneMap") default List processPhoneMap(Map phoneMap) { List list = new ArrayList<>(); @@ -42,4 +46,4 @@ default List processPhoneMap(Map phoneMap) { } return list; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/mapstruct/mapper/TestMapper.java b/src/main/java/nitin/mappers/mapstruct/mapper/TestMapper.java index 69047e27..d8fd70ea 100644 --- a/src/main/java/nitin/mappers/mapstruct/mapper/TestMapper.java +++ b/src/main/java/nitin/mappers/mapstruct/mapper/TestMapper.java @@ -10,6 +10,6 @@ public interface TestMapper { @Mapping(target = "test", source = "tester.test", numberFormat = "₹#.00") TesterDto testMapper(Tester tester); -// @Mapping(target = "test", source = "tester") -// List listPrices(Tester tester); -} \ No newline at end of file + // @Mapping(target = "test", source = "tester") + // List listPrices(Tester tester); +} diff --git a/src/main/java/nitin/mappers/mapstruct/model/Address.java b/src/main/java/nitin/mappers/mapstruct/model/Address.java index 99f70bf4..b5595310 100644 --- a/src/main/java/nitin/mappers/mapstruct/model/Address.java +++ b/src/main/java/nitin/mappers/mapstruct/model/Address.java @@ -13,4 +13,4 @@ public class Address { private String city; private String state; private String zip; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/mapstruct/model/Education.java b/src/main/java/nitin/mappers/mapstruct/model/Education.java index 9b0e4934..21df1a8c 100644 --- a/src/main/java/nitin/mappers/mapstruct/model/Education.java +++ b/src/main/java/nitin/mappers/mapstruct/model/Education.java @@ -1,5 +1,3 @@ package nitin.mappers.mapstruct.model; -public class Education { - -} +public class Education {} diff --git a/src/main/java/nitin/mappers/mapstruct/model/Employee.java b/src/main/java/nitin/mappers/mapstruct/model/Employee.java index 7fb8b67f..394664ec 100755 --- a/src/main/java/nitin/mappers/mapstruct/model/Employee.java +++ b/src/main/java/nitin/mappers/mapstruct/model/Employee.java @@ -1,12 +1,11 @@ package nitin.mappers.mapstruct.model; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; -import nitin.mappers.jackson.model.Address; - import java.util.Date; import java.util.List; import java.util.Map; +import lombok.*; +import nitin.mappers.jackson.model.Address; @NoArgsConstructor @Getter @@ -16,11 +15,15 @@ public class Employee { @JsonProperty("name") private String name; + @JsonProperty("dateOfBirth") private Date dob; + @JsonProperty("phones") private Map phones; + @JsonProperty("addresses") private List
addresses; + private String nullTester; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/mappers/mapstruct/model/Salary.java b/src/main/java/nitin/mappers/mapstruct/model/Salary.java index 2668bdec..f744d9dd 100644 --- a/src/main/java/nitin/mappers/mapstruct/model/Salary.java +++ b/src/main/java/nitin/mappers/mapstruct/model/Salary.java @@ -1,4 +1,3 @@ package nitin.mappers.mapstruct.model; -public class Salary { -} +public class Salary {} diff --git a/src/main/java/nitin/mappers/mapstruct/model/Tester.java b/src/main/java/nitin/mappers/mapstruct/model/Tester.java index ba95f7e9..4449310b 100644 --- a/src/main/java/nitin/mappers/mapstruct/model/Tester.java +++ b/src/main/java/nitin/mappers/mapstruct/model/Tester.java @@ -1,9 +1,8 @@ package nitin.mappers.mapstruct.model; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - import java.util.List; +import lombok.*; @NoArgsConstructor @Getter @@ -13,7 +12,7 @@ public class Tester { @JsonProperty("tester") private Double test; + @JsonProperty("testerList") private List testList; - -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/Factorial.java b/src/main/java/nitin/multithreading/Factorial.java index 9a5c8e81..7f81c9d4 100644 --- a/src/main/java/nitin/multithreading/Factorial.java +++ b/src/main/java/nitin/multithreading/Factorial.java @@ -1,10 +1,7 @@ package nitin.multithreading; -import lombok.NoArgsConstructor; import java.math.BigInteger; - -import static com.utilities.MultiThreadUtility.logMessage; -import static com.utilities.MultiThreadUtility.logShortMessage; +import lombok.NoArgsConstructor; @NoArgsConstructor public class Factorial { @@ -14,7 +11,7 @@ public BigInteger compute(long inputNumber) { } private BigInteger factorial(long n) { - //logMessage("factorial running"); + // logMessage("factorial running"); BigInteger result = BigInteger.ONE; for (long i = n; i > 0; i--) { diff --git a/src/main/java/nitin/multithreading/IOBoundOperations.java b/src/main/java/nitin/multithreading/IOBoundOperations.java index f83216b1..5d500970 100644 --- a/src/main/java/nitin/multithreading/IOBoundOperations.java +++ b/src/main/java/nitin/multithreading/IOBoundOperations.java @@ -1,6 +1,5 @@ package nitin.multithreading; -import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -26,13 +25,19 @@ private static void performTask() { // Simulates a long blocking IO private static void blockingIoOperation() { String unit = "MB"; - long bytesInMb = (1024*1024); + long bytesInMb = (1024 * 1024); Runtime runtime = Runtime.getRuntime(); - //int sleepTime = 10 + new Random().nextInt(991); // 10 to 1000 ms + // int sleepTime = 10 + new Random().nextInt(991); // 10 to 1000 ms int sleepTime = 1000; - System.out.println("Executing a blocking task from thread: " + Thread.currentThread() + " sleeping : " + sleepTime + "ms"); - System.out.println("Available memory when task created: " + runtime.freeMemory()/bytesInMb + unit); + System.out.println( + "Executing a blocking task from thread: " + + Thread.currentThread() + + " sleeping : " + + sleepTime + + "ms"); + System.out.println( + "Available memory when task created: " + runtime.freeMemory() / bytesInMb + unit); try { Thread.sleep(sleepTime); diff --git a/src/main/java/nitin/multithreading/JconsoleThreadDebug.java b/src/main/java/nitin/multithreading/JconsoleThreadDebug.java index 64cd3fdd..0e368865 100644 --- a/src/main/java/nitin/multithreading/JconsoleThreadDebug.java +++ b/src/main/java/nitin/multithreading/JconsoleThreadDebug.java @@ -2,9 +2,7 @@ import java.io.IOException; -/** - * Created by Nitin Chaurasia on 12/5/15 at 6:06 PM. - */ +/** Created by Nitin Chaurasia on 12/5/15 at 6:06 PM. */ public class JconsoleThreadDebug { public static void main(String[] args) { DebugClass d = new DebugClass(); @@ -14,7 +12,6 @@ public static void main(String[] args) { } } - class DebugClass implements Runnable { @Override public void run() { @@ -22,7 +19,7 @@ public void run() { // // Get Process Id - //Turning on jconsole + // Turning on jconsole String command = "jconsole"; Process p; @@ -35,7 +32,7 @@ public void run() { e.printStackTrace(); } - //Sleep to see the results + // Sleep to see the results try { Thread.sleep(10_000); } catch (InterruptedException e) { diff --git a/src/main/java/nitin/multithreading/MatrixMultiplication.java b/src/main/java/nitin/multithreading/MatrixMultiplication.java index 13f451af..7ebffb16 100644 --- a/src/main/java/nitin/multithreading/MatrixMultiplication.java +++ b/src/main/java/nitin/multithreading/MatrixMultiplication.java @@ -5,15 +5,11 @@ import java.io.PrintWriter; import java.util.Random; -/** - * Created by Nitin C on 12/7/2015. - * Assignment Matrix Multiplication in Java - */ - +/** Created by Nitin C on 12/7/2015. Assignment Matrix Multiplication in Java */ public class MatrixMultiplication { /*GLOBAL VARIABLE DECLARATION */ - //Dimensions of the Matrices to be multiplied + // Dimensions of the Matrices to be multiplied public static final int ROW_A = 3; public static final int COL_A = 3; public static final int ROW_B = 3; @@ -27,7 +23,7 @@ public class MatrixMultiplication { /* Variables for tracking time execution time*/ static double begin = 0, end = 0; static double time_spent = 0; - //Random Number Range + // Random Number Range public final int MAXRAND = 99; /* MAIN BEGINS */ @@ -37,11 +33,11 @@ public static void main(String[] args) { System.out.println(" JAVA Multithreading Matrix Multiplication "); System.out.println("=============================================================== \n"); - //FUTURE: to be taken the count of thread by the user -// System.out.println("Enter Number of Threads: "); -// Scanner in = new Scanner(System.in); -// int numThreads = in.nextInt(); -// in.close();//Close the input channel + // FUTURE: to be taken the count of thread by the user + // System.out.println("Enter Number of Threads: "); + // Scanner in = new Scanner(System.in); + // int numThreads = in.nextInt(); + // in.close();//Close the input channel // Hardcoding the number of threads manually numThreads = ROW_A * COL_B; @@ -52,17 +48,17 @@ public static void main(String[] args) { System.out.println("Column for Matrix A should be same as that of Row for Matrix B\n"); System.out.println("Multiplication is not possible\n"); /* NEED TO LEARN: CAN USE USER DEFINED EXCEPTION AS WELL */ - return; //used to control the untimely exit + return; // used to control the untimely exit } /* Generate Random numbers and fill them in the Matrix*/ MatrixMultiplication mm = new MatrixMultiplication(); - //Fill the Matrices with Random Values + // Fill the Matrices with Random Values /*FOR DEBUGGING: ALL VALUES IN MAT A are 3 and MAT B are 1*/ mm.fillMatrix(); - //play with only one a5object to understand a14concurrency challenges + // play with only one a5object to understand a14concurrency challenges Multiply m = new Multiply(); Thread[] t = new Thread[numThreads]; @@ -92,9 +88,19 @@ public static void main(String[] args) { end = System.currentTimeMillis(); time_spent = end - begin; - System.out.println("Execution time of Matrices of dim " + - ROW_A + "X" + COL_A + " & " + ROW_B + "X" + COL_B + - "with " + numThreads + " threads is " + time_spent); + System.out.println( + "Execution time of Matrices of dim " + + ROW_A + + "X" + + COL_A + + " & " + + ROW_B + + "X" + + COL_B + + "with " + + numThreads + + " threads is " + + time_spent); // Write the data inb the text file try { @@ -104,37 +110,36 @@ public static void main(String[] args) { } System.out.println("-------------PROGRAM TERMINATES--------------"); - - }//Main Ends here + } // Main Ends here void fillMatrix() { /* Initialize the seed to generate Random Values */ Random generator = new Random(System.currentTimeMillis()); /* Generate Matrices*/ - //Matrix A + // Matrix A for (int i = 0; i < ROW_A; i++) { for (int j = 0; j < COL_A; j++) { - //matA[i][j] = ((double) generator.nextInt(MAXRAND)); + // matA[i][j] = ((double) generator.nextInt(MAXRAND)); matA[i][j] = generator.nextInt(60); - }//End Loop for Column - }//End Loop for Row + } // End Loop for Column + } // End Loop for Row - //Matrix B + // Matrix B for (int i = 0; i < ROW_B; i++) { for (int j = 0; j < COL_B; j++) { - //matB[i][j] = ((double) generator.nextInt(MAXRAND)); + // matB[i][j] = ((double) generator.nextInt(MAXRAND)); matB[i][j] = generator.nextInt(90); - }//End Loop for Column - }//End Loop for Row + } // End Loop for Column + } // End Loop for Row - //Matrix C (initialized to Zero) + // Matrix C (initialized to Zero) for (int i = 0; i < ROW_A; i++) { for (int j = 0; j < COL_B; j++) { matC[i][j] = 0; - }//End Loop for Column - }//End Loop for Row - }//Fill Matrix Ends + } // End Loop for Column + } // End Loop for Row + } // Fill Matrix Ends void collectResults() throws IOException { final String FILENAME = "nitin.txt"; @@ -144,38 +149,37 @@ void collectResults() throws IOException { PrintWriter output = new PrintWriter(new FileWriter(FILENAME, false)); /* Generate Matrices*/ - //Matrix A + // Matrix A output.println("Matrix A: "); for (int i = 0; i < ROW_A; i++) { for (int j = 0; j < COL_A; j++) { output.print(matA[i][j] + " "); - }//End Loop for Column - output.println();//Change line - }//End Loop for Row + } // End Loop for Column + output.println(); // Change line + } // End Loop for Row - //Matrix B + // Matrix B output.println("Matrix B: "); for (int i = 0; i < ROW_B; i++) { for (int j = 0; j < COL_B; j++) { output.print(matB[i][j] + " "); - }//End Loop for Column - output.println();//Change line - }//End Loop for Row + } // End Loop for Column + output.println(); // Change line + } // End Loop for Row - //Matrix C (initialized to Zero) + // Matrix C (initialized to Zero) output.println("Matrix C: "); for (int i = 0; i < ROW_A; i++) { for (int j = 0; j < COL_B; j++) { output.print(matC[i][j] + " "); - }//End Loop for Column - output.println();//Change line - }//End Loop for Row + } // End Loop for Column + output.println(); // Change line + } // End Loop for Row // Does not write without flush output.flush(); output.close(); } - } /* For multithreaded threaded multiplication, Rows from matrix A is to be multiplied with Columns @@ -199,15 +203,23 @@ public void run() { acted upon by 3 threads. Problem can be solved by having only 3 threads, But this was not the intended behaviour expected */ - MatrixMultiplication.matC[i][j] = MatrixMultiplication.matC[i][j] + (MatrixMultiplication.matA[i][k] * MatrixMultiplication.matB[k][j]); + MatrixMultiplication.matC[i][j] = + MatrixMultiplication.matC[i][j] + + (MatrixMultiplication.matA[i][k] + * MatrixMultiplication.matB[k][j]); } // Console logging for the debugging System.out.print("Operated by Thread : " + Thread.currentThread()); - System.out.print(" --- Entry inserted at " + i + j + " is :" + MatrixMultiplication.matC[i][j]); + System.out.print( + " --- Entry inserted at " + + i + + j + + " is :" + + MatrixMultiplication.matC[i][j]); } } System.out.println(); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/ParallelFactorial.java b/src/main/java/nitin/multithreading/ParallelFactorial.java index d043658c..e0d95fe5 100644 --- a/src/main/java/nitin/multithreading/ParallelFactorial.java +++ b/src/main/java/nitin/multithreading/ParallelFactorial.java @@ -1,13 +1,13 @@ package nitin.multithreading; +import static com.utilities.PerformanceUtility.startTimer; +import static com.utilities.PerformanceUtility.stopTimer; + import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; -import static com.utilities.PerformanceUtility.startTimer; -import static com.utilities.PerformanceUtility.stopTimer; - public class ParallelFactorial { public static void main(String[] args) throws InterruptedException { List inputNumbers = List.of(100L, 3435L, 35435L, 2324L, 4656L, 23L, 5556L); @@ -48,28 +48,28 @@ private static void sequential(List inputNumbers, Factorial factorial) { private static void parallelStream(List inputNumbers, Factorial factorial) { startTimer(); - List list2 = inputNumbers.parallelStream() - .map(factorial::compute) - .toList(); + List list2 = inputNumbers.parallelStream().map(factorial::compute).toList(); stopTimer(); } private static void sequentialWithStreams(List inputNumbers, Factorial factorial) { startTimer(); - List list = inputNumbers.stream() - .map(factorial::compute) - .toList(); + List list = inputNumbers.stream().map(factorial::compute).toList(); stopTimer(); } - private static void runWithTraditionalFactorial(List inputNumbers, Factorial factorial) throws InterruptedException { + private static void runWithTraditionalFactorial(List inputNumbers, Factorial factorial) + throws InterruptedException { List threads = new ArrayList<>(); for (long inputNumber : inputNumbers) { - threads.add(new Thread(() -> { - BigInteger computedFactorial = factorial.compute(inputNumber); - //logShortMessage(STR."Factorial of \{inputNumber} is \{computedFactorial}"); - })); + threads.add( + new Thread( + () -> { + BigInteger computedFactorial = factorial.compute(inputNumber); + // logShortMessage(STR."Factorial of \{inputNumber} is + // \{computedFactorial}"); + })); } startTimer(); @@ -79,13 +79,14 @@ private static void runWithTraditionalFactorial(List inputNumbers, Factori } for (Thread thread : threads) { - // thread.join(2000);//Wait for NOT MORE THAN 2 seconds + // thread.join(2000);//Wait for NOT MORE THAN 2 seconds thread.join(); } stopTimer(); } - private static void runParallelFactorialWithExecutor(List inputNumbers, Factorial factorial) { + private static void runParallelFactorialWithExecutor( + List inputNumbers, Factorial factorial) { /* Pros: Provides better control over thread management. Automatically handles thread pooling and task scheduling. @@ -94,18 +95,18 @@ private static void runParallelFactorialWithExecutor(List inputNumbers, Fa */ Callable task = null; List> futures; - try (ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())) { + try (ExecutorService executor = + Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())) { futures = new ArrayList<>(); for (long inputNumber : inputNumbers) { futures.add(executor.submit(() -> factorial.compute(inputNumber))); } - List results = new ArrayList<>(); startTimer(); for (Future future : futures) { try { - results.add(future.get());//Get is not preferred + results.add(future.get()); // Get is not preferred } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { @@ -116,7 +117,8 @@ private static void runParallelFactorialWithExecutor(List inputNumbers, Fa } } - private static void runParallelFactorialWithVirtualThreads(List inputNumbers, Factorial factorial) throws InterruptedException { + private static void runParallelFactorialWithVirtualThreads( + List inputNumbers, Factorial factorial) throws InterruptedException { /*Pros: More scalable and efficient for I/O-bound tasks. Reduces the overhead of managing many threads. @@ -127,51 +129,58 @@ private static void runParallelFactorialWithVirtualThreads(List inputNumbe ThreadFactory threadFactory = Thread.ofVirtual().name("myThread : ", 0).factory(); List> submitted = new ArrayList<>(); - //try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { + // try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { try (ExecutorService srv = Executors.newThreadPerTaskExecutor(threadFactory)) { for (long inputNumber : inputNumbers) { submitted.add(srv.submit(() -> factorial.compute(inputNumber))); } startTimer(); - List results = submitted.stream() - .map(future -> { - try { - return future.get(); - } catch (Exception e) { - throw new RuntimeException(e); - } - }) - .toList(); + List results = + submitted.stream() + .map( + future -> { + try { + return future.get(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }) + .toList(); stopTimer(); } } private static void runWithCompletableFuture(List inputNumbers, Factorial factorial) { startTimer(); - List> futures = inputNumbers.stream() - .map(inputNumber -> CompletableFuture.supplyAsync(() -> factorial.compute(inputNumber))) - .toList(); - - List results = futures.stream() - .map(CompletableFuture::join) - .toList(); + List> futures = + inputNumbers.stream() + .map( + inputNumber -> + CompletableFuture.supplyAsync( + () -> factorial.compute(inputNumber))) + .toList(); + + List results = futures.stream().map(CompletableFuture::join).toList(); stopTimer(); } - private static void runWithCountDownLatch(List inputNumbers, Factorial factorial) throws InterruptedException { + private static void runWithCountDownLatch(List inputNumbers, Factorial factorial) + throws InterruptedException { CountDownLatch latch = new CountDownLatch(inputNumbers.size()); for (long inputNumber : inputNumbers) { - new Thread(() -> { - try { - factorial.compute(inputNumber); - } finally { - latch.countDown(); - } - }).start(); + new Thread( + () -> { + try { + factorial.compute(inputNumber); + } finally { + latch.countDown(); + } + }) + .start(); } startTimer(); latch.await(); stopTimer(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/ThreadLifeCycleAdvanced.java b/src/main/java/nitin/multithreading/ThreadLifeCycleAdvanced.java index 7c07c977..970536d3 100644 --- a/src/main/java/nitin/multithreading/ThreadLifeCycleAdvanced.java +++ b/src/main/java/nitin/multithreading/ThreadLifeCycleAdvanced.java @@ -37,7 +37,10 @@ public void run() { if (i % 2 == 0) { log(Thread.currentThread().getName() + " - Yielding"); Thread.yield(); - log(Thread.currentThread().getName() + " - After yield, state: " + Thread.currentThread().getState()); + log( + Thread.currentThread().getName() + + " - After yield, state: " + + Thread.currentThread().getState()); } } } @@ -80,4 +83,4 @@ public void run() { private static void log(String message) { System.out.println(message); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/ThreadLifecycle.java b/src/main/java/nitin/multithreading/ThreadLifecycle.java index 40fa8282..d0e27572 100644 --- a/src/main/java/nitin/multithreading/ThreadLifecycle.java +++ b/src/main/java/nitin/multithreading/ThreadLifecycle.java @@ -11,13 +11,15 @@ public static void main(String[] args) { System.out.println("State: " + thread.getState()); // RUNNABLE try { - // If main thread doesn't wait long enough, to allow runnable tasks to finish, the main thread will wait + // If main thread doesn't wait long enough, to allow runnable tasks to finish, the main + // thread will wait Thread.sleep(10); // Main thread sleeps to allow RunnableTask to execute\ - //Thread.sleep(1000); //Main thread sleeps to allow RunnableTask to execute, TERMINATED + // Thread.sleep(1000); //Main thread sleeps to allow RunnableTask to execute, TERMINATED } catch (InterruptedException e) { e.printStackTrace(); } - System.out.println("State: " + thread.getState()); // TIMED_WAITING or TERMINATED, depending on timing + System.out.println( + "State: " + thread.getState()); // TIMED_WAITING or TERMINATED, depending on timing } } diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T0ThreadExecutionOrder.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T0ThreadExecutionOrder.java index 390fdab4..96279e1c 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T0ThreadExecutionOrder.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T0ThreadExecutionOrder.java @@ -1,12 +1,11 @@ package nitin.multithreading.aBasics.aPlatformThreads; -import com.utilities.MultiThreadUtility; - import static com.utilities.MultiThreadUtility.logMessage; public class T0ThreadExecutionOrder { public static void main(String[] args) { - //By default, the platform threads are NON-DAEMON Threads, unless it's explicitly marked daemon. + // By default, the platform threads are NON-DAEMON Threads, unless it's explicitly marked + // daemon. Thread thread1 = new Thread(() -> logMessage("1: I'm going for a walk")); Thread thread2 = new Thread(() -> logMessage("2: I'm going to swim")); diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T1ThreadRunsParentDies.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T1ThreadRunsParentDies.java index cd5d02df..67dd75cd 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T1ThreadRunsParentDies.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T1ThreadRunsParentDies.java @@ -5,23 +5,28 @@ /** * Created by Nitin Chaurasia on 11/30/15 at 10:22 PM. * - * Demonstration that a Child Thread continues even if there is an exception in the Main Thread + *

Demonstration that a Child Thread continues even if there is an exception in the Main Thread */ -public class T1ThreadRunsParentDies {// by overriding run method +public class T1ThreadRunsParentDies { // by overriding run method static final int MAX = 50; - //By default, the platform threads are NON-DAEMON Threads, unless its explicitly marked daemon. - // If any non-daemon thread is running, the JVM WILL NOT shut it down even if the main thread has terminated. + // By default, the platform threads are NON-DAEMON Threads, unless its explicitly marked daemon. + // If any non-daemon thread is running, the JVM WILL NOT shut it down even if the main thread + // has terminated. public static void main(String[] args) throws InterruptedException { - //Starting the Thread - //By default, the platform threads are NON-DAEMON Threads, unless its explicitly marked daemon. + // Starting the Thread + // By default, the platform threads are NON-DAEMON Threads, unless its explicitly marked + // daemon. Thread thread = new Thread(() -> task(), "child"); - thread.setDaemon(false);//false=non-daemon, runs the child thread, even if the parent dies. if set true, the child dies as soon as parent dies + thread.setDaemon( + false); // false=non-daemon, runs the child thread, even if the parent dies. if set + // true, the child dies as soon as parent dies thread.start(); - //Deliberately putting and exception so that mainThread stops + // Deliberately putting and exception so that mainThread stops int test = 10 / 0; - // Runtime Stack will be destroyed (for the main thread) as there is no exception handling code + // Runtime Stack will be destroyed (for the main thread) as there is no exception handling + // code thread.join(); } diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByExtending.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByExtending.java index 0cab22b7..8ed722e0 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByExtending.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByExtending.java @@ -2,36 +2,33 @@ /** * Created by Nitin Chaurasia on 12/2/15 at 9:29 PM. - *

- * Difference between t.start() and t.run() - * t.start calls run() from within. if t.run is executed, - * run method will execute normally. - *

- * ALSO. Since by extending, we are limiting to extending only one class. - * NO CHANCE OF EXTENDING ANY OTHER CLASS!! - * We cannot extend any other class. Thus implementing Runnable Interface - * is preferred over this approach. + * + *

Difference between t.start() and t.run() t.start calls run() from within. if t.run is + * executed, run method will execute normally. + * + *

ALSO. Since by extending, we are limiting to extending only one class. NO CHANCE OF EXTENDING + * ANY OTHER CLASS!! We cannot extend any other class. Thus implementing Runnable Interface is + * preferred over this approach. */ public class T2ThreadByExtending { public static void main(String[] args) { - //Instantiate the Thread + // Instantiate the Thread ThreadDemo t = new ThreadDemo(); // t.run() will be like normal method call. t.run(); // normal function call, thus run() will execute first // t.start will internally call run method. - t.start(); //Make the thread run, Order of execution of threads, not guaranteed + t.start(); // Make the thread run, Order of execution of threads, not guaranteed - //DO NOT RESTART THE THREAD AGAIN - t.start();// Throws IllegalThreadStateException + // DO NOT RESTART THE THREAD AGAIN + t.start(); // Throws IllegalThreadStateException // But Child thread continues execution // Calling the Overloaded run() // Acts like a normal method call t.run(25); - for (int i = 0; i < 100; i++) { System.out.println("Main Thread: " + i); } @@ -50,11 +47,10 @@ public void run() { } } - //OverLoading of Run is Possible, but start() will call run() without arguments - //Overloaded run method will behave like a normal method + // OverLoading of Run is Possible, but start() will call run() without arguments + // Overloaded run method will behave like a normal method public void run(int i) { System.out.println("From Overloaded Run" + i); } } - diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByOverridingStart.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByOverridingStart.java index bc612314..57f86f85 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByOverridingStart.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T2ThreadByOverridingStart.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.aPlatformThreads; -/** - * Created by Nitin Chaurasia on 12/2/15 at 10:08 PM. - */ +/** Created by Nitin Chaurasia on 12/2/15 at 10:08 PM. */ public class T2ThreadByOverridingStart { public static void main(String[] args) { MyThread t = new MyThread(); diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3SleepDemo.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3SleepDemo.java index 60bbb27a..8f9149c9 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3SleepDemo.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3SleepDemo.java @@ -2,15 +2,15 @@ /** * Created by Nitin Chaurasia on 12/3/15 at 12:28 AM. - *

- * To just Pause + * + *

To just Pause */ public class T3SleepDemo { public static void main(String[] args) throws InterruptedException { System.out.println("Line 1"); - //Sleep needs try catch or exception handling - Thread.sleep(1000);// 1 sec, 1000 ms + // Sleep needs try catch or exception handling + Thread.sleep(1000); // 1 sec, 1000 ms System.out.println("Line 2"); Thread.sleep(2000); diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnable.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnable.java index 5513ea59..25d00ba7 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnable.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnable.java @@ -2,10 +2,10 @@ /** * Created by Nitin Chaurasia on 12/2/15 at 10:30 PM. - *

- * This Method is Preferred to DEFINE A THREAD - *

- * We can extend other class while Implementing Runnable Interface + * + *

This Method is Preferred to DEFINE A THREAD + * + *

We can extend other class while Implementing Runnable Interface */ public class T3ThreadByRunnable { public static void main(String[] args) { @@ -17,14 +17,13 @@ public static void main(String[] args) { thread.start(); - //Normal Execution of main + // Normal Execution of main for (int i = 0; i < 100; i++) { System.out.println("From Main: " + i); } } } - class ThreadByRunnableDemo implements Runnable { @Override public void run() { diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnableFluent.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnableFluent.java index 3881cfc1..7b0780ef 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnableFluent.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T3ThreadByRunnableFluent.java @@ -3,19 +3,16 @@ import static com.utilities.MultiThreadUtility.logShortMessage; public class T3ThreadByRunnableFluent { - + public static void main(String[] args) throws InterruptedException { logShortMessage("Starting Main Thread .."); // start a daemon thread using Fluent API Runnable r = new ThreadByRunnable(); - Thread thread = Thread.ofPlatform() - .name("Simple") - .daemon(true) - .start(r); - - thread.join();//Forcing the main thread to stop for the child thread + Thread thread = Thread.ofPlatform().name("Simple").daemon(true).start(r); + + thread.join(); // Forcing the main thread to stop for the child thread logShortMessage("Ending Main Thread .."); } diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T4CreateByLambda.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T4CreateByLambda.java index f8527005..c1bbaa7f 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T4CreateByLambda.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T4CreateByLambda.java @@ -3,19 +3,16 @@ import static com.utilities.MultiThreadUtility.logShortMessage; public class T4CreateByLambda { - + public static void main(String[] args) throws InterruptedException { logShortMessage("Starting Main Thread .."); - Thread thread = new Thread(() -> task(12,24));//Invoking Runnable Lambda + Thread thread = new Thread(() -> task(12, 24)); // Invoking Runnable Lambda thread.join(); logShortMessage("Ending Main Thread .."); - } private static void task(int a, int b) { T5CreateByMethodReference.doSomething(); } - } - diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5CreateByMethodReference.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5CreateByMethodReference.java index 7b4451a4..e217d96f 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5CreateByMethodReference.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5CreateByMethodReference.java @@ -1,13 +1,11 @@ package nitin.multithreading.aBasics.aPlatformThreads; -import nitin.exceptionHandling.customizedExceptions.BusinessException; +import static com.utilities.MultiThreadUtility.logShortMessage; import java.util.concurrent.TimeUnit; -import static com.utilities.MultiThreadUtility.logShortMessage; - public class T5CreateByMethodReference { - + public static void main(String[] args) { logShortMessage("Starting Main Thread .."); @@ -15,7 +13,7 @@ public static void main(String[] args) { thr.start(); logShortMessage("Ending Main Thread .."); } - + public static void doSomething() { logShortMessage("Starting Simple Thread"); @@ -27,4 +25,4 @@ public static void doSomething() { logShortMessage("Ending Simple Thread"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5NameCustomization.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5NameCustomization.java index 75eabed2..8a8464eb 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5NameCustomization.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T5NameCustomization.java @@ -1,37 +1,31 @@ package nitin.multithreading.aBasics.aPlatformThreads; -/** - * Created by Nitin Chaurasia on 12/2/15 at 10:55 PM. - */ +/** Created by Nitin Chaurasia on 12/2/15 at 10:55 PM. */ public class T5NameCustomization { public static void main(String[] args) { Thread t = Thread.currentThread(); - //There is Always a main Thread - System.out.println(t);// Main Thread + // There is Always a main Thread + System.out.println(t); // Main Thread /* Thread[Nitin,5,main] * Thread Name, PRIORITY = 5, by Default for main, Method executing the thread * */ - - //Name Customization + // Name Customization Thread.currentThread().setName("Nitin"); System.out.println(t); - //Individual Tupples + // Individual Tupples System.out.println(t.getName()); System.out.println(t.getId()); System.out.println(t.getPriority()); - //Check the State of the Thread. + // Check the State of the Thread. System.out.println(t.getState()); - //Variables + // Variables System.out.println(Thread.MAX_PRIORITY); System.out.println(Thread.MIN_PRIORITY); System.out.println(Thread.NORM_PRIORITY); - } } - - diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T6ThreadPriority.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T6ThreadPriority.java index 72e85068..01aa0709 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T6ThreadPriority.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T6ThreadPriority.java @@ -1,17 +1,13 @@ package nitin.multithreading.aBasics.aPlatformThreads; -/** - * Created by Nitin Chaurasia on 12/2/15 at 11:03 PM. - */ +/** Created by Nitin Chaurasia on 12/2/15 at 11:03 PM. */ public class T6ThreadPriority { /** * Default Priority for main is 5. - *

- * All Child Threads inheriting from the parent has same priority - * With Same Priority, un-deterministic order - * Priority Varies from 1 to 10 (10 being the most) + * + *

All Child Threads inheriting from the parent has same priority With Same Priority, + * un-deterministic order Priority Varies from 1 to 10 (10 being the most) */ - public static void main(String[] args) { ThreadByRunnable tpd = new ThreadByRunnable(); @@ -23,9 +19,9 @@ public static void main(String[] args) { BUT After child starts executing, Main may also execute */ // Child has more Priority than Parent - //t.setPriority(6); + // t.setPriority(6); - t.setPriority(10);// ?? UNKNOWN BEHAVIOUR + t.setPriority(10); // ?? UNKNOWN BEHAVIOUR t.start(); // Normal Main execution diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T7AnonymousThreadCall.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T7AnonymousThreadCall.java index 4f1d78b6..e5053b01 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T7AnonymousThreadCall.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/T7AnonymousThreadCall.java @@ -2,34 +2,39 @@ /** * Created by Nitin Chaurasia on 12/5/15 at 10:01 PM. - *

- * Calling the thread using the Anonymous Inner Class + * + *

Calling the thread using the Anonymous Inner Class */ public class T7AnonymousThreadCall { public static void main(String[] args) { - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - for (int i = 0; i < 500; i++) { - System.out.println("From Thread 1: " + Thread.currentThread() + " " + i); - } - } - }); + Thread t1 = + new Thread( + new Runnable() { + @Override + public void run() { + for (int i = 0; i < 500; i++) { + System.out.println( + "From Thread 1: " + Thread.currentThread() + " " + i); + } + } + }); - - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - for (int i = 0; i < 500; i++) { - System.out.println("From Thread 2: " + Thread.currentThread() + " " + i); - } - } - }); + Thread t2 = + new Thread( + new Runnable() { + @Override + public void run() { + for (int i = 0; i < 500; i++) { + System.out.println( + "From Thread 2: " + Thread.currentThread() + " " + i); + } + } + }); t1.start(); t2.start(); - //The Main function continues + // The Main function continues for (int i = 0; i < 5; i++) { System.out.println("From Main: " + Thread.currentThread() + " " + i); } diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByExtending.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByExtending.java index 91043561..351b915f 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByExtending.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByExtending.java @@ -1,11 +1,8 @@ package nitin.multithreading.aBasics.aPlatformThreads; -/** - * Created by Nitin Chaurasia on 12/2/15 at 11:53 PM. - */ +/** Created by Nitin Chaurasia on 12/2/15 at 11:53 PM. */ public class ThreadByExtending extends Thread { - // Thread Scheduler Decides which thread runs First // Undeterministic Response @Override diff --git a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByRunnable.java b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByRunnable.java index 5090b43b..13bce191 100644 --- a/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByRunnable.java +++ b/src/main/java/nitin/multithreading/aBasics/aPlatformThreads/ThreadByRunnable.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.aPlatformThreads; -/** - * Created by Nitin Chaurasia on 12/2/15 at 11:44 PM. - */ +/** Created by Nitin Chaurasia on 12/2/15 at 11:44 PM. */ public class ThreadByRunnable implements Runnable { @Override public void run() { diff --git a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/MyThread.java b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/MyThread.java index cdfeb7d9..ebbf769c 100644 --- a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/MyThread.java +++ b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/MyThread.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.bThreadGroups; -/** - * Created by nitin.chaurasia on 12/25/2016. - */ +/** Created by nitin.chaurasia on 12/25/2016. */ public class MyThread extends Thread { MyThread(ThreadGroup g, String name) { super(g, name); @@ -13,7 +11,7 @@ public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { - //Swallowing the Exception + // Swallowing the Exception } } } diff --git a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/aBasicsThreadGroups.java b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/aBasicsThreadGroups.java index 735b04c8..152e73dd 100644 --- a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/aBasicsThreadGroups.java +++ b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/aBasicsThreadGroups.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.bThreadGroups; -/** - * Created by nitin.chaurasia on 12/25/2016. - */ +/** Created by nitin.chaurasia on 12/25/2016. */ public class aBasicsThreadGroups { public static void main(String[] args) { @@ -10,13 +8,17 @@ public static void main(String[] args) { // Get the Default Thread Grp name System.out.println(Thread.currentThread().getThreadGroup()); - //Get the Name of the Parent of the Default ThreadGroup - System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());//main, def. MAX_PRIORITY = 5 + // Get the Name of the Parent of the Default ThreadGroup + System.out.println( + Thread.currentThread() + .getThreadGroup() + .getParent() + .getName()); // main, def. MAX_PRIORITY = 5 ThreadGroup g1 = new ThreadGroup("First thread"); - System.out.println(g1.getParent().getName());//main + System.out.println(g1.getParent().getName()); // main ThreadGroup g2 = new ThreadGroup(g1, "Second thread"); - System.out.println(g2.getParent().getName());//First Thread + System.out.println(g2.getParent().getName()); // First Thread } } diff --git a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/bThreadGroupPriorities.java b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/bThreadGroupPriorities.java index 13a619aa..1d9d2d26 100644 --- a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/bThreadGroupPriorities.java +++ b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/bThreadGroupPriorities.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.bThreadGroups; -/** - * Created by nitin.chaurasia on 12/25/2016. - */ +/** Created by nitin.chaurasia on 12/25/2016. */ public class bThreadGroupPriorities { public static void main(String[] args) { ThreadGroup group = new ThreadGroup("Nitin"); @@ -13,7 +11,7 @@ public static void main(String[] args) { System.out.println("Default Priorities"); System.out.println(t1.getPriority()); System.out.println(t2.getPriority()); - //Threads created after this will have priorities 3 + // Threads created after this will have priorities 3 group.setMaxPriority(3); Thread t3 = new Thread(group, "Third thread"); @@ -25,6 +23,5 @@ public static void main(String[] args) { // prints info about thread grp to the console group.list(); - } } diff --git a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/cThreadGroupMethods.java b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/cThreadGroupMethods.java index 8587781d..ee09cc87 100644 --- a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/cThreadGroupMethods.java +++ b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/cThreadGroupMethods.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.bThreadGroups; -/** - * Created by nitin.chaurasia on 12/25/2016. - */ +/** Created by nitin.chaurasia on 12/25/2016. */ public class cThreadGroupMethods { public static void main(String[] args) { ThreadGroup pg = new ThreadGroup("Parent Group"); @@ -11,22 +9,23 @@ public static void main(String[] args) { MyThread t1 = new MyThread(pg, "ChildThread1"); MyThread t2 = new MyThread(pg, "ChildThread2"); - //Start the Thread + // Start the Thread t1.start(); t2.start(); - System.out.println(pg.activeCount());//2 - System.out.println(pg.activeGroupCount());//1 + System.out.println(pg.activeCount()); // 2 + System.out.println(pg.activeGroupCount()); // 1 pg.list(); - try { // After 10 secs, both active threads will be gone as 5000 is the sleep time for MyReentrantDemoThread - Thread.sleep(1000);// have to use try catch + try { // After 10 secs, both active threads will be gone as 5000 is the sleep time for + // MyReentrantDemoThread + Thread.sleep(1000); // have to use try catch } catch (InterruptedException e) { e.printStackTrace(); } - System.out.println(pg.activeCount());//0 - System.out.println(pg.activeGroupCount());//1 + System.out.println(pg.activeCount()); // 0 + System.out.println(pg.activeGroupCount()); // 1 pg.list(); } diff --git a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/dThreadGroupMethodsEnhanced.java b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/dThreadGroupMethodsEnhanced.java index e9d8b07d..7b40c97a 100644 --- a/src/main/java/nitin/multithreading/aBasics/bThreadGroups/dThreadGroupMethodsEnhanced.java +++ b/src/main/java/nitin/multithreading/aBasics/bThreadGroups/dThreadGroupMethodsEnhanced.java @@ -2,8 +2,8 @@ /** * Created by nitin.chaurasia on 12/25/2016. - *

- * Displaying the System Thread groups MetaData + * + *

Displaying the System Thread groups MetaData */ public class dThreadGroupMethodsEnhanced { public static void main(String[] args) { diff --git a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobCallable.java b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobCallable.java index 5c8181bd..1cea797a 100644 --- a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobCallable.java +++ b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobCallable.java @@ -2,9 +2,7 @@ import java.util.concurrent.Callable; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class PrintJobCallable implements Callable { int num; @@ -14,7 +12,11 @@ public class PrintJobCallable implements Callable { @Override public Object call() throws Exception { - System.out.println(Thread.currentThread().getName() + " is responsible for adding first " + num + " numbers"); + System.out.println( + Thread.currentThread().getName() + + " is responsible for adding first " + + num + + " numbers"); int sum = 0; for (int i = 0; i < num; i++) { diff --git a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobRunnable.java b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobRunnable.java index b54ca719..4f3c070b 100644 --- a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobRunnable.java +++ b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/PrintJobRunnable.java @@ -1,8 +1,6 @@ package nitin.multithreading.aBasics.cThreadPoolsAKAExecutorFW; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class PrintJobRunnable implements Runnable { String name; @@ -13,7 +11,8 @@ public class PrintJobRunnable implements Runnable { @Override public void run() { - System.out.println(name + " ... Job Started By Thread : " + Thread.currentThread().getName()); + System.out.println( + name + " ... Job Started By Thread : " + Thread.currentThread().getName()); try { Thread.sleep(2000); @@ -21,6 +20,7 @@ public void run() { e.printStackTrace(); } - System.out.println(name + " ... Jon Completed by Thread : " + Thread.currentThread().getName()); + System.out.println( + name + " ... Jon Completed by Thread : " + Thread.currentThread().getName()); } } diff --git a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/aExecutorDemo.java b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/aExecutorDemo.java index dd5b6e34..44f6c119 100644 --- a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/aExecutorDemo.java +++ b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/aExecutorDemo.java @@ -3,17 +3,15 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class aExecutorDemo { public static void main(String[] args) { PrintJobRunnable[] jobs = { // Creating runnable array - new PrintJobRunnable("Clarks Summit"), - new PrintJobRunnable("Scranton"), - new PrintJobRunnable("GreenVille"), - new PrintJobRunnable("Cary"), - new PrintJobRunnable("New Jersey") + new PrintJobRunnable("Clarks Summit"), + new PrintJobRunnable("Scranton"), + new PrintJobRunnable("GreenVille"), + new PrintJobRunnable("Cary"), + new PrintJobRunnable("New Jersey") }; ExecutorService service = Executors.newFixedThreadPool(9); diff --git a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/bCallableDemo.java b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/bCallableDemo.java index b3f96830..367e1d8e 100644 --- a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/bCallableDemo.java +++ b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/bCallableDemo.java @@ -5,23 +5,22 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class bCallableDemo { public static void main(String[] args) { PrintJobCallable[] jobs = { - new PrintJobCallable(10), - new PrintJobCallable(20), - new PrintJobCallable(30), - new PrintJobCallable(40), - new PrintJobCallable(50), - new PrintJobCallable(60)}; + new PrintJobCallable(10), + new PrintJobCallable(20), + new PrintJobCallable(30), + new PrintJobCallable(40), + new PrintJobCallable(50), + new PrintJobCallable(60) + }; ExecutorService service = Executors.newFixedThreadPool(3); for (PrintJobCallable job : jobs) { - Future f = service.submit(job);//To hold the return + Future f = service.submit(job); // To hold the return try { System.out.println("Return Value is : " + f.get()); } catch (InterruptedException e) { diff --git a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/threadCreationExecutorService/ES1SingleThreadExecutor.java b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/threadCreationExecutorService/ES1SingleThreadExecutor.java index a50c0bb4..b03047f4 100644 --- a/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/threadCreationExecutorService/ES1SingleThreadExecutor.java +++ b/src/main/java/nitin/multithreading/aBasics/cThreadPoolsAKAExecutorFW/threadCreationExecutorService/ES1SingleThreadExecutor.java @@ -1,16 +1,16 @@ package nitin.multithreading.aBasics.cThreadPoolsAKAExecutorFW.threadCreationExecutorService; +import static com.utilities.MultiThreadUtility.logShortMessage; + import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import static com.utilities.MultiThreadUtility.logShortMessage; - /** - * Created by Nitin C on 3/3/2016. - * Concurrency API includes the Executors factory class that can - * be used to create instances of the ExecutorServiceObject - *

- * Tasks are guaranteed to be executed in the order they are submitted for a single-threaded application + * Created by Nitin C on 3/3/2016. Concurrency API includes the Executors factory class that can be + * used to create instances of the ExecutorServiceObject + * + *

Tasks are guaranteed to be executed in the order they are submitted for a single-threaded + * application */ public class ES1SingleThreadExecutor { public static void main(String[] args) { @@ -19,21 +19,22 @@ public static void main(String[] args) { service = Executors.newSingleThreadExecutor(); System.out.println("BEGIN"); - //execute needs runnable + // execute needs runnable // fire and forget method service.execute(() -> System.out.println("One little lambda function for the thread")); - service.execute(() -> { - for (int i = 0; i < 10; i++) { - logShortMessage("Printing : " + i); - } - }); + service.execute( + () -> { + for (int i = 0; i < 10; i++) { + logShortMessage("Printing : " + i); + } + }); System.out.println("END"); } finally { - // A thread executor creates anon-daemon thread on the first task taht is executed, so failing to call + // A thread executor creates anon-daemon thread on the first task taht is executed, so + // failing to call // shutdown() will result in your application never terminating // shutdownNow() attempts to stop all running thread - if (service != null) - service.shutdown(); + if (service != null) service.shutdown(); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T1YieldDemo.java b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T1YieldDemo.java index 3d04fc31..ec8c0ee5 100644 --- a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T1YieldDemo.java +++ b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T1YieldDemo.java @@ -6,14 +6,12 @@ /** * Created by Nitin Chaurasia on 12/2/15 at 11:25 PM. - *

- * Pause current executing threads, giving chance to remaining - * waiting Threads OF SAME PRIORITY. - *

- * If no waiting Threads, or all threads have lower Priority - * Then Same thread will continue execution. + * + *

Pause current executing threads, giving chance to remaining waiting Threads OF SAME PRIORITY. + * + *

If no waiting Threads, or all threads have lower Priority Then Same thread will continue + * execution. */ - public class T1YieldDemo { public static void main(String[] args) { ThreadByRunnable tr = new ThreadByRunnable(); @@ -25,7 +23,6 @@ public static void main(String[] args) { System.out.println("From Main: " + i); } } - } class ThreadYield implements Runnable { @@ -37,6 +34,3 @@ public void run() { } } } - - - diff --git a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T2JoinDemo.java b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T2JoinDemo.java index 97ca67b7..890e7e7c 100644 --- a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T2JoinDemo.java +++ b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T2JoinDemo.java @@ -2,10 +2,10 @@ /** * Created by Nitin Chaurasia on 12/3/15 at 12:03 AM. - *

- * Wait until the Completion of some other Thread - *

- * Throws interruptedException (handle else compile error) + * + *

Wait until the Completion of some other Thread + * + *

Throws interruptedException (handle else compile error) */ public class T2JoinDemo { public static void main(String[] args) { @@ -35,11 +35,11 @@ class ThreadJoin implements Runnable { public void run() { for (int i = 0; i < 1000; i++) { System.out.println("Child : " + i); -// try { -// /Thread.sleep(200); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } + // try { + // /Thread.sleep(200); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } } } } diff --git a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T3InterruptDemo.java b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T3InterruptDemo.java index d15e7290..d7ea841c 100644 --- a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T3InterruptDemo.java +++ b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T3InterruptDemo.java @@ -2,8 +2,8 @@ /** * Created by Nitin Chaurasia on 12/3/15 at 12:57 AM. - *

- * A Thread Can Interrupt another Sleeping or Waiting Thread + * + *

A Thread Can Interrupt another Sleeping or Waiting Thread */ public class T3InterruptDemo { public static void main(String[] args) { @@ -15,7 +15,7 @@ public static void main(String[] args) { // No impact if target thread is in NOT in sleeping or Waiting state t.interrupt(); - //Normal Main Execution + // Normal Main Execution for (int i = 0; i < 100; i++) { System.out.println("Main: " + i); } @@ -35,4 +35,4 @@ public void run() { } } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T4SleepNWait.java b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T4SleepNWait.java index 26bc8464..f187ac70 100644 --- a/src/main/java/nitin/multithreading/aBasics/executionPrevention/T4SleepNWait.java +++ b/src/main/java/nitin/multithreading/aBasics/executionPrevention/T4SleepNWait.java @@ -1,16 +1,14 @@ package nitin.multithreading.aBasics.executionPrevention; /** - * Created by Nitin Chaurasia on 12/3/15 at 2:11 AM. - * wait() method RELEASE the acquired lock when thread is waiting while - * Thread.sleep() method keeps the lock or monitor - *

- * Also wait should be called from synchronized method or block - * while there is no such requirement for sleep() method. - *

- * Another difference isThread.sleep() method is a static method and applies on current thread, - * while wait() is an instance specific method and only got wake up if some other thread - * calls notify method on same a5object. + * Created by Nitin Chaurasia on 12/3/15 at 2:11 AM. wait() method RELEASE the acquired lock when + * thread is waiting while Thread.sleep() method keeps the lock or monitor + * + *

Also wait should be called from synchronized method or block while there is no such + * requirement for sleep() method. + * + *

Another difference isThread.sleep() method is a static method and applies on current thread, + * while wait() is an instance specific method and only got wake up if some other thread calls + * notify method on same a5object. */ -public class T4SleepNWait { -} +public class T4SleepNWait {} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/A16AnyOf.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/A16AnyOf.java index 951b3585..2412c9f5 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/A16AnyOf.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/A16AnyOf.java @@ -1,30 +1,40 @@ package nitin.multithreading.bFuturesAndCompletableFutures; import com.github.javafaker.Faker; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - import java.util.concurrent.CompletableFuture; - +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A16AnyOf { public static void main(String[] args) { DataFetchService dataFetchService = new DataFetchService(); // Tasks we want to run in parallel - var future1 = CompletableFuture.supplyAsync(() -> dataFetchService.microTask("Harry Potter", 2, true)); - var future2 = CompletableFuture.supplyAsync(() -> dataFetchService.microTask("Ron Weasley", 5, true)); - var future3 = CompletableFuture.supplyAsync(() -> dataFetchService.microTask("Hermione Granger", 6, true)); - var future4 = CompletableFuture.supplyAsync(() -> dataFetchService.microTask(Faker.instance().harryPotter().character(), 1, true)); + var future1 = + CompletableFuture.supplyAsync( + () -> dataFetchService.microTask("Harry Potter", 2, true)); + var future2 = + CompletableFuture.supplyAsync( + () -> dataFetchService.microTask("Ron Weasley", 5, true)); + var future3 = + CompletableFuture.supplyAsync( + () -> dataFetchService.microTask("Hermione Granger", 6, true)); + var future4 = + CompletableFuture.supplyAsync( + () -> + dataFetchService.microTask( + Faker.instance().harryPotter().character(), 1, true)); // Returns a CompletableFuture which completes when any of the 4 futures complete // The remaining tasks are not cancelled CompletableFuture.anyOf(future1, future2, future3, future4) - .thenAccept(result -> { - System.out.println("Handling Accept :: " + result); - }) - .exceptionally(throwable -> { - System.out.println("Handling Failure :: " + throwable); - return null; - }) + .thenAccept( + result -> { + System.out.println("Handling Accept :: " + result); + }) + .exceptionally( + throwable -> { + System.out.println("Handling Failure :: " + throwable); + return null; + }) .join(); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/TestAsync.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/TestAsync.java index 2ab53cb2..84a512eb 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/TestAsync.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/TestAsync.java @@ -6,13 +6,12 @@ public class TestAsync { public static void main(String[] args) { for (int i = 0; i < 100; i++) { asyncMethodWithVoidReturnType(i); - } } @Async public static void asyncMethodWithVoidReturnType(int i) { - System.out.println("Execute method asynchronously. #" + i - + " :: " + Thread.currentThread().getName()); + System.out.println( + "Execute method asynchronously. #" + i + " :: " + Thread.currentThread().getName()); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A0DefiningCompletableFuture.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A0DefiningCompletableFuture.java index 281358d0..4d7a5f09 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A0DefiningCompletableFuture.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A0DefiningCompletableFuture.java @@ -1,29 +1,31 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; +import static com.utilities.MultiThreadUtility.*; import java.util.concurrent.CompletableFuture; - -import static com.utilities.MultiThreadUtility.*; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A0DefiningCompletableFuture { public static void main(String[] args) { DataFetchService dataFetchService = new DataFetchService(); logMessage("From Main Thread"); - CompletableFuture stringCompletableFuture = CompletableFuture.supplyAsync(() -> getData(dataFetchService)); + CompletableFuture stringCompletableFuture = + CompletableFuture.supplyAsync(() -> getData(dataFetchService)); - stringCompletableFuture - .thenAccept(greetings -> logMessage("Message received from supply Async: " + greetings)); + stringCompletableFuture.thenAccept( + greetings -> logMessage("Message received from supply Async: " + greetings)); - delay(1000);//Introducing delays to let the completable future finish without using join or get + delay(1000); // Introducing delays to let the completable future finish without using join + // or get System.out.println("DONE"); - //stringCompletableFuture.get();// wait till Task Future is Completed (No Return data) - delay(1000);// This delay forces the thread from supplier to run prior to ending the program + // stringCompletableFuture.get();// wait till Task Future is Completed (No Return data) + delay(1000); // This delay forces the thread from supplier to run prior to ending the + // program } private static String getData(DataFetchService dataFetchService) { - logMessage("Inside getData : " ); + logMessage("Inside getData : "); return dataFetchService.greetingsService(1000); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A10ASucceedOnTimeOut.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A10ASucceedOnTimeOut.java index 5576e176..159ed05b 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A10ASucceedOnTimeOut.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A10ASucceedOnTimeOut.java @@ -1,16 +1,15 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; +import static com.utilities.MultiThreadUtility.delay; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import static com.utilities.MultiThreadUtility.delay; - public class A10ASucceedOnTimeOut { public static void main(String[] args) { CompletableFuture future = new CompletableFuture<>(); - future - .thenApply(data -> data + 3) + future.thenApply(data -> data + 3) .exceptionally(throwable -> handleExcptionally(throwable)) .thenApply(data -> data * 2) .thenAccept(data -> System.out.println("Result from Future " + data)); @@ -19,15 +18,17 @@ public static void main(String[] args) { delay(1000); - future.completeOnTimeout(5, 1, TimeUnit.SECONDS);//With Java 9 onwards - //does not keep the pipeline in PENDING STATE more than a second. If the values doesnt arrive in a second, - //then resolve it with the default value being passes + future.completeOnTimeout(5, 1, TimeUnit.SECONDS); // With Java 9 onwards + // does not keep the pipeline in PENDING STATE more than a second. If the values doesnt + // arrive in a second, + // then resolve it with the default value being passes delay(2000); - //If there is delay for complete to run more than time out value from completeOnTimeout, then complete on time - //out code will run - future.complete(2);//if this runs, then completeOnTimeout will have no effect + // If there is delay for complete to run more than time out value from completeOnTimeout, + // then complete on time + // out code will run + future.complete(2); // if this runs, then completeOnTimeout will have no effect System.out.println("DONE"); } @@ -38,12 +39,15 @@ private static Integer handleExcptionally(Throwable throwable) { } private static void successOnTimeOut(CompletableFuture future) { - future.completeOnTimeout(5, 1, TimeUnit.SECONDS);//Does not keep the pipeline in PENDING state - //for more than a second. the value doesn't arrive in 1 sec (timeout) then resolve it, via the default value + future.completeOnTimeout( + 5, 1, TimeUnit.SECONDS); // Does not keep the pipeline in PENDING state + // for more than a second. the value doesn't arrive in 1 sec (timeout) then resolve it, via + // the default value } private static void failureOnTimeOut(CompletableFuture future) { - future.orTimeout(1, TimeUnit.SECONDS);//Does not keep the pipeline in PENDING state - //for more than a second. the value doesn't arrive in 1 sec (timeout) then cancel it, and completes it exceptionally with a TimeoutException + future.orTimeout(1, TimeUnit.SECONDS); // Does not keep the pipeline in PENDING state + // for more than a second. the value doesn't arrive in 1 sec (timeout) then cancel it, and + // completes it exceptionally with a TimeoutException } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A11AFailOnTimeOut.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A11AFailOnTimeOut.java index 73bd414c..87820266 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A11AFailOnTimeOut.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A11AFailOnTimeOut.java @@ -1,16 +1,15 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; +import static com.utilities.MultiThreadUtility.delay; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import static com.utilities.MultiThreadUtility.delay; - public class A11AFailOnTimeOut { public static void main(String[] args) { CompletableFuture future = new CompletableFuture<>(); - future - .thenApply(data -> data + 3) + future.thenApply(data -> data + 3) .exceptionally(throwable -> handleExceptionally(throwable)) .thenApply(data -> data * 2) .thenAccept(data -> System.out.println("Result from Future " + data)); @@ -19,8 +18,8 @@ public static void main(String[] args) { delay(1000); - future.orTimeout(1, TimeUnit.SECONDS);//This will blowout if the state is resolved - delay(2000);//Delay between timeout and completion is taking into account + future.orTimeout(1, TimeUnit.SECONDS); // This will blowout if the state is resolved + delay(2000); // Delay between timeout and completion is taking into account future.complete(2); System.out.println("DONE"); diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12Combine.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12Combine.java index f6a5b455..423c44e8 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12Combine.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12Combine.java @@ -2,14 +2,15 @@ import java.util.concurrent.CompletableFuture; -import static com.utilities.MultiThreadUtility.delay; - public class A12Combine { public static void main(String[] args) { - CompletableFuture radiusFuture = CompletableFuture.supplyAsync(() -> 1.0);//Returning a random number Asyncronously + CompletableFuture radiusFuture = + CompletableFuture.supplyAsync(() -> 1.0); // Returning a random number Asyncronously radiusFuture - //.thenApply(radius -> CompletableFuture.supplyAsync(() -> calculateArea(radius)))//Returns a completable future, not the value of it, java.util.concurrent.CompletableFuture@7106e68e[Completed normally] - .thenCompose(radius -> CompletableFuture.supplyAsync(() -> calculateArea(radius))) + // .thenApply(radius -> CompletableFuture.supplyAsync(() -> + // calculateArea(radius)))//Returns a completable future, not the value of it, + // java.util.concurrent.CompletableFuture@7106e68e[Completed normally] + .thenCompose(radius -> CompletableFuture.supplyAsync(() -> calculateArea(radius))) .thenAccept(area -> System.out.println(area)); } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCombine.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCombine.java index 9e39cd23..a3615b24 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCombine.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCombine.java @@ -1,97 +1,126 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; +import static com.utilities.MultiThreadUtility.*; import java.util.concurrent.CompletableFuture; - -import static com.utilities.MultiThreadUtility.*; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A12ThenCombine { static DataFetchService dataFetchService; /** - * Completion stage method - * used to combine Independent Completable Futures - * Takes two arguments - * CompletionStage, BiFunction - * Returns a CompletableFuture + * Completion stage method used to combine Independent Completable Futures Takes two arguments + * CompletionStage, BiFunction Returns a CompletableFuture * * @param args */ public static void main(String[] args) { dataFetchService = new DataFetchService(); - //CompletableFuture future2 = fullNameService(); - //CompletableFuture future3 = fullNameWithGreetingService(); + // CompletableFuture future2 = fullNameService(); + // CompletableFuture future3 = fullNameWithGreetingService(); CompletableFuture future4 = fullNameWithGreetingAndGoodByesService(); - //future2.thenAccept(data -> System.out.println(data)).join(); - //future3.thenAccept(data -> System.out.println(data)).join(); + // future2.thenAccept(data -> System.out.println(data)).join(); + // future3.thenAccept(data -> System.out.println(data)).join(); System.out.println("--------------------------"); future4.thenAccept(data -> System.out.println(data)).join(); System.out.println("--------------------------"); } - //Combining Two Completable Futures + // Combining Two Completable Futures public static CompletableFuture fullNameService() { - //All are independent Tasks - CompletableFuture firstName = CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); - CompletableFuture lastName = CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); + // All are independent Tasks + CompletableFuture firstName = + CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); + CompletableFuture lastName = + CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); CompletableFuture fullNameCompletableFuture = firstName - .thenCombine(lastName, (fn, ln) -> getAppendedString(fn, ln))//Completion stage is the last name service. + .thenCombine( + lastName, + (fn, ln) -> + getAppendedString( + fn, + ln)) // Completion stage is the last name service. .thenApply(completeName -> completeName.toUpperCase()); return fullNameCompletableFuture; } - //Three Completable Futures + // Three Completable Futures public static CompletableFuture fullNameWithGreetingService() { - CompletableFuture firstName = CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); - CompletableFuture lastName = CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); - CompletableFuture greetings = CompletableFuture.supplyAsync(() -> { - return "Hello!!"; - }); + CompletableFuture firstName = + CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); + CompletableFuture lastName = + CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); + CompletableFuture greetings = + CompletableFuture.supplyAsync( + () -> { + return "Hello!!"; + }); CompletableFuture fullNameCompletableFuture = - greetings.thenCombine(firstName, (previous, current) -> { - return previous + " " + current; - }) - .thenCombine(lastName, (fn, ln) -> { - return fn + " " + ln; - })//Completion stage is the last name service. + greetings + .thenCombine( + firstName, + (previous, current) -> { + return previous + " " + current; + }) + .thenCombine( + lastName, + (fn, ln) -> { + return fn + " " + ln; + }) // Completion stage is the last name service. .thenApply(completeName -> completeName.toUpperCase()); return fullNameCompletableFuture; } - //Four Completable Futures + // Four Completable Futures public static CompletableFuture fullNameWithGreetingAndGoodByesService() { - CompletableFuture firstName = CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); - CompletableFuture lastName = CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); - - CompletableFuture intro = CompletableFuture.supplyAsync(() -> { - delay(1000); - logMessage("From intro Service"); - return "Hello!!"; - }); - - //Longest Running task decides the end of the completable Futures - CompletableFuture extro = CompletableFuture.supplyAsync(() -> { - delay(1100); - logShortMessage("From extro Service"); - return ", Thank You!!"; - }); + CompletableFuture firstName = + CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); + CompletableFuture lastName = + CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); + + CompletableFuture intro = + CompletableFuture.supplyAsync( + () -> { + delay(1000); + logMessage("From intro Service"); + return "Hello!!"; + }); + + // Longest Running task decides the end of the completable Futures + CompletableFuture extro = + CompletableFuture.supplyAsync( + () -> { + delay(1100); + logShortMessage("From extro Service"); + return ", Thank You!!"; + }); CompletableFuture fullNameCompletableFuture = - intro.thenCombine(firstName, (previous, current) -> getAppendedString(previous, current)) //previous is greeting, current is first name - .thenCombine(lastName, (fn, ln) -> getAppendedString(fn, ln))//Completion stage is the last name service. + intro.thenCombine( + firstName, + (previous, current) -> + getAppendedString( + previous, + current)) // previous is greeting, current is first + // name + .thenCombine( + lastName, + (fn, ln) -> + getAppendedString( + fn, + ln)) // Completion stage is the last name service. .thenCombine(extro, (prev, curr) -> prev + curr) .thenApply(completeName -> completeName.toUpperCase()); diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCompose.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCompose.java index 523fe00a..3caf950d 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCompose.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A12ThenCompose.java @@ -1,13 +1,12 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; import com.entity.dto.VehicleTransformed; -import lombok.NoArgsConstructor; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.functions.DataTransformationFunctions; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; +import lombok.NoArgsConstructor; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.functions.DataTransformationFunctions; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; @NoArgsConstructor public class A12ThenCompose { @@ -17,13 +16,11 @@ public A12ThenCompose(DataFetchService dataFetchService) { A12ThenCompose.dataFetchService = dataFetchService; } - //CHECK TEST CASES AS WELL + // CHECK TEST CASES AS WELL /** - * Completion Stage method - * Transform data from one form to another - * Input is Function functional interface - * Deals with methods that return completableFuture + * Completion Stage method Transform data from one form to another Input is Function functional + * interface Deals with methods that return completableFuture * * @param args */ @@ -31,11 +28,10 @@ public static void main(String[] args) { dataFetchService = new DataFetchService(); CompletableFuture greetingsComposeFuture = getGreetings_compose(); - greetingsComposeFuture - .thenAccept(str -> System.out.println(str)) - .join(); + greetingsComposeFuture.thenAccept(str -> System.out.println(str)).join(); - CompletableFuture vehicleTransformedCompletableFuture = getHeighestMileageCar(); + CompletableFuture vehicleTransformedCompletableFuture = + getHeighestMileageCar(); vehicleTransformedCompletableFuture .thenAccept(data -> System.out.println(data.toString())) .join(); @@ -44,24 +40,35 @@ public static void main(String[] args) { public static CompletableFuture getHeighestMileageCar() { return CompletableFuture.supplyAsync(() -> vehicleCompletableFuture()) - .thenCompose((previousVehicleFuture) -> - dataFetchService.findVehicleWithGreatMileage(previousVehicleFuture)); + .thenCompose( + (previousVehicleFuture) -> + dataFetchService.findVehicleWithGreatMileage( + previousVehicleFuture)); } public static CompletableFuture getGreetings_compose() { - //Fetch the name from the first name serviceTask and then feed the output to the futureName service for greeting + // Fetch the name from the first name serviceTask and then feed the output to the futureName + // service for greeting return CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)) - .thenCompose((firstNameFromPrevious) -> dataFetchService.futureName(firstNameFromPrevious)); + .thenCompose( + (firstNameFromPrevious) -> + dataFetchService.futureName(firstNameFromPrevious)); } private static List vehicleCompletableFuture() { - CompletableFuture> x = CompletableFuture - .supplyAsync(() -> dataFetchService.fetchVehicles(2)) - .thenApply(vehicleList -> vehicleList.stream() - .map(vehicle -> DataTransformationFunctions.vehicleFunction.apply(vehicle)) - .collect(Collectors.toList())); + CompletableFuture> x = + CompletableFuture.supplyAsync(() -> dataFetchService.fetchVehicles(2)) + .thenApply( + vehicleList -> + vehicleList.stream() + .map( + vehicle -> + DataTransformationFunctions + .vehicleFunction + .apply(vehicle)) + .collect(Collectors.toList())); return x.join(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A13AllOf.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A13AllOf.java index 0bda77fd..b8122310 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A13AllOf.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A13AllOf.java @@ -1,39 +1,46 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; +import static com.utilities.PerformanceUtility.*; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; - -import static com.utilities.PerformanceUtility.*; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A13AllOf { public static void main(String[] args) { DataFetchService dataFetchService = new DataFetchService(); startTimer(); - CompletableFuture helloFuture = CompletableFuture.supplyAsync(() -> dataFetchService.greetingsService(3000)); - CompletableFuture firstNameFuture = CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(2000)); - CompletableFuture lastNameFuture = CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); + CompletableFuture helloFuture = + CompletableFuture.supplyAsync(() -> dataFetchService.greetingsService(3000)); + CompletableFuture firstNameFuture = + CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(2000)); + CompletableFuture lastNameFuture = + CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); CompletableFuture exclaim = CompletableFuture.supplyAsync(() -> "!!"); stopTimer(); resetTimer(); - List> completableFutures = List.of(helloFuture, firstNameFuture, lastNameFuture, exclaim); - CompletableFuture resultantCf = CompletableFuture.allOf(completableFutures - .toArray(new CompletableFuture[completableFutures.size()])); + List> completableFutures = + List.of(helloFuture, firstNameFuture, lastNameFuture, exclaim); + CompletableFuture resultantCf = + CompletableFuture.allOf( + completableFutures.toArray( + new CompletableFuture[completableFutures.size()])); - CompletableFuture> allFutureResults = resultantCf.thenApply(t -> completableFutures - .stream() - .map(CompletableFuture::join) - .collect(Collectors.toList())); + CompletableFuture> allFutureResults = + resultantCf.thenApply( + t -> + completableFutures.stream() + .map(CompletableFuture::join) + .collect(Collectors.toList())); try { startTimer(); System.out.println("Before Get"); - List resultString = allFutureResults.get();//Actual Execution of all methods + List resultString = allFutureResults.get(); // Actual Execution of all methods System.out.println("After Get"); stopTimer(); diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A14AllOfHeterogenious.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A14AllOfHeterogenious.java index 5a2abca8..7c3c1e29 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A14AllOfHeterogenious.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A14AllOfHeterogenious.java @@ -4,7 +4,6 @@ import com.entity.Vehicle; import com.utilities.InternetUtilities; import com.utilities.RestGETReadUtility; - import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -15,17 +14,25 @@ public class A14AllOfHeterogenious { public static void main(String[] args) { InternetUtilities internetUtilities = new InternetUtilities(); - CompletableFuture> beerCompletableFuture = CompletableFuture.supplyAsync(() -> InternetUtilities.getBeers(2)); - CompletableFuture> vehicleCompletableFuture = CompletableFuture.supplyAsync(() -> RestGETReadUtility.getRandomVehicles(1)); + CompletableFuture> beerCompletableFuture = + CompletableFuture.supplyAsync(() -> InternetUtilities.getBeers(2)); + CompletableFuture> vehicleCompletableFuture = + CompletableFuture.supplyAsync(() -> RestGETReadUtility.getRandomVehicles(1)); - List completableFutures = Arrays.asList(beerCompletableFuture, vehicleCompletableFuture); + List completableFutures = + Arrays.asList(beerCompletableFuture, vehicleCompletableFuture); - CompletableFuture resultantCf = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])); + CompletableFuture resultantCf = + CompletableFuture.allOf( + completableFutures.toArray( + new CompletableFuture[completableFutures.size()])); - CompletableFuture allFutureResults = resultantCf.thenApply(t -> completableFutures - .stream()//Need a list of completableFutures - .map(CompletableFuture::join) - .collect(Collectors.toList())); + CompletableFuture allFutureResults = + resultantCf.thenApply( + t -> + completableFutures.stream() // Need a list of completableFutures + .map(CompletableFuture::join) + .collect(Collectors.toList())); try { System.out.println("Result - " + allFutureResults.get()); @@ -36,12 +43,12 @@ public static void main(String[] args) { } } - private static String getString(CompletableFuture> beerCompletableFuture, CompletableFuture> vehicleCompletableFuture) { - String beer = beerCompletableFuture - .join().stream().findFirst().get().getAlcohol(); + private static String getString( + CompletableFuture> beerCompletableFuture, + CompletableFuture> vehicleCompletableFuture) { + String beer = beerCompletableFuture.join().stream().findFirst().get().getAlcohol(); - vehicleCompletableFuture.join() - .get(0); + vehicleCompletableFuture.join().get(0); /*StringBuilder builder = new StringBuilder(); String ret = builder diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A15AllOfWithWhenComplete.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A15AllOfWithWhenComplete.java index 68517482..5bdca3eb 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A15AllOfWithWhenComplete.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A15AllOfWithWhenComplete.java @@ -1,10 +1,7 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - -import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.function.Supplier; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A15AllOfWithWhenComplete { static DataFetchService dataFetchService = new DataFetchService(); @@ -21,21 +18,30 @@ public static void main(String[] args) { // Returns a CompletableFuture which completes when all 4 futures are completed // Use whenComplete to handle completion CompletableFuture.allOf(future1, future2, future3, future4) - .whenComplete((Void, throwable) -> { - if (throwable == null) { - try { - // Retrieve results from all future - // Combine results - String combinedResult = STR."\{future1.get()} \{future2.get()} \{future3.get()} \{future4.get()}"; - System.out.println("Combined result: " + combinedResult); - } catch (Exception e) { - // Handle exceptions from get() calls - System.err.println("An error occurred while retrieving results: " + e.getMessage()); - } - } else { - // Handle exception from the CompletableFuture - System.err.println("An error occurred: " + throwable.getMessage()); - } - }).join(); + .whenComplete( + (Void, throwable) -> { + if (throwable == null) { + try { + // Retrieve results from all future + // Combine results + String combinedResult = + STR."\{ + future1.get()} \{ + future2.get()} \{ + future3.get()} \{ + future4.get()}"; + System.out.println("Combined result: " + combinedResult); + } catch (Exception e) { + // Handle exceptions from get() calls + System.err.println( + "An error occurred while retrieving results: " + + e.getMessage()); + } + } else { + // Handle exception from the CompletableFuture + System.err.println("An error occurred: " + throwable.getMessage()); + } + }) + .join(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A16CompletedFuture.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A16CompletedFuture.java index 0440c254..ed21e1e7 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A16CompletedFuture.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A16CompletedFuture.java @@ -2,25 +2,25 @@ import com.github.javafaker.Book; import com.github.javafaker.Faker; - import java.util.concurrent.CompletableFuture; public class A16CompletedFuture { public static void main(String[] args) { // Create a completed CompletableFuture with a predefined value - CompletableFuture completedFuture = CompletableFuture.completedFuture("Hello, World!"); + CompletableFuture completedFuture = + CompletableFuture.completedFuture("Hello, World!"); // Use the completed CompletableFuture - CompletableFuture stringCompletableFuture = completedFuture - .thenApply(result -> { - // This block will be executed immediately with the precomputed result - return result + " - Processed"; - }); + CompletableFuture stringCompletableFuture = + completedFuture.thenApply( + result -> { + // This block will be executed immediately with the precomputed result + return result + " - Processed"; + }); System.out.println(stringCompletableFuture.join()); Book book = Faker.instance().book(); - System.out.println(book.title() ); - + System.out.println(book.title()); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1Intro.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1Intro.java index 5d9a4468..a9762264 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1Intro.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1Intro.java @@ -1,38 +1,39 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; import com.utilities.MultiThreadUtility; -import org.apache.commons.lang3.RandomUtils; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import org.apache.commons.lang3.RandomUtils; -public class A1Intro { +public class A1Intro { public static void main(String[] args) { - //eg1(); + // eg1(); eg2(); - //eg3(); + // eg3(); } private static void eg1() { System.out.println("main thread1: " + Thread.currentThread()); - CompletableFuture - .supplyAsync(() -> {//Runs in a separate thread and releases it - System.out.println("supplier: " + Thread.currentThread()); - return Math.PI; - }) - .thenAccept(data -> System.out.println("Message received from supply Async: " + data)); + CompletableFuture.supplyAsync( + () -> { // Runs in a separate thread and releases it + System.out.println("supplier: " + Thread.currentThread()); + return Math.PI; + }) + .thenAccept( + data -> System.out.println("Message received from supply Async: " + data)); System.out.println("main thread2: " + Thread.currentThread()); } private static void eg2() { - CompletableFuture thisNeverEnds = getData() - .thenAccept(data -> System.out.println(data)) - .thenRun(() -> System.out.println("Can continue from this on...")) - .thenRun(() -> System.out.println("this never ends")) - .thenRun(() -> System.out.println("tap on, get data... get out...")); + CompletableFuture thisNeverEnds = + getData() + .thenAccept(data -> System.out.println(data)) + .thenRun(() -> System.out.println("Can continue from this on...")) + .thenRun(() -> System.out.println("this never ends")) + .thenRun(() -> System.out.println("tap on, get data... get out...")); try { thisNeverEnds.get(); @@ -41,12 +42,13 @@ private static void eg2() { } catch (ExecutionException e) { throw new RuntimeException(e); } - } private static void eg3() { try { - System.out.println(getData().get());//BAD IDEA, forces exception handling, it's a BLOCKING CALL for forGET + System.out.println( + getData().get()); // BAD IDEA, forces exception handling, it's a BLOCKING CALL + // for forGET } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { @@ -56,15 +58,16 @@ private static void eg3() { public static CompletableFuture generateRand() { return CompletableFuture.supplyAsync( - () -> RandomUtils.nextInt(1, 10));//Returning a random number Asyncronously + () -> RandomUtils.nextInt(1, 10)); // Returning a random number Asyncronously } public static CompletableFuture getData() { return CompletableFuture.supplyAsync( () -> { System.out.println("Getting the data......"); - MultiThreadUtility.delay(1000);//Try commenting and see how it's changing the thread - return Double.valueOf(22/7); + MultiThreadUtility.delay( + 1000); // Try commenting and see how it's changing the thread + return Double.valueOf(22 / 7); }); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithGet.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithGet.java index 2ec273ac..0ee1d4c8 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithGet.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithGet.java @@ -1,9 +1,8 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A1WithGet { @@ -11,16 +10,26 @@ public static void main(String[] args) { DataFetchService dataFetchService = new DataFetchService(); System.out.println("main: " + Thread.currentThread()); - CompletableFuture voidCompletableFuture = CompletableFuture - .supplyAsync(() -> { - System.out.println("supplier: " + Thread.currentThread());//Runs in a separate thread pool - return dataFetchService.greetingsService(1_000); - }) - .thenApply(String::toUpperCase) - .thenAccept(greetings -> System.out.println("Message received from supply Async: " + greetings + ": " + Thread.currentThread())); + CompletableFuture voidCompletableFuture = + CompletableFuture.supplyAsync( + () -> { + System.out.println( + "supplier: " + + Thread.currentThread()); // Runs in a separate + // thread pool + return dataFetchService.greetingsService(1_000); + }) + .thenApply(String::toUpperCase) + .thenAccept( + greetings -> + System.out.println( + "Message received from supply Async: " + + greetings + + ": " + + Thread.currentThread())); try { - voidCompletableFuture.get();//Blocks the main thread until the supplyAsync is done + voidCompletableFuture.get(); // Blocks the main thread until the supplyAsync is done } catch (InterruptedException e) { System.out.println("Thread was interrupted"); Thread.currentThread().interrupt(); // Preserve interruption status @@ -28,7 +37,7 @@ public static void main(String[] args) { System.out.println("Caught exception: " + e.getCause()); // Print actual cause } - //Because of join, DONE will be printed after async call is done + // Because of join, DONE will be printed after async call is done System.out.println("DONE: " + Thread.currentThread()); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithJoin.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithJoin.java index 9965f403..8ede7885 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithJoin.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A1WithJoin.java @@ -1,8 +1,7 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - import java.util.concurrent.CompletableFuture; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A1WithJoin { @@ -10,17 +9,27 @@ public static void main(String[] args) { DataFetchService dataFetchService = new DataFetchService(); System.out.println("main: " + Thread.currentThread()); - CompletableFuture voidCompletableFuture = CompletableFuture - .supplyAsync(() -> { - System.out.println("supplier: " + Thread.currentThread());//Runs in a separate thread pool - return dataFetchService.greetingsService(10_000); - }) - .thenApply(String::toUpperCase) - .thenAccept(greetings -> System.out.println("Message received from supply Async: " + greetings + ": " + Thread.currentThread())); + CompletableFuture voidCompletableFuture = + CompletableFuture.supplyAsync( + () -> { + System.out.println( + "supplier: " + + Thread.currentThread()); // Runs in a separate + // thread pool + return dataFetchService.greetingsService(10_000); + }) + .thenApply(String::toUpperCase) + .thenAccept( + greetings -> + System.out.println( + "Message received from supply Async: " + + greetings + + ": " + + Thread.currentThread())); - voidCompletableFuture.join();//Blocks the main thread until the supplyAsync is done + voidCompletableFuture.join(); // Blocks the main thread until the supplyAsync is done - //Because of join, DONE will be printed after async call is done + // Because of join, DONE will be printed after async call is done System.out.println("DONE: " + Thread.currentThread()); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A3Pipeline.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A3Pipeline.java index 98b06213..7a1c83fa 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A3Pipeline.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A3Pipeline.java @@ -1,43 +1,62 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; +import static com.utilities.MultiThreadUtility.delaySeconds; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import static com.utilities.MultiThreadUtility.delaySeconds; - public class A3Pipeline { public static void main(String[] args) throws ExecutionException, InterruptedException { - //intro(); + // intro(); establishAndrunPipeline(); } private static void establishAndrunPipeline() { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> getData()); - //If there is an exception, the future will go into REJECT state - CompletableFuture voidCompletableFuture = completableFuture - .thenApply(x -> x.intValue()) - .thenApply(x -> Double.parseDouble(String.valueOf(x))) //If there is an exception, handle with exceptionally - .thenApply(x -> 2 / x) - .exceptionally(throwable -> { - System.out.println("Exception received " + throwable); - return Double.valueOf(-1); - }) - .thenAccept(x -> System.out.println("rtr " + x))//Behaves like ForEach, but not a reduction operation. - .thenRun(() -> System.out.println("Can continue")) - .thenRun(() -> System.out.println("Even further")); + CompletableFuture completableFuture = + CompletableFuture.supplyAsync(() -> getData()); + // If there is an exception, the future will go into REJECT state + CompletableFuture voidCompletableFuture = + completableFuture + .thenApply(x -> x.intValue()) + .thenApply( + x -> + Double.parseDouble( + String.valueOf( + x))) // If there is an exception, handle + // with exceptionally + .thenApply(x -> 2 / x) + .exceptionally( + throwable -> { + System.out.println("Exception received " + throwable); + return Double.valueOf(-1); + }) + .thenAccept( + x -> + System.out.println( + "rtr " + x)) // Behaves like ForEach, but not a + // reduction operation. + .thenRun(() -> System.out.println("Can continue")) + .thenRun(() -> System.out.println("Even further")); delaySeconds(5); - voidCompletableFuture.join();//Holding the main thread from quitting before spitting out the logs + voidCompletableFuture + .join(); // Holding the main thread from quitting before spitting out the logs System.out.println("Done"); } private static void intro() { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> getData()); + CompletableFuture completableFuture = + CompletableFuture.supplyAsync(() -> getData()); - CompletableFuture voidCompletableFuture = completableFuture - .thenApply(num -> num * 100)//like Map - .thenAccept(data -> System.out.println(data))//forEach, like reduction operation - .thenRun(() -> System.out.println("Job Done!!"));//Still continue with the CompletableFuture + CompletableFuture voidCompletableFuture = + completableFuture + .thenApply(num -> num * 100) // like Map + .thenAccept( + data -> + System.out.println( + data)) // forEach, like reduction operation + .thenRun(() -> System.out.println("Job Done!!")); // Still continue with the + // CompletableFuture voidCompletableFuture.join(); } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4Complete.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4Complete.java index 53afb95b..6d27e91a 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4Complete.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4Complete.java @@ -5,13 +5,13 @@ public class A4Complete { public static void main(String[] args) { CompletableFuture future = new CompletableFuture<>(); - //Establish the pipeline + // Establish the pipeline future.thenApply(num -> num * 2) .thenApply(num -> num + 1) .thenAccept(System.out::println) .thenRun(() -> System.out.println("Continue on...")); - //Pipeline does not run until the complete is supplied a value + // Pipeline does not run until the complete is supplied a value future.complete(100); // Manually complete the future with the value 42 } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteExceptionally.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteExceptionally.java index 97b15c91..83fe5bd5 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteExceptionally.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteExceptionally.java @@ -1,9 +1,9 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import java.util.concurrent.CompletableFuture; - import static com.utilities.MultiThreadUtility.delay; +import java.util.concurrent.CompletableFuture; + public class A4CompleteExceptionally { public static void main(String[] args) { CompletableFuture future = new CompletableFuture<>(); @@ -16,8 +16,11 @@ public static void main(String[] args) { System.out.println("Pipeline is built...."); delay(1000); - future.completeExceptionally(new RuntimeException("don't write such code"));//Evaluates lazily. The pipeline executes from this point on - //future.complete(2); + future.completeExceptionally( + new RuntimeException( + "don't write such code")); // Evaluates lazily. The pipeline executes from + // this point on + // future.complete(2); delay(1000); } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteVariety.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteVariety.java index b74970e1..b86194d6 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteVariety.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4CompleteVariety.java @@ -1,13 +1,12 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import com.utilities.InternetUtilities; +import static com.utilities.MultiThreadUtility.delay; +import com.utilities.InternetUtilities; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; -import static com.utilities.MultiThreadUtility.delay; - public class A4CompleteVariety { public static void main(String[] args) { intro0(); @@ -24,17 +23,18 @@ private static void intro0() { System.out.println("Pipeline is built"); // Manually complete the future with the value 42 - completableFuture.complete(3);//Pipeline doesnot run until the complete is supplied a value. + completableFuture.complete( + 3); // Pipeline doesnot run until the complete is supplied a value. } private static void intro1() { CompletableFuture future = new CompletableFuture<>(); - future - .thenApply(data -> 2 / data * 2) - .exceptionally(throwable -> { - System.out.println(throwable.getMessage()); - return 9; - }) + future.thenApply(data -> 2 / data * 2) + .exceptionally( + throwable -> { + System.out.println(throwable.getMessage()); + return 9; + }) .thenApply(data -> data + 1) .thenAccept(data -> System.out.println("Result from Future " + data)) .thenRun(() -> System.out.println("Process Completed!!")); @@ -42,26 +42,28 @@ private static void intro1() { System.out.println("Pipeline is built...."); delay(4000); - future.complete(0);//Evaluates lazily. The pipeline executes from this point on + future.complete(0); // Evaluates lazily. The pipeline executes from this point on } private static void intro2() { CompletableFuture> future = new CompletableFuture<>(); - future - .thenApply(data -> data.stream().limit(10).collect(Collectors.toList())) - .thenApply(data -> { - return data.stream() - .map(word -> getTransformedString(word)) - .collect(Collectors.toList()); - - }) + future.thenApply(data -> data.stream().limit(10).collect(Collectors.toList())) + .thenApply( + data -> { + return data.stream() + .map(word -> getTransformedString(word)) + .collect(Collectors.toList()); + }) .thenAccept(data -> data.forEach(str -> System.out.println("Word is :: " + str))); System.out.println("Pipeline is built...."); delay(3000); - future.complete(InternetUtilities.bringWordListFromNet());//Evaluates lazily. The pipeline executes from this point on + future.complete( + InternetUtilities + .bringWordListFromNet()); // Evaluates lazily. The pipeline executes from + // this point on System.out.println("Post Future"); } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4ThenApply.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4ThenApply.java index d9c554d9..160ae043 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4ThenApply.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A4ThenApply.java @@ -2,37 +2,36 @@ import com.entity.Vehicle; import com.entity.dto.VehicleTransformed; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.functions.DataTransformationFunctions; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.functions.DataTransformationFunctions; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A4ThenApply { static DataFetchService dataFetchService; /** - * ### thenApply() - * Completion Stage method - * used for applying transformations, takes a Function - * thenApply deals with **Function that returns** a value - * returns CompletableFuture of Type T + * ### thenApply() Completion Stage method used for applying transformations, takes a Function + * thenApply deals with **Function that returns** a value returns CompletableFuture of Type T */ public static void main(String[] args) { dataFetchService = new DataFetchService(); CompletableFuture> completableFuture = CompletableFuture.supplyAsync(() -> dataFetchService.fetchVehicles(2)) - .thenApply(vehicles -> getTransformedList(vehicles));//returns the completable future of type entity + .thenApply( + vehicles -> + getTransformedList( + vehicles)); // returns the completable future of + // type entity List join = completableFuture.join(); System.out.println(join.size()); } private static List getTransformedList(List vehicles) { - return vehicles - .stream() + return vehicles.stream() .map(DataTransformationFunctions.vehicleFunction) .collect(Collectors.toList()); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5CompletableFutureExceptionHandling.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5CompletableFutureExceptionHandling.java index c434a8e8..a4e746c2 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5CompletableFutureExceptionHandling.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5CompletableFutureExceptionHandling.java @@ -1,76 +1,95 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; +import static com.utilities.MultiThreadUtility.logShortMessage; import java.util.concurrent.CompletableFuture; - -import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class A5CompletableFutureExceptionHandling { DataFetchService dataFetchService = new DataFetchService(); public String async_call_exception_handle() { - CompletableFuture greetings = CompletableFuture.supplyAsync(() -> this.dataFetchService.greetingsService(1000)); - CompletableFuture firstName = CompletableFuture.supplyAsync(() -> this.dataFetchService.firstNameService(1000)); - CompletableFuture lastName = CompletableFuture.supplyAsync(() -> this.dataFetchService.lastNameService(1000)); + CompletableFuture greetings = + CompletableFuture.supplyAsync(() -> this.dataFetchService.greetingsService(1000)); + CompletableFuture firstName = + CompletableFuture.supplyAsync(() -> this.dataFetchService.firstNameService(1000)); + CompletableFuture lastName = + CompletableFuture.supplyAsync(() -> this.dataFetchService.lastNameService(1000)); CompletableFuture fullNameCompletableFuture = greetings - .handle((result, exception) -> { - logShortMessage("Result is " + result); - if (null != exception) { - logShortMessage("Found Exception" + exception.getMessage()); - return "ERROR Hi!!"; - } else { - return result; - } - }) - .thenCombine(firstName, (previous, current) -> { - return previous + " " + current; - }) - .handle((result, exception) -> { - logShortMessage("Result is " + result); - if (null != exception) { - logShortMessage("Found Exception" + exception.getMessage()); - return "ERROR FN!!"; - } else { - return result; - } - }) - .thenCombine(lastName, (fn, ln) -> { - return fn + " " + ln; - })//Completion stage is the last name service. + .handle( + (result, exception) -> { + logShortMessage("Result is " + result); + if (null != exception) { + logShortMessage("Found Exception" + exception.getMessage()); + return "ERROR Hi!!"; + } else { + return result; + } + }) + .thenCombine( + firstName, + (previous, current) -> { + return previous + " " + current; + }) + .handle( + (result, exception) -> { + logShortMessage("Result is " + result); + if (null != exception) { + logShortMessage("Found Exception" + exception.getMessage()); + return "ERROR FN!!"; + } else { + return result; + } + }) + .thenCombine( + lastName, + (fn, ln) -> { + return fn + " " + ln; + }) // Completion stage is the last name service. .thenApply(completeName -> completeName.toUpperCase()); return fullNameCompletableFuture.join(); } public String async_call_exception_exceptionally() { - CompletableFuture greetings = CompletableFuture.supplyAsync(() -> this.dataFetchService.greetingsService(1000)); - CompletableFuture firstName = CompletableFuture.supplyAsync(() -> this.dataFetchService.firstNameService(1000)); - CompletableFuture lastName = CompletableFuture.supplyAsync(() -> this.dataFetchService.lastNameService(1000)); + CompletableFuture greetings = + CompletableFuture.supplyAsync(() -> this.dataFetchService.greetingsService(1000)); + CompletableFuture firstName = + CompletableFuture.supplyAsync(() -> this.dataFetchService.firstNameService(1000)); + CompletableFuture lastName = + CompletableFuture.supplyAsync(() -> this.dataFetchService.lastNameService(1000)); CompletableFuture fullNameCompletableFuture = greetings - .exceptionally((exception) -> { - if (null != exception) { - logShortMessage("Found Exception" + exception.getMessage()); - } - return "ERROR Hi!!"; - }) - .thenCombine(firstName, (previous, current) -> { - return previous + " " + current; - }) - .exceptionally((exception) -> { - if (null != exception) { - logShortMessage("Found Exception after greetings" + exception.getMessage()); - } - return "ERROR FN!!"; - }) - .thenCombine(lastName, (fn, ln) -> { - return fn + " " + ln; - })//Completion stage is the last name service. + .exceptionally( + (exception) -> { + if (null != exception) { + logShortMessage("Found Exception" + exception.getMessage()); + } + return "ERROR Hi!!"; + }) + .thenCombine( + firstName, + (previous, current) -> { + return previous + " " + current; + }) + .exceptionally( + (exception) -> { + if (null != exception) { + logShortMessage( + "Found Exception after greetings" + + exception.getMessage()); + } + return "ERROR FN!!"; + }) + .thenCombine( + lastName, + (fn, ln) -> { + return fn + " " + ln; + }) // Completion stage is the last name service. .thenApply(completeName -> completeName.toUpperCase()); return fullNameCompletableFuture.join(); diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5Exceptionally.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5Exceptionally.java index a29c085d..d259716b 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5Exceptionally.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A5Exceptionally.java @@ -1,35 +1,39 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; +import static com.utilities.MultiThreadUtility.delay; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import static com.utilities.MultiThreadUtility.delay; - public class A5Exceptionally { public static void main(String[] args) throws ExecutionException, InterruptedException { - //exceptionIntro1(); + // exceptionIntro1(); CompletableFuture future = new CompletableFuture<>(); - future - .thenApply(data -> 5 / data)//Exception will not be printed unless exceptionally is written to handle it. - .exceptionally(throwable -> { - System.out.println("5/data exception" + throwable.getMessage()); - return null; - }) - .thenApply(data -> data * 2)//This will get skipped if the above exception is not handled + future.thenApply(data -> 5 / data) // Exception will not be printed unless + // exceptionally is written to handle it. + .exceptionally( + throwable -> { + System.out.println("5/data exception" + throwable.getMessage()); + return null; + }) + .thenApply(data -> data * 2) // This will get skipped if the above exception is not + // handled .exceptionally(throwable -> handleEx1(throwable)) - .thenApply(data -> data + 2)//NOT A PROBABLE EXCEPTION, except for a null - .exceptionally(throwable -> { - System.out.println("Exception after data+2 :: NPE " + throwable); - return -1; - }) + .thenApply(data -> data + 2) // NOT A PROBABLE EXCEPTION, except for a null + .exceptionally( + throwable -> { + System.out.println("Exception after data+2 :: NPE " + throwable); + return -1; + }) .thenAccept(data -> System.out.println(data)); System.out.println("Pipeline is done"); delay(4000); - //future.complete(3/0);//Exception will be thrown only for the imperative style not for the functional + // future.complete(3/0);//Exception will be thrown only for the imperative style not for the + // functional future.complete(0); } @@ -38,11 +42,15 @@ private static void exceptionIntro1() { future = getData(); future - //.thenApply(x -> x.intValue() ) + // .thenApply(x -> x.intValue() ) .thenApply(x -> 0) .exceptionally(throwable -> handleEx1(throwable)) .thenApply(x -> 2 * x) - .thenAccept(x -> System.out.println("rtr " + x))//Behaves like ForEach, but not a reduction operation. + .thenAccept( + x -> + System.out.println( + "rtr " + x)) // Behaves like ForEach, but not a reduction + // operation. .exceptionally(throwable -> handleEx2(throwable)) .thenRun(() -> System.out.println("Can continue")) .thenRun(() -> System.out.println("Even further")) diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A6DontUseGet.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A6DontUseGet.java index fe400043..d1fad98f 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A6DontUseGet.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A6DontUseGet.java @@ -1,25 +1,26 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import java.util.concurrent.CompletableFuture; - import static com.utilities.MultiThreadUtility.delay; +import java.util.concurrent.CompletableFuture; + public class A6DontUseGet { public static void main(String[] args) throws Exception { CompletableFuture future = CompletableFuture.supplyAsync(() -> compute()); System.out.println("Before running the pileline"); - //Double data = future.get();//BAD Idea, forces to handle exception - //get() is a blocking call; The best thing to do with GET is to forGET - //INSTEAD use thenAccept - + // Double data = future.get();//BAD Idea, forces to handle exception + // get() is a blocking call; The best thing to do with GET is to forGET + // INSTEAD use thenAccept delay(100); - //if it's so important to use get, use getNow() with a default value - Double data = future.getNow(-99.0);//need to provide a value if the value is absent - //getNow() is impatient non-blocking and moves on with a value if there is no immediate response - //If there is delay prior to getNow call then the getNow may return the correct value. - //The delay in compute is 100 ms while that of the delay above getNow is 1000ms, so it works. + // if it's so important to use get, use getNow() with a default value + Double data = future.getNow(-99.0); // need to provide a value if the value is absent + // getNow() is impatient non-blocking and moves on with a value if there is no immediate + // response + // If there is delay prior to getNow call then the getNow may return the correct value. + // The delay in compute is 100 ms while that of the delay above getNow is 1000ms, so it + // works. System.out.println(data); } @@ -28,4 +29,4 @@ private static double compute() { delay(100); return 3.14; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A7ThreadOfExecution.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A7ThreadOfExecution.java index c7d2b890..68ff7f9f 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A7ThreadOfExecution.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A7ThreadOfExecution.java @@ -1,23 +1,23 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - -import java.util.concurrent.CompletableFuture; - import static com.utilities.MultiThreadUtility.delay; import static com.utilities.PerformanceUtility.*; +import java.util.concurrent.CompletableFuture; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; + public class A7ThreadOfExecution { public static void main(String[] args) { DataFetchService dataFetchService = new DataFetchService(); System.out.println("main:: " + Thread.currentThread()); System.out.println("++++++++++++++++++++++++ Synchronization Run ++++++++++++++++++++++++"); - //Takes total time equal to sum total of individual method times - //total time = method1 + method2 + method3 + // Takes total time equal to sum total of individual method times + // total time = method1 + method2 + method3 sequentialProgramRunningInOneThread(dataFetchService); System.out.println("++++++++++++++++++++++++ Async Run ++++++++++++++++++++++++"); - //Takes time based on the slowest method. total time = Max(method1, method2, method3) + tiny extra processing time + // Takes time based on the slowest method. total time = Max(method1, method2, method3) + + // tiny extra processing time asyncRun(dataFetchService); System.out.println("main:: " + Thread.currentThread()); @@ -27,18 +27,19 @@ public static void main(String[] args) { private static void test() { CompletableFuture future = getData(); - delay(1000);//delay + delay(1000); // delay future.thenAccept(data -> getPrintln(data)); // May run in the main thread if all the executions are done, // or it may run in a different thread System.out.println("After printing Data"); - delay(1000);//delay + delay(1000); // delay } private static void sequentialProgramRunningInOneThread(DataFetchService dataFetchService) { - //Example service, could be a DB Call or a REST Call to outside Service or anyService Call (KafkaQueue, other messaging Queue) + // Example service, could be a DB Call or a REST Call to outside Service or anyService Call + // (KafkaQueue, other messaging Queue) startTimer(); String hello = dataFetchService.greetingsService(1000); String firstName = dataFetchService.firstNameService(1000); @@ -52,12 +53,20 @@ private static void sequentialProgramRunningInOneThread(DataFetchService dataFet private static void asyncRun(DataFetchService dataFetchService) { // May run in the main thread if all the executions are done, // or it may run in a different thread - CompletableFuture helloFuture = CompletableFuture.supplyAsync(() -> dataFetchService.greetingsService(1000)); - CompletableFuture firstNameFuture = CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); - CompletableFuture lastNameFuture = CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); - - startTimer();//Actual call to the pipeline - System.out.println(helloFuture.join() + " " + firstNameFuture.join() + " " + lastNameFuture.join());//Prefer join instead of GET + CompletableFuture helloFuture = + CompletableFuture.supplyAsync(() -> dataFetchService.greetingsService(1000)); + CompletableFuture firstNameFuture = + CompletableFuture.supplyAsync(() -> dataFetchService.firstNameService(1000)); + CompletableFuture lastNameFuture = + CompletableFuture.supplyAsync(() -> dataFetchService.lastNameService(1000)); + + startTimer(); // Actual call to the pipeline + System.out.println( + helloFuture.join() + + " " + + firstNameFuture.join() + + " " + + lastNameFuture.join()); // Prefer join instead of GET stopTimer(); } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A8ChangingThreadPool.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A8ChangingThreadPool.java index 335e26b3..fc0e2f95 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A8ChangingThreadPool.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/A8ChangingThreadPool.java @@ -1,36 +1,37 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; +import static com.utilities.MultiThreadUtility.delay; + import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; - -import static com.utilities.MultiThreadUtility.delay; public class A8ChangingThreadPool { /* In Spring properties yml, more arguments to Constructor can be passed. - spring: - task: - execution: - pool: - coreSize: 10 - maxSize: 400 - keepAlive: 60s - allowCoreThreadTimeout: true - */ + spring: + task: + execution: + pool: + coreSize: 10 + maxSize: 400 + keepAlive: 60s + allowCoreThreadTimeout: true + */ public static void main(String[] args) { System.out.println("m: " + Thread.currentThread()); - //ForkJoinPool pool = new ForkJoinPool(10); + // ForkJoinPool pool = new ForkJoinPool(10); ExecutorService pool = Executors.newCachedThreadPool(); - CompletableFuture future = CompletableFuture.supplyAsync(() -> compute(), pool); - CompletableFuture doubleCompletableFuture = future.thenApplyAsync(data -> data * 2, pool); + CompletableFuture future = CompletableFuture.supplyAsync(() -> compute(), pool); + CompletableFuture doubleCompletableFuture = + future.thenApplyAsync(data -> data * 2, pool); delay(2000); - CompletableFuture voidCompletableFuture = doubleCompletableFuture.thenAcceptAsync(data -> getPrintln(data),pool); + CompletableFuture voidCompletableFuture = + doubleCompletableFuture.thenAcceptAsync(data -> getPrintln(data), pool); // May run in the main thread if all the executions are done, // or it may run in a different thread System.out.println("After printing Data"); - delay(1000);//delay + delay(1000); // delay System.out.println("m: " + Thread.currentThread()); pool.close(); diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/ECallMultipleService.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/ECallMultipleService.java index 2771664e..4c0d67a4 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/ECallMultipleService.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/ECallMultipleService.java @@ -6,7 +6,6 @@ import com.entity.gutendex.Result; import com.entity.openLibrary.OpenLibDto; import com.utilities.RestGETReadUtility; - import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -20,7 +19,8 @@ public class ECallMultipleService { public static void main(String[] args) { String bookName = "The+Christmas+Carol"; - // 1. Gutendex search (Search the Author from book name) - https://gutendex.com/books/?search=Pride+and+Prejudice + // 1. Gutendex search (Search the Author from book name) - + // https://gutendex.com/books/?search=Pride+and+Prejudice Gutendex gutendex = RestGETReadUtility.getGutenbergResults(bookName); List results = gutendex.results.stream().collect(Collectors.toList()); Author author = results.stream().findFirst().get().getAuthors().stream().findFirst().get(); @@ -31,14 +31,20 @@ public static void main(String[] args) { List isbnList = new ArrayList<>(); for (int i = 0; i < itemList.size(); i++) { Item item = itemList.get(i); - isbnList.addAll(item.getIsbn().stream().filter(x -> x != null).collect(Collectors.toList())); + isbnList.addAll( + item.getIsbn().stream().filter(x -> x != null).collect(Collectors.toList())); } - //String isbn = itemList.stream().findFirst().get().getIsbn().stream().findFirst().get(); + // String isbn = itemList.stream().findFirst().get().getIsbn().stream().findFirst().get(); - // 3. Find Book Details from ISBN - https://openlibrary.org/api/books?bibkeys=ISBN:9781108074568&format=json&jscmd=data - String isbn = isbnList.stream().reduce("", (partialString, element) -> partialString + element + ","); + // 3. Find Book Details from ISBN - + // https://openlibrary.org/api/books?bibkeys=ISBN:9781108074568&format=json&jscmd=data + String isbn = + isbnList.stream() + .reduce("", (partialString, element) -> partialString + element + ","); - List openLibDto = RestGETReadUtility.getBookDetailsOpenLibrary(isbn).stream().collect(Collectors.toList()); + List openLibDto = + RestGETReadUtility.getBookDetailsOpenLibrary(isbn).stream() + .collect(Collectors.toList()); openLibDto.forEach(x -> System.out.println(x)); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/TestThenCompose.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/TestThenCompose.java index b35310f2..9e18253f 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/TestThenCompose.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/TestThenCompose.java @@ -1,26 +1,37 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics; import com.entity.dto.VehicleTransformed; -import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; - import java.util.concurrent.CompletableFuture; +import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; public class TestThenCompose { public static DataFetchService dfs = new DataFetchService(); public static A12ThenCompose cf = new A12ThenCompose(dfs); public static void main(String[] args) { - CompletableFuture testGetGreetings_compose = A12ThenCompose.getGreetings_compose();//Get name from one service and pass the name into another + CompletableFuture testGetGreetings_compose = + A12ThenCompose + .getGreetings_compose(); // Get name from one service and pass the name into + // another - CompletableFuture testGetHeighestMileageCar = A12ThenCompose.getHeighestMileageCar();//Get name from one service and pass the name into another + CompletableFuture testGetHeighestMileageCar = + A12ThenCompose + .getHeighestMileageCar(); // Get name from one service and pass the name + // into another - //Gather the results adn then accept - testGetGreetings_compose.thenAccept(result -> { - System.out.println(result); - }).join(); + // Gather the results adn then accept + testGetGreetings_compose + .thenAccept( + result -> { + System.out.println(result); + }) + .join(); - testGetHeighestMileageCar.thenAccept(result -> { - System.out.println(result); - }).join(); + testGetHeighestMileageCar + .thenAccept( + result -> { + System.out.println(result); + }) + .join(); } } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/functions/DataTransformationFunctions.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/functions/DataTransformationFunctions.java index 64319b35..ca69fe17 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/functions/DataTransformationFunctions.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/functions/DataTransformationFunctions.java @@ -2,32 +2,32 @@ import com.entity.Vehicle; import com.entity.dto.VehicleTransformed; - -import java.time.ZonedDateTime; import java.util.function.Function; public class DataTransformationFunctions { public static Function vehicleFunction = (vehicle) -> { - StringBuilder carOptionsBuilder = new StringBuilder(); StringBuilder specsBuilder = new StringBuilder(); for (int i = 0; i < vehicle.getCarOptions().size() - 1; i++) { carOptionsBuilder.append(vehicle.getCarOptions().get(i)).append(";"); } - carOptionsBuilder.append(vehicle.getCarOptions().get(vehicle.getCarOptions().size() - 1));//Off by one + carOptionsBuilder.append( + vehicle.getCarOptions() + .get(vehicle.getCarOptions().size() - 1)); // Off by one for (int i = 0; i < vehicle.getSpecs().size() - 1; i++) { specsBuilder.append(vehicle.getSpecs().get(i)).append(";"); } - specsBuilder.append(vehicle.getSpecs().get(vehicle.getSpecs().size() - 1));//Off by one + specsBuilder.append( + vehicle.getSpecs().get(vehicle.getSpecs().size() - 1)); // Off by one return VehicleTransformed.builder() .carOptions(carOptionsBuilder.toString()) .specs(specsBuilder.toString()) - //Other properties + // Other properties .carType(vehicle.getCarType()) .color(vehicle.getColor()) .doors(vehicle.getDoors()) diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/service/DataFetchService.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/service/DataFetchService.java index ce26f62d..635acfa8 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/service/DataFetchService.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/completableFutureBasics/service/DataFetchService.java @@ -1,18 +1,16 @@ package nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service; +import static com.utilities.MultiThreadUtility.*; +import static nitin.multithreading.cVirtualThreads.v3structuredConcurrency.BlockingIOTasks.TaskResponse; + import com.entity.Vehicle; import com.entity.dto.VehicleTransformed; import com.utilities.RestGETReadUtility; - -import static nitin.multithreading.cVirtualThreads.v3structuredConcurrency.BlockingIOTasks.TaskResponse; - import java.util.Comparator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import static com.utilities.MultiThreadUtility.*; - public class DataFetchService { public List fetchVehicles(int size) { @@ -20,7 +18,7 @@ public List fetchVehicles(int size) { } public String firstNameService(int delayInMillisec) { - delay(delayInMillisec);//simulating task completion latency + delay(delayInMillisec); // simulating task completion latency logMessage("From firstNameService"); return "john"; } @@ -37,25 +35,32 @@ public String greetingsService(int delayInMillisec) { return "Hello!"; } - public CompletableFuture findVehicleWithGreatMileage(List vehicleList) { + public CompletableFuture findVehicleWithGreatMileage( + List vehicleList) { logMessage("From composeVehicleData"); - //Returning the vehicle with maximum mileage - return CompletableFuture.supplyAsync(() -> vehicleList.stream() - .sorted(Comparator.comparing(VehicleTransformed::getMileage).reversed()) - .findFirst().get()); + // Returning the vehicle with maximum mileage + return CompletableFuture.supplyAsync( + () -> + vehicleList.stream() + .sorted( + Comparator.comparing(VehicleTransformed::getMileage) + .reversed()) + .findFirst() + .get()); } public CompletableFuture futureName(String name) { - return CompletableFuture.supplyAsync(() -> { - delay(1000); - return ("Hello " + name); - }); + return CompletableFuture.supplyAsync( + () -> { + delay(1000); + return ("Hello " + name); + }); } public TaskResponse microTask(String name, int secs, boolean isSuccess) { logShortMessage("Begin microTask of " + secs + " seconds"); - //Fail Fast + // Fail Fast if (!isSuccess || secs > 7) { throw new RuntimeException(STR."Task Failed : \{name} \{isSuccess} \{secs}"); } @@ -66,7 +71,7 @@ public TaskResponse microTask(String name, int secs, boolean isSuccess) { } catch (InterruptedException e) { throw new RuntimeException(e); } - long endTime = System.currentTimeMillis(); + long endTime = System.currentTimeMillis(); logShortMessage("End microTask of " + secs + " seconds"); return new TaskResponse(name, String.valueOf(secs), endTime - currentTime); diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/FuturesPlay.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/FuturesPlay.java index 2892cbef..dd9041f1 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/FuturesPlay.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/FuturesPlay.java @@ -4,7 +4,7 @@ /* * This class has methods whichs submits tasks in multiple ways. - * You can uncomment the method call in main and run to play with these. + * You can uncomment the method call in main and run to play with these. */ @SuppressWarnings("unused") public class FuturesPlay { @@ -12,26 +12,28 @@ public class FuturesPlay { public static void main(String[] args) throws Exception { // Example of submitting a Runnable Task - // exampleSubmitRunnable(); - + // exampleSubmitRunnable(); + // Example of submitting a Callable Task and getting TaskResult // exampleSubmitOneCallable(); - + // Example of submitting multiple Callable Tasks // exampleSubmitMultipleCallables(); - + // Example of submitting multiple Callable Tasks // using the ExecutorCompletionService exampleSubmitTasksUsingCompletionService(); - + // Example using FutureTask // exampleFutureTasks(); } private static void exampleFutureTasks() { - OurFutureTask task1 = new OurFutureTask<>(() -> FuturesPlay.doTask("task1", 1, true)); - OurFutureTask task2 = new OurFutureTask<>(() -> FuturesPlay.doTask("task2", 4, false)); + OurFutureTask task1 = + new OurFutureTask<>(() -> FuturesPlay.doTask("task1", 1, true)); + OurFutureTask task2 = + new OurFutureTask<>(() -> FuturesPlay.doTask("task2", 4, false)); try (ExecutorService service = Executors.newCachedThreadPool()) { @@ -51,50 +53,47 @@ private static void exampleFutureTasks() { System.out.println("Completed all"); } - // Becomes complex when dealing with chaining static void exampleSubmitTasksUsingCompletionService() { - try (ExecutorService service = Executors.newFixedThreadPool(3)) { - - ExecutorCompletionService srv - = new ExecutorCompletionService<>(service); + try (ExecutorService service = Executors.newFixedThreadPool(3)) { - Callable callable1 = () -> FuturesPlay.doTask("task1", 2, false); - Callable callable2 = () -> FuturesPlay.doTask("task2", 1, false); + ExecutorCompletionService srv = new ExecutorCompletionService<>(service); - Future task1Future = srv.submit(callable1); - Future task2Future = srv.submit(callable2); + Callable callable1 = () -> FuturesPlay.doTask("task1", 2, false); + Callable callable2 = () -> FuturesPlay.doTask("task2", 1, false); - try { - for (int j = 0; j < 2; j++) { + Future task1Future = srv.submit(callable1); + Future task2Future = srv.submit(callable2); - Future future = srv.take(); - if (future == task1Future) { - // handle task1 future - System.out.println(future.get()); - } - else if (future == task2Future) { - // handle task2 future - System.out.println(future.get()); - } + try { + for (int j = 0; j < 2; j++) { + + Future future = srv.take(); + if (future == task1Future) { + // handle task1 future + System.out.println(future.get()); + } else if (future == task2Future) { + // handle task2 future + System.out.println(future.get()); } } - catch (InterruptedException | ExecutionException e) { - System.out.println(e); - } - + } catch (InterruptedException | ExecutionException e) { + System.out.println(e); + } } } - static void exampleSubmitMultipleCallables() { try (ExecutorService service = Executors.newFixedThreadPool(3)) { - Future task1Future = service.submit(() -> FuturesPlay.doTask("task1", 3, false)); - Future task2Future = service.submit(() -> FuturesPlay.doTask("task2", 2, false)); - Future task3Future = service.submit(() -> FuturesPlay.doTask("task3", 1, false)); + Future task1Future = + service.submit(() -> FuturesPlay.doTask("task1", 3, false)); + Future task2Future = + service.submit(() -> FuturesPlay.doTask("task2", 2, false)); + Future task3Future = + service.submit(() -> FuturesPlay.doTask("task3", 1, false)); try { @@ -114,17 +113,14 @@ static void exampleSubmitMultipleCallables() { System.out.println(e); } } - } static void exampleSubmitOneCallable() { - try (ExecutorService service - = Executors.newFixedThreadPool(3)) { + try (ExecutorService service = Executors.newFixedThreadPool(3)) { - Future future - = service.submit( - () -> FuturesPlay.doTask("SimpleTask", 1, false)); + Future future = + service.submit(() -> FuturesPlay.doTask("SimpleTask", 1, false)); // supposed to do some other work @@ -135,14 +131,12 @@ static void exampleSubmitOneCallable() { System.out.println(e); } } - } - static void exampleSubmitRunnable() - throws ExecutionException, InterruptedException { + static void exampleSubmitRunnable() throws ExecutionException, InterruptedException { // Submit a Task - try(ExecutorService service = Executors.newSingleThreadExecutor()) { + try (ExecutorService service = Executors.newSingleThreadExecutor()) { Future future = service.submit(FuturesPlay::doSimpleTask); // do other tasks here @@ -157,8 +151,7 @@ static void exampleSubmitRunnable() public static void doSimpleTask() { - System.out.printf("%s : Starting Simple Task\n", - Thread.currentThread().getName()); + System.out.printf("%s : Starting Simple Task\n", Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(5); @@ -167,28 +160,24 @@ public static void doSimpleTask() { System.out.println("Task Interrupted"); } - System.out.printf("%s : Ending Simple Task\n", - Thread.currentThread().getName()); + System.out.printf("%s : Ending Simple Task\n", Thread.currentThread().getName()); } public static TaskResult doTask(String name, int secs, boolean fail) { - System.out.printf("%s : Starting Task %s\n", - Thread.currentThread().getName(), name); + System.out.printf("%s : Starting Task %s\n", Thread.currentThread().getName(), name); try { TimeUnit.SECONDS.sleep(secs); } catch (InterruptedException e) { throw new RuntimeException(e); } - + if (fail) { throw new RuntimeException("Task Failed : " + name); } - System.out.printf("%s : Ending Task %s\n", - Thread.currentThread().getName(), name); + System.out.printf("%s : Ending Task %s\n", Thread.currentThread().getName(), name); return new TaskResult(name, secs); } - } diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/OurFutureTask.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/OurFutureTask.java index 018064f4..3c16f84b 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/OurFutureTask.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/OurFutureTask.java @@ -17,7 +17,5 @@ protected void done() { } catch (InterruptedException | ExecutionException e) { System.out.println("Exception Task1..." + exceptionNow()); } - } - + } } - diff --git a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/TaskResult.java b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/TaskResult.java index c6fec0eb..bebf1587 100644 --- a/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/TaskResult.java +++ b/src/main/java/nitin/multithreading/bFuturesAndCompletableFutures/futures/TaskResult.java @@ -1,4 +1,3 @@ package nitin.multithreading.bFuturesAndCompletableFutures.futures; -public record TaskResult(String taskName, int secs) { -} +public record TaskResult(String taskName, int secs) {} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/Business.java b/src/main/java/nitin/multithreading/cVirtualThreads/Business.java index b0f5213a..7f62fab2 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/Business.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/Business.java @@ -1,9 +1,9 @@ package nitin.multithreading.cVirtualThreads; -import com.utilities.MultiThreadUtility; -import org.json.JSONArray; -import org.json.JSONObject; +import static com.utilities.PerformanceUtility.startTimer; +import static com.utilities.PerformanceUtility.stopTimer; +import com.utilities.MultiThreadUtility; import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -15,16 +15,15 @@ import java.util.List; import java.util.Random; import java.util.stream.Stream; - -import static com.utilities.PerformanceUtility.startTimer; -import static com.utilities.PerformanceUtility.stopTimer; +import org.json.JSONArray; +import org.json.JSONObject; public class Business { private static final String FILE_PATH = "src/main/resources/twitter-words.txt"; public static void executeBusinessLogic() { MultiThreadUtility.logMessage("Start::executeBusinessLogic"); - MultiThreadUtility.delay(1_000);//Simulating an IO blocking call + MultiThreadUtility.delay(1_000); // Simulating an IO blocking call MultiThreadUtility.logMessage("END::executeBusinessLogic"); } @@ -37,10 +36,10 @@ public static String fetchFile() { list = lines.toList(); } catch (IOException e) { System.out.println(e); - }finally { + } finally { MultiThreadUtility.logMessage("End fetchFile()"); } - //Returning a random string + // Returning a random string String str = list.get(new Random().nextInt(list.size())); stopTimer(); return str; @@ -86,7 +85,7 @@ public static String blockingNetworkCall(int secs) { try (InputStream stream = uri.toURL().openStream()) { String response = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - JSONObject jsonObject = new JSONObject(response);// Parse the JSON response + JSONObject jsonObject = new JSONObject(response); // Parse the JSON response return jsonObject.getString("url"); } catch (IOException e) { throw new RuntimeException(e); @@ -100,7 +99,7 @@ public static String getBrewer() { URI uri = null; try { - MultiThreadUtility.delay(1_000);//One request per second is allowed + MultiThreadUtility.delay(1_000); // One request per second is allowed uri = new URI("https://api.openbrewerydb.org/v1/breweries/random"); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI: " + e.getMessage(), e); @@ -120,7 +119,7 @@ public static String getBrewer() { } } catch (IOException e) { throw new RuntimeException(e); - }finally { + } finally { MultiThreadUtility.logMessage("End getBrewer()"); } } @@ -147,7 +146,7 @@ public static String getBeer() { apiResponse = STR."\{name} \{style} "; } catch (IOException e) { throw new RuntimeException(e); - }finally { + } finally { MultiThreadUtility.logMessage("End getBeer()"); } return apiResponse; diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/Student.java b/src/main/java/nitin/multithreading/cVirtualThreads/Student.java index 5a923282..40910a36 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/Student.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/Student.java @@ -3,9 +3,11 @@ import lombok.*; /* Do we need to make this class Thread safe */ -@Getter @Setter -@ToString @AllArgsConstructor +@Getter +@Setter +@ToString +@AllArgsConstructor @Builder public class Student { private String name; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V1Intro.java b/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V1Intro.java index 7a11016a..a19cff22 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V1Intro.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V1Intro.java @@ -1,22 +1,20 @@ package nitin.multithreading.cVirtualThreads.v1Runnable; import com.utilities.MultiThreadUtility; -import nitin.multithreading.cVirtualThreads.Business; - import java.util.ArrayList; +import nitin.multithreading.cVirtualThreads.Business; public class V1Intro { - final static int MAX_THREADS = 100_000;//One Million + static final int MAX_THREADS = 100_000; // One Million public static void main(String[] args) throws InterruptedException { MultiThreadUtility.logShortMessage("Starting main"); platformThreads(); - //virtualThreads(); + // virtualThreads(); MultiThreadUtility.delay(1000); MultiThreadUtility.logShortMessage("Ending main"); - } private static void platformThreads() throws InterruptedException { @@ -30,9 +28,9 @@ private static void platformThreads() throws InterruptedException { } for (Thread thread : threadList) { - thread.join();//Joining all of the threads so that the next set of instructions does not run until this is done. + thread.join(); // Joining all of the threads so that the next set of instructions does + // not run until this is done. } - } private static void virtualThreads() throws InterruptedException { @@ -42,17 +40,22 @@ private static void virtualThreads() throws InterruptedException { } for (Thread thread : threadList) { - thread.join();//Joining all of the threads so that the next set of instructions does not run until this is done. + thread.join(); // Joining all of the threads so that the next set of instructions does + // not run until this is done. } } private static Thread createPlatformThread() { - //The Virtual thread starts as a Daemon thread where as the platform thread starts as a non-daemon thread - return new Thread(Business::executeBusinessLogic);//JVM Can't handle large number threads with platform threads + // The Virtual thread starts as a Daemon thread where as the platform thread starts as a + // non-daemon thread + return new Thread( + Business::executeBusinessLogic); // JVM Can't handle large number threads with + // platform threads } private static Thread createVirtualThread() { - //With Virtual threads, mounting and unmounting would happen so a thread is free to do tasks + // With Virtual threads, mounting and unmounting would happen so a thread is free to do + // tasks // Overhead of context switching is needed. return Thread.startVirtualThread(Business::executeBusinessLogic); } diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V3ThreadsNewLight.java b/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V3ThreadsNewLight.java index 180418ce..391dcf15 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V3ThreadsNewLight.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V3ThreadsNewLight.java @@ -4,11 +4,11 @@ public class V3ThreadsNewLight { public static void main(String[] args) throws InterruptedException { - //Static method initialization + // Static method initialization var t1 = Thread.startVirtualThread(() -> task1()); var t2 = Thread.startVirtualThread(() -> task2()); - //All Virtual Threads are always daemon threads, + // All Virtual Threads are always daemon threads, // don’t forget to call join() if you want to wait on the main thread. t1.join(); t2.join(); diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V5VirtualThreadCreation.java b/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V5VirtualThreadCreation.java index 69177c61..832f3d2f 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V5VirtualThreadCreation.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v1Runnable/V5VirtualThreadCreation.java @@ -1,47 +1,47 @@ package nitin.multithreading.cVirtualThreads.v1Runnable; -import com.utilities.MultiThreadUtility; -import nitin.multithreading.cVirtualThreads.Business; +import static nitin.multithreading.cVirtualThreads.Business.executeBusinessLogic; +import com.utilities.MultiThreadUtility; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; - -import static nitin.multithreading.cVirtualThreads.Business.executeBusinessLogic; +import nitin.multithreading.cVirtualThreads.Business; public class V5VirtualThreadCreation { public static void main(String[] args) throws Exception { MultiThreadUtility.logMessage("Main starts"); - //createWithStaticMethod(); - //createWithVirtualBuilder(); - //createWithFactory(); - //createWithVirtualExecutorService(); + // createWithStaticMethod(); + // createWithVirtualBuilder(); + // createWithFactory(); + // createWithVirtualExecutorService(); createWithThreadPerTaskExecutorService(); MultiThreadUtility.logMessage("Main ends successfully"); } /* Creates Virtual Threads using Static method Thread.ofVirtual() */ private static void createWithStaticMethod() throws Exception { - Thread t1 = Thread.ofVirtual().start(Business::executeBusinessLogic);//Can't be named + Thread t1 = Thread.ofVirtual().start(Business::executeBusinessLogic); // Can't be named Thread t2 = Thread.ofVirtual().start(Business::executeBusinessLogic); - //Make sure that the thread terminates before moving on + // Make sure that the thread terminates before moving on t1.join(); t2.join(); } /* Creates Virtual Threads using a Virtual Builder. * Builder is not Thread Safe - */ + */ private static void createWithVirtualBuilder() throws Exception { - Thread.Builder.OfVirtual ofVirtualBuilder = Thread.ofVirtual().name("my_virtual_thread",0); + Thread.Builder.OfVirtual ofVirtualBuilder = Thread.ofVirtual().name("my_virtual_thread", 0); - //Start the threads + // Start the threads Thread t1 = ofVirtualBuilder.start(() -> executeBusinessLogic()); Thread t2 = ofVirtualBuilder.start(() -> executeBusinessLogic()); // Make sure the threads terminate - t1.join(); t2.join(); + t1.join(); + t2.join(); } /* Creates Virtual Threads using a Thread Factory. Thread Safe */ @@ -75,7 +75,6 @@ private static void createWithVirtualExecutorService() { } } - /* Thread Per Task Executor Service */ private static void createWithThreadPerTaskExecutorService() { // Create a Virtual Thread factory with custom name @@ -88,4 +87,4 @@ private static void createWithThreadPerTaskExecutorService() { srv.submit(() -> executeBusinessLogic()); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/RequestHandler.java b/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/RequestHandler.java index d8d4f2fd..7fefd495 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/RequestHandler.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/RequestHandler.java @@ -1,7 +1,5 @@ package nitin.multithreading.cVirtualThreads.v2callable; -import nitin.multithreading.cVirtualThreads.Business; - import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; @@ -9,113 +7,130 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Collectors; +import nitin.multithreading.cVirtualThreads.Business; public class RequestHandler implements Callable { - @Override - public String call() throws Exception { - //return sequentialCall();//1 - //return concurrentCallWithFutures();//2: with its own virtual thread, Imperative style - //return concurrentCallFunctional();//2.1: functional style - - return concurrentCallCompletableFuture(); - } - - // runs the tasks concurrently using Virtual Threads and Completable Futures. - private String concurrentCallCompletableFuture() { - try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { - // CompletableFuture for dbCall with enhanced error handling - CompletableFuture dbCallFuture = CompletableFuture - .supplyAsync(() -> Business.blockingDbCall(2), service) - .exceptionally(ex -> { - System.err.println("Exception occurred in dbCall: " + ex.getMessage()); - return "Default dbCallResult (Exception)"; - }); - - // CompletableFuture for getBrewer with error handling - CompletableFuture getBrewerFuture = CompletableFuture.supplyAsync(() -> Business.getBrewer(), service) - .exceptionally(ex -> { - System.err.println("Exception occurred in getBrewer: " + ex.getMessage()); - return "Default brewer (Exception)"; - }); - - // CompletableFuture for getBeer with error handling - CompletableFuture getBeerFuture = CompletableFuture.supplyAsync(() -> Business.getBeer(), service) - .exceptionally(ex -> { - System.err.println("Exception occurred in getBeer: " + ex.getMessage()); - return "Default beer (Exception)"; - }); - - - // Combine results of all CompletableFuture - String output = CompletableFuture.allOf(dbCallFuture, getBrewerFuture, getBeerFuture) - .thenApplyAsync(voidResult -> { - String result1 = dbCallFuture.join(); - String result2 = getBrewerFuture.join(); - String result3 = getBeerFuture.join(); - return STR."[\{result1},\{result2},\{result3}]"; - }, service) - .join(); - - System.out.println(output); - return output; - - } - } - - //runs the tasks concurrently using Virtual Threads and Futures. - private String concurrentCallWithFutures() throws Exception { - //Starting 2 tasks under one thread - try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { - - long start = System.currentTimeMillis(); - //One virtual thread per task - Future dbFuture = service.submit(() -> Business.blockingDbCall(2)); - Future restFuture = service.submit(Business::getBeer); - - //The get() calls are blocking calls - String result = String.format("[%s,%s,%s]", "concurrentCallWithFutures :: ",dbFuture.get(), restFuture.get()); - - System.out.println("time = " + (System.currentTimeMillis() - start) + " ms"); - System.out.println("concurrentCallWithFutures ::" + result); - return result; - - } - } - - // runs the tasks concurrently using Virtual Threads, Futures and functional style. - private String concurrentCallFunctional() throws Exception { - try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { - - String result = service.invokeAll(Arrays.asList(() -> Business.blockingDbCall(2), Business::getBeer)) - .stream() - .map(f -> { - try { - return (String)f.get(); - } - catch (Exception e) { - return null; - } - }) - .collect(Collectors.joining(",")); - - return "[" + result + "]"; - - } - } - - //Request which is handled Sequentially using Virtual Threads. - private String sequentialCall() throws Exception { - long start = System.currentTimeMillis(); - - String result1 = Business.getBrewer(); - String result2 = Business.getBeer(); - - String result = String.format("[%s,%s]", result1, result2); - - long end = System.currentTimeMillis(); - System.out.println("time = " + (end - start)); - - return result; - } -} \ No newline at end of file + @Override + public String call() throws Exception { + // return sequentialCall();//1 + // return concurrentCallWithFutures();//2: with its own virtual thread, Imperative style + // return concurrentCallFunctional();//2.1: functional style + + return concurrentCallCompletableFuture(); + } + + // runs the tasks concurrently using Virtual Threads and Completable Futures. + private String concurrentCallCompletableFuture() { + try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { + // CompletableFuture for dbCall with enhanced error handling + CompletableFuture dbCallFuture = + CompletableFuture.supplyAsync(() -> Business.blockingDbCall(2), service) + .exceptionally( + ex -> { + System.err.println( + "Exception occurred in dbCall: " + ex.getMessage()); + return "Default dbCallResult (Exception)"; + }); + + // CompletableFuture for getBrewer with error handling + CompletableFuture getBrewerFuture = + CompletableFuture.supplyAsync(() -> Business.getBrewer(), service) + .exceptionally( + ex -> { + System.err.println( + "Exception occurred in getBrewer: " + + ex.getMessage()); + return "Default brewer (Exception)"; + }); + + // CompletableFuture for getBeer with error handling + CompletableFuture getBeerFuture = + CompletableFuture.supplyAsync(() -> Business.getBeer(), service) + .exceptionally( + ex -> { + System.err.println( + "Exception occurred in getBeer: " + + ex.getMessage()); + return "Default beer (Exception)"; + }); + + // Combine results of all CompletableFuture + String output = + CompletableFuture.allOf(dbCallFuture, getBrewerFuture, getBeerFuture) + .thenApplyAsync( + voidResult -> { + String result1 = dbCallFuture.join(); + String result2 = getBrewerFuture.join(); + String result3 = getBeerFuture.join(); + return STR."[\{result1},\{result2},\{result3}]"; + }, + service) + .join(); + + System.out.println(output); + return output; + } + } + + // runs the tasks concurrently using Virtual Threads and Futures. + private String concurrentCallWithFutures() throws Exception { + // Starting 2 tasks under one thread + try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { + + long start = System.currentTimeMillis(); + // One virtual thread per task + Future dbFuture = service.submit(() -> Business.blockingDbCall(2)); + Future restFuture = service.submit(Business::getBeer); + + // The get() calls are blocking calls + String result = + String.format( + "[%s,%s,%s]", + "concurrentCallWithFutures :: ", dbFuture.get(), restFuture.get()); + + System.out.println("time = " + (System.currentTimeMillis() - start) + " ms"); + System.out.println("concurrentCallWithFutures ::" + result); + return result; + } + } + + // runs the tasks concurrently using Virtual Threads, Futures and functional style. + private String concurrentCallFunctional() throws Exception { + try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { + + String result = + service + .invokeAll( + Arrays.asList( + () -> Business.blockingDbCall(2), Business::getBeer)) + .stream() + .map( + f -> { + try { + return (String) f.get(); + } catch (Exception e) { + return null; + } + }) + .collect(Collectors.joining(",")); + + return "[" + result + "]"; + } + } + + // Request which is handled Sequentially using Virtual Threads. + private String sequentialCall() throws Exception { + long start = System.currentTimeMillis(); + + String result1 = Business.getBrewer(); + String result2 = Business.getBeer(); + + String result = String.format("[%s,%s]", result1, result2); + + long end = System.currentTimeMillis(); + System.out.println("time = " + (end - start)); + + return result; + } +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/Runner.java b/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/Runner.java index 5a4f9ccd..7603dff7 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/Runner.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v2callable/Runner.java @@ -5,21 +5,24 @@ import java.util.concurrent.ThreadFactory; /** - * A thread is assigned to each user and the thread calls the RequestHandler - * which in-turn invokes calls to database,REST api, file handling calls which are all blocking calls. + * A thread is assigned to each user and the thread calls the RequestHandler which in-turn invokes + * calls to database,REST api, file handling calls which are all blocking calls. */ public class Runner { - private static final int NUM_USERS = 1;//1_000_000; + private static final int NUM_USERS = 1; // 1_000_000; - public static void main(String[] args) { - //Creating virtual thread per taskExecutor via factory - ThreadFactory factory = Thread.ofVirtual().name("request-handler-",0).factory(); - //ThreadFactory ptFactory = Thread.ofPlatform().name("request-handler-pt-",0).factory(); - try (ExecutorService executor = Executors.newThreadPerTaskExecutor(factory)) {//One thread per user if ptFactory is used - for (int i = 0; i < NUM_USERS; i++) { - //Submit needs a callable task - executor.submit(new RequestHandler());//Controls the style from the constructor of RequestHandler - } - } - } + public static void main(String[] args) { + // Creating virtual thread per taskExecutor via factory + ThreadFactory factory = Thread.ofVirtual().name("request-handler-", 0).factory(); + // ThreadFactory ptFactory = Thread.ofPlatform().name("request-handler-pt-",0).factory(); + try (ExecutorService executor = + Executors.newThreadPerTaskExecutor( + factory)) { // One thread per user if ptFactory is used + for (int i = 0; i < NUM_USERS; i++) { + // Submit needs a callable task + executor.submit(new RequestHandler()); // Controls the style from the constructor of + // RequestHandler + } + } + } } diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/BlockingIOTasks.java b/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/BlockingIOTasks.java index df921409..75d98023 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/BlockingIOTasks.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/BlockingIOTasks.java @@ -1,11 +1,9 @@ package nitin.multithreading.cVirtualThreads.v3structuredConcurrency; import com.github.javafaker.Faker; -import lombok.AllArgsConstructor; - import java.time.Duration; import java.util.concurrent.Callable; - +import lombok.AllArgsConstructor; import nitin.exceptionHandling.customizedExceptions.BusinessException; import nitin.multithreading.cVirtualThreads.v3structuredConcurrency.BlockingIOTasks.TaskResponse; @@ -14,9 +12,9 @@ public class BlockingIOTasks implements Callable { private final String jobName; private final int time; private final boolean isSuccessful; - + // Represents successful response of the Task - public record TaskResponse(String name, String response, long timeTaken) { } + public record TaskResponse(String name, String response, long timeTaken) {} // Executes when the executorService.submit(task) is run; @Override @@ -24,19 +22,19 @@ public TaskResponse call() throws InterruptedException, BusinessException { return getTaskResponse(); } - //Body of the task which will be run on a separate Thread (mostly Virtual Thread) + // Body of the task which will be run on a separate Thread (mostly Virtual Thread) // It responds to interrupts and cleanly terminates on interruption or failure. private TaskResponse getTaskResponse() throws InterruptedException, BusinessException { logMessage("Start"); long start = System.currentTimeMillis(); - //Simulating long running task. + // Simulating long running task. for (int i = 1; i <= time; i++) { - if (Thread.interrupted()) {//Checking the interrupt + if (Thread.interrupted()) { // Checking the interrupt throwInterruptedException(); } logMessage("Working since.." + i + " seconds"); - Thread.sleep(Duration.ofSeconds(1));//Time taken for some blocking io operation + Thread.sleep(Duration.ofSeconds(1)); // Time taken for some blocking io operation } /* simulate failure of task */ @@ -47,7 +45,7 @@ private TaskResponse getTaskResponse() throws InterruptedException, BusinessExce logMessage("Complete"); long end = System.currentTimeMillis(); - //Simulating CPU intensive operation + // Simulating CPU intensive operation String fakeResponse = Faker.instance().harryPotter().character(); return new TaskResponse(this.jobName, fakeResponse, end - start); } @@ -65,4 +63,4 @@ private void throwInterruptedException() throws InterruptedException { private void logMessage(String message) { System.out.printf("%s : %s : %s\n", jobName, message, Thread.currentThread()); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/CompletionServiceRunner.java b/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/CompletionServiceRunner.java index 3dd10e39..c7f39424 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/CompletionServiceRunner.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/CompletionServiceRunner.java @@ -7,29 +7,28 @@ import java.util.concurrent.Future; public class CompletionServiceRunner { - + public static void main(String[] args) throws Exception { - //Handle parallel tasks using CompletionService. + // Handle parallel tasks using CompletionService. List result = doParallelWork(); System.out.println(STR."Parallel Work output = \{result}"); } private static List doParallelWork() throws Exception { // Create the tasks - var tasks = List.of( - new BlockingIOTasks("dbCall", 3,true), - new BlockingIOTasks("networkCall", 10,false) - ); + var tasks = + List.of( + new BlockingIOTasks("dbCall", 3, true), + new BlockingIOTasks("networkCall", 10, false)); try (var service = Executors.newVirtualThreadPerTaskExecutor()) { - CompletionService completionService = new ExecutorCompletionService(service); + CompletionService completionService = + new ExecutorCompletionService(service); - List> taskFutures - = tasks.stream() - .map(completionService::submit) - .toList(); + List> taskFutures = + tasks.stream().map(completionService::submit).toList(); try { - for(int j = 0; j < taskFutures.size() ; j++) { + for (int j = 0; j < taskFutures.size(); j++) { completionService.take().get(); } } catch (Exception e) { @@ -39,13 +38,13 @@ private static List doParallelWork() throws Except } throw e; } - + // All tasks are successful at this point - List result - = taskFutures.stream().map(Future::resultNow).toList(); - + List result = + taskFutures.stream().map(Future::resultNow).toList(); + System.out.println(result); return result; } // makes sure that all threads are fully terminated } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/StructuredTaskScopeRunner.java b/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/StructuredTaskScopeRunner.java index 3684b822..0e5ec1b9 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/StructuredTaskScopeRunner.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v3structuredConcurrency/StructuredTaskScopeRunner.java @@ -8,100 +8,111 @@ import java.util.concurrent.StructuredTaskScope.Subtask.State; public class StructuredTaskScopeRunner { - + public static void main(String[] args) throws Exception { System.out.println("Main thread : Start : " + Thread.currentThread()); - + // Simulate interrupt to the Main Thread before Child threads complete - //interruptMain(); - //shutdownOnFailure(); + // interruptMain(); + // shutdownOnFailure(); shutdownOnSuccess(); - //completeAllTasks(); + // completeAllTasks(); System.out.println("Main Thread : Complete: " + Thread.currentThread()); } private static void completeAllTasks() throws InterruptedException { - var tasks = List.of(new BlockingIOTasks("task1", 3,false), - new BlockingIOTasks("task2", 5,false)); + var tasks = + List.of( + new BlockingIOTasks("task1", 3, false), + new BlockingIOTasks("task2", 5, false)); - try(var scope = new StructuredTaskScope()) { + try (var scope = new StructuredTaskScope()) { // Start running the tasks in parallel - List> subtasks = tasks.stream().map(task -> scope.fork(task)).toList(); + List> subtasks = + tasks.stream().map(task -> scope.fork(task)).toList(); // Code to simulate random exception being thrown // This should still terminate the child threads - //if (true) { + // if (true) { // Thread.sleep(Duration.ofSeconds(2)); // throw new RuntimeException("Some Exception"); - //} + // } // Wait for all tasks to complete (success or not) scope.join(); - subtasks.stream().forEach(subTask -> { - // Handle Child Task Results (might have succeeded or failed) - State taskState = subTask.state(); - if (taskState == State.SUCCESS) - System.out.println(subTask.get()); - else if (taskState == State.FAILED) - System.out.println(subTask.exception()); - }); + subtasks.stream() + .forEach( + subTask -> { + // Handle Child Task Results (might have succeeded or failed) + State taskState = subTask.state(); + if (taskState == State.SUCCESS) System.out.println(subTask.get()); + else if (taskState == State.FAILED) + System.out.println(subTask.exception()); + }); } } - private static void shutdownOnFailure() - throws InterruptedException, ExecutionException { + private static void shutdownOnFailure() throws InterruptedException, ExecutionException { - var tasks = List.of(new BlockingIOTasks("Task#1", 3,true), - new BlockingIOTasks("Task#2", 5,true), - new BlockingIOTasks("Task#3", 7,true)); - - try(var scope = new StructuredTaskScope.ShutdownOnFailure()) { + var tasks = + List.of( + new BlockingIOTasks("Task#1", 3, true), + new BlockingIOTasks("Task#2", 5, true), + new BlockingIOTasks("Task#3", 7, true)); + + try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { // Start running the tasks in parallel - List> subtasks = tasks.stream().map(task -> scope.fork(task)).toList(); + List> subtasks = + tasks.stream().map(task -> scope.fork(task)).toList(); // Wait for all tasks to complete (success or not) scope.join(); - scope.throwIfFailed();// Wait till first Child Task fails. Send cancellation to all other Child Tasks - + scope.throwIfFailed(); // Wait till first Child Task fails. Send cancellation to all + // other Child Tasks + // Handle Success Child Task Results subtasks.forEach(System.out::println); } } - private static void shutdownOnSuccess() - throws InterruptedException, ExecutionException { - var tasks = List.of(new BlockingIOTasks("Price-1", 3, true), - new BlockingIOTasks("Price-2", 10,true)); + private static void shutdownOnSuccess() throws InterruptedException, ExecutionException { + var tasks = + List.of( + new BlockingIOTasks("Price-1", 3, true), + new BlockingIOTasks("Price-2", 10, true)); - try(var scope = new StructuredTaskScope.ShutdownOnSuccess()) { + try (var scope = + new StructuredTaskScope.ShutdownOnSuccess()) { // Start running the tasks in parallel - List> list = tasks.stream().map(task -> scope.fork(task)).toList(); - + List> list = + tasks.stream().map(task -> scope.fork(task)).toList(); + // Wait till first Child Task Succeeds. Send Cancellation // to all other Child Tasks scope.join(); - + // Handle Successful Child Task BlockingIOTasks.TaskResponse result = scope.result(); System.out.println(result); } } - + private static void interruptMain() { - + Thread mainThread = Thread.currentThread(); - Thread.ofPlatform().start(() -> { - - try { - Thread.sleep(Duration.ofSeconds(2)); - mainThread.interrupt(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); + Thread.ofPlatform() + .start( + () -> { + try { + Thread.sleep(Duration.ofSeconds(2)); + mainThread.interrupt(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T0ThreadLocal.java b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T0ThreadLocal.java index f9f3b793..1ff0ef73 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T0ThreadLocal.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T0ThreadLocal.java @@ -3,8 +3,8 @@ import nitin.multithreading.cVirtualThreads.Student; /** - * Simple example with a Single Thread. Demonstrates use of Thread Local - * as an implicit parameter in whole method stack + * Simple example with a Single Thread. Demonstrates use of Thread Local as an implicit parameter in + * whole method stack */ public class T0ThreadLocal { @@ -13,7 +13,8 @@ public class T0ThreadLocal { public static void main(String[] args) { mainThread(); handleUser(); - System.out.println(STR."\{studentThreadLocal.get()}Nitin\{studentThreadLocal.get().getName()}"); + System.out.println( + STR."\{studentThreadLocal.get()}Nitin\{studentThreadLocal.get().getName()}"); } private static void mainThread() { @@ -31,6 +32,4 @@ private static void handleUser() { public static void print(String m) { System.out.printf("[%s] %s\n", Thread.currentThread().getName(), m); } - } - diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T1ThreadLocal.java b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T1ThreadLocal.java index f452721b..490fc413 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T1ThreadLocal.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T1ThreadLocal.java @@ -1,29 +1,35 @@ package nitin.multithreading.cVirtualThreads.v4threadLocals; -import nitin.multithreading.cVirtualThreads.Student; import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class T1ThreadLocal { // Main and Child Thread can set different User object in Threadlocal public static final ThreadLocal studentThreadLocal = new ThreadLocal(); - + public static void main(String[] args) throws InterruptedException { - //setStudentInAThread(student,"Harry Potter"); + // setStudentInAThread(student,"Harry Potter"); logShortMessage("Initial => " + studentThreadLocal.get()); // Main thread sets the user - studentThreadLocal.set(Student.builder().name("Harry Potter").build());//Creating a new instance + studentThreadLocal.set( + Student.builder().name("Harry Potter").build()); // Creating a new instance logShortMessage("Final => " + studentThreadLocal.get()); // Start a Child Thread - Thread thread = Thread.ofVirtual().start(() -> { - Thread.currentThread().setName("ron"); - //setStudentInAThread(student,"Ron Weasley"); - logShortMessage("Initial => " + studentThreadLocal.get()); - //studentThreadLocal.set(Student.builder().name("Ron Weasley").build());//Creating a new instance - studentThreadLocal.get().setName("Ron Weasley"); - logShortMessage("Final => " + studentThreadLocal.get()); - }); - + Thread thread = + Thread.ofVirtual() + .start( + () -> { + Thread.currentThread().setName("ron"); + // setStudentInAThread(student,"Ron Weasley"); + logShortMessage("Initial => " + studentThreadLocal.get()); + // studentThreadLocal.set(Student.builder().name("Ron + // Weasley").build());//Creating a new instance + studentThreadLocal.get().setName("Ron Weasley"); + logShortMessage("Final => " + studentThreadLocal.get()); + }); + thread.join(); logShortMessage(STR."Finally => \{studentThreadLocal.get()}"); } diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T2ThreadLocalWithInitial.java b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T2ThreadLocalWithInitial.java index 73f0105d..c8511ed7 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T2ThreadLocalWithInitial.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T2ThreadLocalWithInitial.java @@ -1,29 +1,38 @@ package nitin.multithreading.cVirtualThreads.v4threadLocals; -import nitin.multithreading.cVirtualThreads.Student; import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class T2ThreadLocalWithInitial { // With Default Initial Value using a Supplier // The Supplier is called when calling get() // After remove(), if get() is called again, the supplier will be invoked Again - public static final ThreadLocal studentThreadLocal = ThreadLocal.withInitial(() -> new Student("Albus Dumbledore")); - + public static final ThreadLocal studentThreadLocal = + ThreadLocal.withInitial(() -> new Student("Albus Dumbledore")); + public static void main(String[] args) throws InterruptedException { logShortMessage("Initial => " + studentThreadLocal.get()); // Main thread sets the user - studentThreadLocal.set(Student.builder().name("Harry Potter").build());//Creating a new instance + studentThreadLocal.set( + Student.builder().name("Harry Potter").build()); // Creating a new instance logShortMessage("Final => " + studentThreadLocal.get()); // Start a Child Thread - Thread thread = Thread.ofPlatform().start(() -> { - Thread.currentThread().setName("ron"); - logShortMessage("Initial => " + studentThreadLocal.get()); - // Main thread sets the user - studentThreadLocal.set(Student.builder().name("Ron Weasley").build());//Creating a new instance - logShortMessage("Final => " + studentThreadLocal.get()); - }); - + Thread thread = + Thread.ofPlatform() + .start( + () -> { + Thread.currentThread().setName("ron"); + logShortMessage("Initial => " + studentThreadLocal.get()); + // Main thread sets the user + studentThreadLocal.set( + Student.builder() + .name("Ron Weasley") + .build()); // Creating a new instance + logShortMessage("Final => " + studentThreadLocal.get()); + }); + thread.join(); logShortMessage(STR."Finally => \{studentThreadLocal.get()}"); studentThreadLocal.remove(); diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T3InheritableThreadLocal.java b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T3InheritableThreadLocal.java index 494031c0..4bd2047e 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T3InheritableThreadLocal.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T3InheritableThreadLocal.java @@ -1,32 +1,50 @@ package nitin.multithreading.cVirtualThreads.v4threadLocals; -import nitin.multithreading.cVirtualThreads.Student; import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class T3InheritableThreadLocal { // Child thread will see the thread local values of the Parent. // Thread local map is automatically copied when the child thread is created - public static final InheritableThreadLocal studentInheritableThreadLocal = new InheritableThreadLocal<>(); - + public static final InheritableThreadLocal studentInheritableThreadLocal = + new InheritableThreadLocal<>(); + public static void main(String[] args) throws InterruptedException { logShortMessage("Initial => " + studentInheritableThreadLocal.get()); // Main thread sets the user - studentInheritableThreadLocal.set(Student.builder().name("Harry Potter").build());//First getting the parent object then mutating it. + studentInheritableThreadLocal.set( + Student.builder() + .name("Harry Potter") + .build()); // First getting the parent object then mutating it. logShortMessage("Final => " + studentInheritableThreadLocal.get()); - // Start a Child Thread - Thread thread = Thread.ofVirtual().start(() -> { - Thread.currentThread().setName("ron"); - logShortMessage("Initial => " + studentInheritableThreadLocal.get()); - //This DOES NOT CHANGE THE PARENT VALUE - //studentInheritableThreadLocal.set(new Student("Ron Weasley"));//Creating a new instance of Student and assigning to the child thread. - studentInheritableThreadLocal.get().setName("Ron Weasley");//First getting the parent object then mutating it. - logShortMessage("Final => " + studentInheritableThreadLocal.get()); - }); + Thread thread = + Thread.ofVirtual() + .start( + () -> { + Thread.currentThread().setName("ron"); + logShortMessage( + "Initial => " + studentInheritableThreadLocal.get()); + // This DOES NOT CHANGE THE PARENT VALUE + // studentInheritableThreadLocal.set(new Student("Ron + // Weasley"));//Creating a new instance of Student and assigning + // to the child thread. + studentInheritableThreadLocal + .get() + .setName("Ron Weasley"); // First getting the parent + // object then mutating it. + logShortMessage( + "Final => " + studentInheritableThreadLocal.get()); + }); thread.join(); - logShortMessage(STR."Finally => \{studentInheritableThreadLocal.get()}");//Since child thread set a new name, parent should reflect the same + logShortMessage( + STR."Finally => \{ + studentInheritableThreadLocal + .get()}"); // Since child thread set a new name, parent should + // reflect the same } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T4InheritableThreadLocalDeepCopy.java b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T4InheritableThreadLocalDeepCopy.java index 021e9dcf..5e802856 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T4InheritableThreadLocalDeepCopy.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/T4InheritableThreadLocalDeepCopy.java @@ -1,40 +1,49 @@ package nitin.multithreading.cVirtualThreads.v4threadLocals; -import nitin.multithreading.cVirtualThreads.Student; import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class T4InheritableThreadLocalDeepCopy { // deep copy ONLY WHEN childValue() method is used - public static final InheritableThreadLocal studentDeepCopy = new InheritableThreadLocal() { - @Override - protected Student childValue(Student parentValue) { - // Create a deep copy of the parent value for the child thread - return new Student(parentValue.getName()); - } - - @Override - protected Student initialValue() { - return new Student("Albus Dumbledore"); - } - }; - + public static final InheritableThreadLocal studentDeepCopy = + new InheritableThreadLocal() { + @Override + protected Student childValue(Student parentValue) { + // Create a deep copy of the parent value for the child thread + return new Student(parentValue.getName()); + } + + @Override + protected Student initialValue() { + return new Student("Albus Dumbledore"); + } + }; + public static void main(String[] args) throws InterruptedException { logShortMessage("Initial => " + studentDeepCopy.get()); // Main thread sets the user - studentDeepCopy.set(Student.builder().name("Harry Potter").build());//Creating a new instance + studentDeepCopy.set( + Student.builder().name("Harry Potter").build()); // Creating a new instance logShortMessage("Final => " + studentDeepCopy.get()); // Start a Child Thread - Thread thread = Thread.ofVirtual().start(() -> { - Thread.currentThread().setName("ron"); - logShortMessage("Initial => " + studentDeepCopy.get()); - // Main thread sets the user - studentDeepCopy.set(Student.builder().name("Ron Weasley").build());//Creating a new instance - logShortMessage("Final => " + studentDeepCopy.get()); - }); + Thread thread = + Thread.ofVirtual() + .start( + () -> { + Thread.currentThread().setName("ron"); + logShortMessage("Initial => " + studentDeepCopy.get()); + // Main thread sets the user + studentDeepCopy.set( + Student.builder() + .name("Ron Weasley") + .build()); // Creating a new instance + logShortMessage("Final => " + studentDeepCopy.get()); + }); thread.join(); logShortMessage(STR."Finally => \{studentDeepCopy.get()}"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/UserHandler.java b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/UserHandler.java index 73a8ccc4..8630bc15 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/UserHandler.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v4threadLocals/UserHandler.java @@ -7,12 +7,11 @@ public class UserHandler { public void handle() { Student requestStudent = T0ThreadLocal.studentThreadLocal.get(); print("handle - User => " + requestStudent); - + // handle user 'requestUser' } public static void print(String m) { T0ThreadLocal.print(m); } - -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S1ScopedValue.java b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S1ScopedValue.java index 57e3e8b7..237495ab 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S1ScopedValue.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S1ScopedValue.java @@ -1,30 +1,34 @@ package nitin.multithreading.cVirtualThreads.v5scopedvalue; -import nitin.multithreading.cVirtualThreads.Student; import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class S1ScopedValue { - //Not yet bound + // Not yet bound public static final ScopedValue studentScopedValue = ScopedValue.newInstance(); - + public static void main(String[] args) throws Exception { logShortMessage("isBound? " + studentScopedValue.isBound()); Student hp = new Student("Harry Potter"); - boolean result //bind a key (studentScopedValue) to a value (hp) with an operation op (handleUser()) - = ScopedValue.callWhere(studentScopedValue, hp, S1ScopedValue::handleUser);//using a callable - + boolean result // bind a key (studentScopedValue) to a value (hp) with an operation op + // (handleUser()) + = + ScopedValue.callWhere( + studentScopedValue, hp, S1ScopedValue::handleUser); // using a callable + // boolean result = handleUser(); logShortMessage("Result: " + result); logShortMessage("isBound? " + studentScopedValue.isBound()); - //logShortMessage("Finally: " + studentScopedValue.get()); - //Exception in thread "main" java.util.NoSuchElementException + // logShortMessage("Finally: " + studentScopedValue.get()); + // Exception in thread "main" java.util.NoSuchElementException // at java.base/java.lang.ScopedValue.slowGet(ScopedValue.java:700) } - + private static boolean handleUser() { ScopedUserHandler handler = new ScopedUserHandler(); return handler.handle(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S2ScopedValueRebind.java b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S2ScopedValueRebind.java index fd4aae09..b8bbcc89 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S2ScopedValueRebind.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S2ScopedValueRebind.java @@ -1,31 +1,39 @@ package nitin.multithreading.cVirtualThreads.v5scopedvalue; -import nitin.multithreading.cVirtualThreads.Student; - import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class S2ScopedValueRebind { - + public static ScopedValue studentScopedValue = ScopedValue.newInstance(); - + public static void main(String[] args) throws Exception { - logShortMessage("isBound? " + studentScopedValue.isBound());//False - outside the dynamic scope of the method + logShortMessage( + "isBound? " + + studentScopedValue + .isBound()); // False - outside the dynamic scope of the method Student hp = new Student("Harry Potter"); ScopedValue.runWhere(studentScopedValue, hp, S2ScopedValueRebind::runnableVoidMethod); - logShortMessage("isBound? " + studentScopedValue.isBound());//False - outside the dynamic scope of the method + logShortMessage( + "isBound? " + + studentScopedValue + .isBound()); // False - outside the dynamic scope of the method } - + private static void runnableVoidMethod() { logShortMessage("handleUser - isBound? " + studentScopedValue.isBound()); logShortMessage("handleUser - " + studentScopedValue.get()); - ScopedValue.runWhere(studentScopedValue, new Student("Default Student"),//Rebinding + ScopedValue.runWhere( + studentScopedValue, + new Student("Default Student"), // Rebinding S2ScopedValueRebind::anonylousCall); logShortMessage("handleUser - " + studentScopedValue.get()); } - + private static void anonylousCall() { logShortMessage("callAsAnonymous - isBound? " + studentScopedValue.isBound()); logShortMessage("callAsAnonymous - " + studentScopedValue.get()); - } + } } diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S3ScopedValueInheritance.java b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S3ScopedValueInheritance.java index 36e98603..8df0fa46 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S3ScopedValueInheritance.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S3ScopedValueInheritance.java @@ -1,31 +1,32 @@ package nitin.multithreading.cVirtualThreads.v5scopedvalue; -import nitin.multithreading.cVirtualThreads.Student; - import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; + public class S3ScopedValueInheritance { public static ScopedValue studentScopedValue = ScopedValue.newInstance(); - + public static void main(String[] args) throws Exception { - ScopedValue - .where(studentScopedValue, new Student("Harry Potter")) - .run(S3ScopedValueInheritance::invokeThread); + ScopedValue.where(studentScopedValue, new Student("Harry Potter")) + .run(S3ScopedValueInheritance::invokeThread); } - + private static void invokeThread() { try { logShortMessage("isBound? " + studentScopedValue.isBound()); Student reqStudent = studentScopedValue.get(); logShortMessage("invokeThread - user " + reqStudent); - //Starting a new named child Thread - Thread thread = Thread.ofVirtual().name("hp-thread").start(()->getHarryPotter()); - //Connecting with the main thread + // Starting a new named child Thread + Thread thread = Thread.ofVirtual().name("hp-thread").start(() -> getHarryPotter()); + // Connecting with the main thread thread.join(); logShortMessage("invokeThread - user " + reqStudent); - } catch (InterruptedException exp) { /* do something */ } + } catch (InterruptedException exp) { + /* do something */ + } } private static void getHarryPotter() { diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S4ScopedValueStructuredTaskScope.java b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S4ScopedValueStructuredTaskScope.java index b893f21c..797fe15b 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S4ScopedValueStructuredTaskScope.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/S4ScopedValueStructuredTaskScope.java @@ -1,38 +1,41 @@ package nitin.multithreading.cVirtualThreads.v5scopedvalue; -import nitin.multithreading.cVirtualThreads.Student; +import static com.utilities.MultiThreadUtility.logShortMessage; + import java.util.concurrent.StructuredTaskScope; import java.util.concurrent.ThreadFactory; - -import static com.utilities.MultiThreadUtility.logShortMessage; +import nitin.multithreading.cVirtualThreads.Student; public class S4ScopedValueStructuredTaskScope { public static final ScopedValue studentScopedValue = ScopedValue.newInstance(); public static void main(String[] args) throws Exception { - ScopedValue - .where(studentScopedValue, new Student("Harry Potter")) + ScopedValue.where(studentScopedValue, new Student("Harry Potter")) .call(S4ScopedValueStructuredTaskScope::invokeTaskScope); } private static String invokeTaskScope() throws InterruptedException { - ThreadFactory factory = Thread.ofVirtual().name("child-",0).factory(); - try (var scope = new StructuredTaskScope("child-scope", factory)) {// + ThreadFactory factory = Thread.ofVirtual().name("child-", 0).factory(); + try (var scope = new StructuredTaskScope("child-scope", factory)) { // - scope.fork(() -> { - Student reqUser = studentScopedValue.orElse(new Student("Ron Weasley")); - logShortMessage("invokeTaskScope - user " + reqUser); + scope.fork( + () -> { + Student reqUser = studentScopedValue.orElse(new Student("Ron Weasley")); + logShortMessage("invokeTaskScope - user " + reqUser); - // set the Id for the user - reqUser.setName("Jennie");//Changing the Parent thread value - return "done"; - }); + // set the Id for the user + reqUser.setName("Jennie"); // Changing the Parent thread value + return "done"; + }); scope.join(); - }//All child threads finish in the structured task scope. Child thread can't run beyond Parent thread + } // All child threads finish in the structured task scope. Child thread can't run beyond + // Parent thread - Student reqUser = studentScopedValue.orElse(new Student("Ron Weasley"));//Set new if there is nothing returned + Student reqUser = + studentScopedValue.orElse( + new Student("Ron Weasley")); // Set new if there is nothing returned logShortMessage("invokeTaskScope - user " + reqUser); return "done"; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/ScopedUserHandler.java b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/ScopedUserHandler.java index 90843e1c..4c28be88 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/ScopedUserHandler.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v5scopedvalue/ScopedUserHandler.java @@ -1,10 +1,9 @@ package nitin.multithreading.cVirtualThreads.v5scopedvalue; +import static com.utilities.MultiThreadUtility.logShortMessage; import nitin.multithreading.cVirtualThreads.Student; -import static com.utilities.MultiThreadUtility.logShortMessage; - public class ScopedUserHandler { public boolean handle() { @@ -15,7 +14,7 @@ public boolean handle() { Student requestStudent = S1ScopedValue.studentScopedValue.get(); logShortMessage("handle - User: " + requestStudent); } - + return bound; } } diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C1ContinuationsAsCoroutines.java b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C1ContinuationsAsCoroutines.java index 8c591281..d0119021 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C1ContinuationsAsCoroutines.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C1ContinuationsAsCoroutines.java @@ -1,45 +1,46 @@ package nitin.multithreading.cVirtualThreads.v6DelimitedContinuations; -import jdk.internal.vm.Continuation; -import jdk.internal.vm.ContinuationScope; - -import java.time.Duration; -import java.time.ZonedDateTime; import static com.utilities.MultiThreadUtility.logShortMessage; import static com.utilities.ZonedDateTimeUtility.zonedDateTimeStr; +import java.time.Duration; +import java.time.ZonedDateTime; +import jdk.internal.vm.Continuation; +import jdk.internal.vm.ContinuationScope; + public class C1ContinuationsAsCoroutines { private static final ContinuationScope SCOPE = new ContinuationScope("scope"); // --add-exports java.base/jdk.internal.vm=ALL-UNNAMED in the grdle build package - //Package 'jdk.internal.vm' is declared in module 'java.base', which does not export it to the unnamed module + // Package 'jdk.internal.vm' is declared in module 'java.base', which does not export it to the + // unnamed module public static void main(String[] args) throws Exception { logShortMessage("Main method : START"); - Continuation continuation = new Continuation(SCOPE, C1ContinuationsAsCoroutines::continuationMethod); - while (!continuation.isDone()) {//Run as long as Continuations are running. - continuation.run();//Run with each Continuation.yield method + Continuation continuation = + new Continuation(SCOPE, C1ContinuationsAsCoroutines::continuationMethod); + while (!continuation.isDone()) { // Run as long as Continuations are running. + continuation.run(); // Run with each Continuation.yield method logShortMessage("##### Continuation loop #####"); Thread.sleep(Duration.ofSeconds(3)); } logShortMessage("Main method : END"); } - private static void continuationMethod() { logShortMessage("continuationMethod : enter"); Incrementer incrementer = new Incrementer(1, zonedDateTimeStr(ZonedDateTime.now())); logShortMessage("State 1 : " + incrementer); - //Restores the state - Continuation.yield(SCOPE);//Run until here and send the control back to the main method + // Restores the state + Continuation.yield(SCOPE); // Run until here and send the control back to the main method - //Restore from previous point, Resumes the state + // Restore from previous point, Resumes the state modifyIncrementer(incrementer); logShortMessage("State 2 : " + incrementer); Continuation.yield(SCOPE); - //Restore from previous point, Resumes the state + // Restore from previous point, Resumes the state modifyIncrementer(incrementer); logShortMessage("State 3 : " + incrementer); Continuation.yield(SCOPE); @@ -51,4 +52,4 @@ private static void modifyIncrementer(Incrementer incrementer) { incrementer.setCounter(incrementer.getCounter() + 1); incrementer.setTimeOfIncrement(zonedDateTimeStr(ZonedDateTime.now())); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C2CascadingContinuationsCallingObjects.java b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C2CascadingContinuationsCallingObjects.java index d5edc660..1d329763 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C2CascadingContinuationsCallingObjects.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/C2CascadingContinuationsCallingObjects.java @@ -1,17 +1,18 @@ package nitin.multithreading.cVirtualThreads.v6DelimitedContinuations; -import jdk.internal.vm.Continuation; -import jdk.internal.vm.ContinuationScope; - -import java.time.Duration; import static com.utilities.MultiThreadUtility.logShortMessage; +import java.time.Duration; +import jdk.internal.vm.Continuation; +import jdk.internal.vm.ContinuationScope; + public class C2CascadingContinuationsCallingObjects { private static final ContinuationScope SCOPE = new ContinuationScope("scope"); public static void main(String[] args) throws Exception { logShortMessage("Main method : START"); - Continuation c = new Continuation(SCOPE, new RunnableContinuationProcessor());//Calling an object + Continuation c = + new Continuation(SCOPE, new RunnableContinuationProcessor()); // Calling an object while (!c.isDone()) { c.run(); logShortMessage(">> main : scope1 loop"); @@ -19,4 +20,4 @@ public static void main(String[] args) throws Exception { } logShortMessage("main : exit"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/Incrementer.java b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/Incrementer.java index a8ac9265..ef038d23 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/Incrementer.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/Incrementer.java @@ -6,9 +6,10 @@ import lombok.ToString; @Data -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@NoArgsConstructor @ToString public class Incrementer { int counter; String timeOfIncrement; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/RunnableContinuationProcessor.java b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/RunnableContinuationProcessor.java index 11212798..d37ceb1f 100644 --- a/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/RunnableContinuationProcessor.java +++ b/src/main/java/nitin/multithreading/cVirtualThreads/v6DelimitedContinuations/RunnableContinuationProcessor.java @@ -1,13 +1,12 @@ package nitin.multithreading.cVirtualThreads.v6DelimitedContinuations; -import jdk.internal.vm.Continuation; -import jdk.internal.vm.ContinuationScope; - -import java.time.ZonedDateTime; - import static com.utilities.MultiThreadUtility.logShortMessage; import static com.utilities.ZonedDateTimeUtility.zonedDateTimeStr; +import java.time.ZonedDateTime; +import jdk.internal.vm.Continuation; +import jdk.internal.vm.ContinuationScope; + public class RunnableContinuationProcessor implements Runnable { private static final ContinuationScope SCOPE = new ContinuationScope("newScope"); @@ -28,21 +27,20 @@ private void method() { logShortMessage("RunnableContinuationProcessor.run : exit"); } - private void continuationMethod() { logShortMessage("RunnableContinuationProcessor.continuationMethod : enter"); Incrementer incrementer = new Incrementer(1, zonedDateTimeStr(ZonedDateTime.now())); logShortMessage("State 1 : " + incrementer); - //Restores the state - Continuation.yield(SCOPE);//Run until here and send the control back to the main method + // Restores the state + Continuation.yield(SCOPE); // Run until here and send the control back to the main method - //Restore from previous point, Resumes the state + // Restore from previous point, Resumes the state modifyIncrementer(incrementer); logShortMessage("State 2 : " + incrementer); Continuation.yield(SCOPE); - //Restore from previous point, Resumes the state + // Restore from previous point, Resumes the state modifyIncrementer(incrementer); logShortMessage("State 3 : " + incrementer); Continuation.yield(SCOPE); diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C1ReentrantLock.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C1ReentrantLock.java index df3a8226..7485f0a8 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C1ReentrantLock.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C1ReentrantLock.java @@ -3,14 +3,12 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -/** - * Created by Nitin C on 12/5/2015. - */ +/** Created by Nitin C on 12/5/2015. */ public class C1ReentrantLock { public static void main(String[] args) { RLock r = new RLock(); - //Three threads competiting for the same a5object + // Three threads competiting for the same a5object Thread t1 = new Thread(r); Thread t2 = new Thread(r); Thread t3 = new Thread(r); @@ -20,7 +18,6 @@ public static void main(String[] args) { t3.start(); System.out.println(t1.getState()); - } } @@ -34,7 +31,7 @@ public void run() { l.tryLock(); System.out.println("Locked by: " + Thread.currentThread()); - //After Locking make it sleep, so that other threads can get chance + // After Locking make it sleep, so that other threads can get chance try { Thread.sleep(2000); System.out.println("Waiting with thread: " + Thread.currentThread()); diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C2ReadWriteLock.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C2ReadWriteLock.java index da8d0bee..78dbe975 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C2ReadWriteLock.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/C2ReadWriteLock.java @@ -1,20 +1,17 @@ package nitin.multithreading.raceCondition.bReentrantLocks; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.concurrent.locks.ReadWriteLock; import static com.utilities.MultiThreadUtility.logShortMessage; -/** - * Created by Nitin C on 12/5/2015. - * Modified on Aug 11 2024 - */ +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +/** Created by Nitin C on 12/5/2015. Modified on Aug 11 2024 */ public class C2ReadWriteLock { private final ReadWriteLock lock = new ReentrantReadWriteLock(); Lock readLock = lock.readLock(); Lock writeLock = lock.writeLock(); - private int value = 0;//Shared Resource + private int value = 0; // Shared Resource public static void main(String[] args) { C2ReadWriteLock example = new C2ReadWriteLock(); diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/MyTryLockWithArgumentDemoThread.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/MyTryLockWithArgumentDemoThread.java index ede4c8f0..447654d8 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/MyTryLockWithArgumentDemoThread.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/MyTryLockWithArgumentDemoThread.java @@ -3,14 +3,12 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class MyTryLockWithArgumentDemoThread extends Thread { static ReentrantLock l = new ReentrantLock(); - //Constructor + // Constructor MyTryLockWithArgumentDemoThread(String name) { super(name); } @@ -18,24 +16,27 @@ public class MyTryLockWithArgumentDemoThread extends Thread { public void run() { do { try { - if (l.tryLock(3000, TimeUnit.MILLISECONDS)) {//will try for lock every 3 seconds - System.out.println(Thread.currentThread().getName() + "... got Lock and performing Safe Operations"); + if (l.tryLock(3000, TimeUnit.MILLISECONDS)) { // will try for lock every 3 seconds + System.out.println( + Thread.currentThread().getName() + + "... got Lock and performing Safe Operations"); try { Thread.sleep(30000); } catch (InterruptedException e) { - //Swallowing Exception + // Swallowing Exception } l.unlock(); System.out.println(Thread.currentThread().getName() + " ... Released Lock"); break; } else { - System.out.println(Thread.currentThread().getName() + "....unable to get lock and hence performinng alternative operations"); + System.out.println( + Thread.currentThread().getName() + + "....unable to get lock and hence performinng alternative operations"); } } catch (InterruptedException e) { e.printStackTrace(); } - } - while (true); + } while (true); } } diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/aRELBasics.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/aRELBasics.java index 4e01a92e..dec4ba5f 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/aRELBasics.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/aRELBasics.java @@ -2,25 +2,22 @@ import java.util.concurrent.locks.ReentrantLock; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class aRELBasics { public static void main(String[] args) { ReentrantLock l = new ReentrantLock(); l.lock(); l.lock(); - System.out.println(l.isLocked());//true - System.out.println(l.isHeldByCurrentThread());//true - System.out.println(l.getQueueLength());//0 + System.out.println(l.isLocked()); // true + System.out.println(l.isHeldByCurrentThread()); // true + System.out.println(l.getQueueLength()); // 0 l.unlock(); - System.out.println(l.getHoldCount());//1 - System.out.println(l.isLocked());//true + System.out.println(l.getHoldCount()); // 1 + System.out.println(l.isLocked()); // true l.unlock(); - System.out.println(l.isLocked());//false - System.out.println(l.isFair());//false : Default Value - + System.out.println(l.isLocked()); // false + System.out.println(l.isFair()); // false : Default Value } } diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/atmExample/MyATM.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/atmExample/MyATM.java index 0bfb5a5f..fef07e49 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/atmExample/MyATM.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/atmExample/MyATM.java @@ -15,7 +15,6 @@ public int withdraw(int amount) { int temp = balance; lock.lock(); - lock.unlock(); return temp; } @@ -24,7 +23,6 @@ public int deposit(int amount) { int temp = balance; lock.lock(); - lock.unlock(); return temp; } diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/cTryLockDemo.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/cTryLockDemo.java index c98c07de..21bdd4f7 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/cTryLockDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/cTryLockDemo.java @@ -1,8 +1,6 @@ package nitin.multithreading.raceCondition.bReentrantLocks; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class cTryLockDemo { public static void main(String[] args) { /* @@ -13,5 +11,4 @@ public static void main(String[] args) { t1.start(); t2.start(); */ } - } diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/dTryLockArgumentDemo.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/dTryLockArgumentDemo.java index ecf4632c..8d0d0137 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/dTryLockArgumentDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/dTryLockArgumentDemo.java @@ -2,8 +2,8 @@ /** * Created by nitin.chaurasia on 12/26/2016. - *

- * Second thread will continue to pull if the Lock is available or not + * + *

Second thread will continue to pull if the Lock is available or not */ public class dTryLockArgumentDemo { public static void main(String[] args) { diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/Display.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/Display.java index de0bf86e..be22f14e 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/Display.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/Display.java @@ -2,9 +2,7 @@ import java.util.concurrent.locks.ReentrantLock; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class Display { ReentrantLock l = new ReentrantLock(); @@ -15,7 +13,7 @@ public void wishReentrantLocked(String name) { for (int i = 0; i < 10; i++) { System.out.print("Good Morning : "); try { - Thread.sleep(500);//wait for two secs + Thread.sleep(500); // wait for two secs } catch (InterruptedException e) { e.printStackTrace(); } @@ -24,12 +22,12 @@ public void wishReentrantLocked(String name) { l.unlock(); } - //With the use of synchronized, we are forcing the other thread to wait + // With the use of synchronized, we are forcing the other thread to wait public synchronized void wishSynchronized(String name) { for (int i = 0; i < 10; i++) { System.out.print("Good Morning : "); try { - Thread.sleep(500);//wait for two secs + Thread.sleep(500); // wait for two secs } catch (InterruptedException e) { e.printStackTrace(); } diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyReentrantDemoThread.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyReentrantDemoThread.java index f13055cd..06eb6938 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyReentrantDemoThread.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyReentrantDemoThread.java @@ -1,8 +1,6 @@ package nitin.multithreading.raceCondition.bReentrantLocks.reEntrantDemo; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class MyReentrantDemoThread extends Thread { Display d; diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyTryLockDemoThread.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyTryLockDemoThread.java index 78bfcbd1..65398901 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyTryLockDemoThread.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/MyTryLockDemoThread.java @@ -2,29 +2,31 @@ import java.util.concurrent.locks.ReentrantLock; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class MyTryLockDemoThread extends Thread { static ReentrantLock l = new ReentrantLock(); - //Constructor + // Constructor MyTryLockDemoThread(String name) { super(name); } public void run() { if (l.tryLock()) { - System.out.println(Thread.currentThread().getName() + "... got Lock and performing Safe Operations"); + System.out.println( + Thread.currentThread().getName() + + "... got Lock and performing Safe Operations"); try { Thread.sleep(500); } catch (InterruptedException e) { - //Swallowing Exception + // Swallowing Exception } l.unlock(); } else { - System.out.println(Thread.currentThread().getName() + "....unable to get lock and hence performinng alternative operations"); + System.out.println( + Thread.currentThread().getName() + + "....unable to get lock and hence performinng alternative operations"); } } } diff --git a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/bReentrantDemo.java b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/bReentrantDemo.java index 8df0fc7e..c965bf40 100644 --- a/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/bReentrantDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/bReentrantLocks/reEntrantDemo/bReentrantDemo.java @@ -1,8 +1,6 @@ package nitin.multithreading.raceCondition.bReentrantLocks.reEntrantDemo; -/** - * Created by nitin.chaurasia on 12/26/2016. - */ +/** Created by nitin.chaurasia on 12/26/2016. */ public class bReentrantDemo { public static void main(String[] args) { Display d = new Display(); diff --git a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/I3NotifyAll.java b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/I3NotifyAll.java index a22e80b4..78025f1c 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/I3NotifyAll.java +++ b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/I3NotifyAll.java @@ -1,10 +1,8 @@ package nitin.multithreading.raceCondition.dInterThreadComm; -/** - * Created by Nitin Chaurasia on 12/4/15 at 1:32 AM. - */ +/** Created by Nitin Chaurasia on 12/4/15 at 1:32 AM. */ public class I3NotifyAll { - //To control the Flow. Just by using Join it did not work + // To control the Flow. Just by using Join it did not work int status = 1; public static void main(String[] args) throws InterruptedException { @@ -24,4 +22,3 @@ public static void main(String[] args) throws InterruptedException { c.join(); } } - diff --git a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player1.java b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player1.java index 41e2a346..21cf25b8 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player1.java +++ b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player1.java @@ -16,7 +16,6 @@ public void run() { try { synchronized (notifyAllExample) { - for (int i = 0; i < 100; i++) { while (notifyAllExample.status != 1) { diff --git a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player2.java b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player2.java index 0e23ef2d..f75aba7a 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player2.java +++ b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player2.java @@ -16,11 +16,10 @@ public void run() { try { synchronized (notifyAllExample) { - for (int i = 0; i < 100; i++) { while (notifyAllExample.status != 2) { - notifyAllExample.wait(); // wait and notify method are from object class + notifyAllExample.wait(); // wait and notify method are from object class // sleep method is from thread class // sleep method never releases the lock } @@ -40,5 +39,4 @@ public void run() { } System.out.println("total score by b : " + totalscore); } - } diff --git a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player3.java b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player3.java index a64ddbd1..83127d2f 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player3.java +++ b/src/main/java/nitin/multithreading/raceCondition/dInterThreadComm/Player3.java @@ -17,10 +17,9 @@ public void run() { try { synchronized (notifyAllExample) { - for (int i = 0; i < 100; i++) { - while (notifyAllExample.status != 3) {//Runs only when status is 1 or 2 + while (notifyAllExample.status != 3) { // Runs only when status is 1 or 2 notifyAllExample.wait(); } @@ -31,7 +30,6 @@ public void run() { notifyAllExample.status = 1; notifyAllExample.notifyAll(); } - } } catch (Exception e) { System.out.println("Exception 3 :" + e.getMessage()); diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C3CountDownLatch.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C3CountDownLatch.java index 249b46d1..8da8b803 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C3CountDownLatch.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C3CountDownLatch.java @@ -1,7 +1,4 @@ package nitin.multithreading.raceCondition.dSynchronization; -/** - * Created by Nitin C on 12/5/2015. - */ -public class C3CountDownLatch { -} +/** Created by Nitin C on 12/5/2015. */ +public class C3CountDownLatch {} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C4CyclicBarrier.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C4CyclicBarrier.java index 80bdcd41..ce699e49 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C4CyclicBarrier.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/C4CyclicBarrier.java @@ -5,9 +5,7 @@ import java.util.logging.Level; import java.util.logging.Logger; -/** - * Created by Nitin C on 12/5/2015. - */ +/** Created by Nitin C on 12/5/2015. */ public class C4CyclicBarrier { int i = 0; @@ -15,16 +13,17 @@ public static void main(String[] args) { // Number of threads that need to wait at the barrier final int numThreads = 3; - //creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await() - final CyclicBarrier cb = new CyclicBarrier(numThreads, (() -> { + // creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await() + final CyclicBarrier cb = + new CyclicBarrier( + numThreads, + (() -> { + // This task will be executed once all thread reaches barrier + System.out.println("All parties are arrived at barrier, lets play"); + })); - //This task will be executed once all thread reaches barrier - System.out.println("All parties are arrived at barrier, lets play"); - - })); - - //starting each of thread + // starting each of thread Thread t1 = new Thread(new Task(cb), "Thread 1"); Thread t2 = new Thread(new Task(cb), "Thread 2"); Thread t3 = new Thread(new Task(cb), "Thread 3"); @@ -32,11 +31,9 @@ public static void main(String[] args) { t1.start(); t2.start(); t3.start(); - } - - //Runnable task for each thread + // Runnable task for each thread private static class Task implements Runnable { private final CyclicBarrier barrier; @@ -45,13 +42,13 @@ public Task(CyclicBarrier barrier) { this.barrier = barrier; } - public void run() { try { for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + " is waiting on barrier"); barrier.await(); - System.out.println(Thread.currentThread().getName() + " has crossed the barrier"); + System.out.println( + Thread.currentThread().getName() + " has crossed the barrier"); barrier.await(); } } catch (InterruptedException ex) { @@ -61,6 +58,4 @@ public void run() { } } } - - } diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/DatabaseOperations.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/DatabaseOperations.java index d08e56ea..18632019 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/DatabaseOperations.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/DatabaseOperations.java @@ -1,15 +1,14 @@ package nitin.multithreading.raceCondition.dSynchronization; -import lombok.NoArgsConstructor; - import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; +import lombok.NoArgsConstructor; -//Run all the database operation in parallel +// Run all the database operation in parallel @NoArgsConstructor public class DatabaseOperations { public void performTask(CyclicBarrier c1, CyclicBarrier c2) { - try {//to be used for cyclic barrier + try { // to be used for cyclic barrier getDriver(); establishConnection(); c1.await(); @@ -21,7 +20,6 @@ public void performTask(CyclicBarrier c1, CyclicBarrier c2) { } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } - } private void getDriver() { @@ -29,11 +27,14 @@ private void getDriver() { } private void establishConnection() { - System.out.println("Establish Connection using Connection Class by : " + Thread.currentThread()); + System.out.println( + "Establish Connection using Connection Class by : " + Thread.currentThread()); } private void prepareStatement() { - System.out.println("Prepare an SQL Statement to be executed on the DB Server by : " + Thread.currentThread()); + System.out.println( + "Prepare an SQL Statement to be executed on the DB Server by : " + + Thread.currentThread()); } private void obtainResultSet() { @@ -41,15 +42,18 @@ private void obtainResultSet() { } private void closeConnection() { - System.out.println("After obtaining the result, Close the connection by : " + Thread.currentThread()); + System.out.println( + "After obtaining the result, Close the connection by : " + Thread.currentThread()); } private void summary() { - System.out.println("By : " + Thread.currentThread() + - "\n1. Obtain DRIVER \n" + - "2. Estb. CONNECTION \n" + - "3. Write SQL STATEMENT \n" + - "4. Obtain result in RESULTSET \n" + - "5. Close the connection"); + System.out.println( + "By : " + + Thread.currentThread() + + "\n1. Obtain DRIVER \n" + + "2. Estb. CONNECTION \n" + + "3. Write SQL STATEMENT \n" + + "4. Obtain result in RESULTSET \n" + + "5. Close the connection"); } } diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCountDownLatch.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCountDownLatch.java index b0970d8f..9e28d101 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCountDownLatch.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCountDownLatch.java @@ -1,6 +1,5 @@ package nitin.multithreading.raceCondition.dSynchronization; - import java.util.concurrent.CountDownLatch; public class IncrementTaskCountDownLatch implements Runnable { @@ -17,4 +16,4 @@ public void run() { sharedCounter.increment(); latch.countDown(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCyclicBarrier.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCyclicBarrier.java index ecd7180b..9b234deb 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCyclicBarrier.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskCyclicBarrier.java @@ -21,4 +21,4 @@ public void run() { e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskSemaphore.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskSemaphore.java index 39e0097f..a1af8723 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskSemaphore.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/IncrementTaskSemaphore.java @@ -22,4 +22,4 @@ public void run() { semaphore.release(); // Release the permit } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/M1CyclicBarriar.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/M1CyclicBarriar.java index 9ef89ec7..b9ee3026 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/M1CyclicBarriar.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/M1CyclicBarriar.java @@ -1,33 +1,36 @@ package nitin.multithreading.raceCondition.dSynchronization; -import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Nitin C on 3/5/2016. - *

- * A CyclicBarrier takes in its constructor a limit value, indicating the number of threads to wait for - * As each thread finishes, it calls the await() method on the CyclicBarrier. Once the specified number of threads - * have each called await(), the barrier is released, and all the threads can continue - *

- * DEADLOCK CONDITION: Set the available thread to be atleast as large as your Cyclic barrier limit value, else - * the code will hang indefinitely. THE BARRIER WILL NEVER BE REACHED - *

- * After the cyclic barrier is broken, all threads are released adn the number of threads waiting on the CyclicBarrier - * goes back to 0. eg: # threads = 15, CyclicBarrier = 5; CyclicBarrier will be activated a total of 3 times + * + *

A CyclicBarrier takes in its constructor a limit value, indicating the number of threads to + * wait for As each thread finishes, it calls the await() method on the CyclicBarrier. Once the + * specified number of threads have each called await(), the barrier is released, and all the + * threads can continue + * + *

DEADLOCK CONDITION: Set the available thread to be atleast as large as your Cyclic barrier + * limit value, else the code will hang indefinitely. THE BARRIER WILL NEVER BE REACHED + * + *

After the cyclic barrier is broken, all threads are released adn the number of threads waiting + * on the CyclicBarrier goes back to 0. eg: # threads = 15, CyclicBarrier = 5; CyclicBarrier will be + * activated a total of 3 times */ public class M1CyclicBarriar { // Executing the database operation by 5 threads public static void main(String[] args) { DatabaseOperations databaseOperations = new DatabaseOperations(); - try(ExecutorService executorService = Executors.newFixedThreadPool(5)) { + try (ExecutorService executorService = Executors.newFixedThreadPool(5)) { - // Creating the barrier for more number of threads (eg 10 in this case) HALTS THE PROGRAM. DEADLOCK SITUATION + // Creating the barrier for more number of threads (eg 10 in this case) HALTS THE + // PROGRAM. DEADLOCK SITUATION CyclicBarrier c1 = new CyclicBarrier(5); - CyclicBarrier c2 = new CyclicBarrier(4, () -> System.out.println("**** CONNECTION ESTBD ****")); + CyclicBarrier c2 = + new CyclicBarrier(4, () -> System.out.println("**** CONNECTION ESTBD ****")); for (int i = 0; i < 1; i++) { executorService.submit(() -> databaseOperations.performTask(c1, c2)); @@ -35,4 +38,3 @@ public static void main(String[] args) { } } } - diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/Processor.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/Processor.java index 338ce200..9503dec2 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/Processor.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/Processor.java @@ -1,9 +1,9 @@ package nitin.multithreading.raceCondition.dSynchronization; -import java.util.concurrent.CountDownLatch; - import static com.utilities.MultiThreadUtility.logMessage; +import java.util.concurrent.CountDownLatch; + public class Processor implements Runnable { private final CountDownLatch latch; @@ -11,7 +11,6 @@ public class Processor implements Runnable { this.latch = latch; } - @Override public void run() { logMessage("Started."); diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblems.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblems.java index e9041bf9..0281e540 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblems.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblems.java @@ -1,43 +1,43 @@ package nitin.multithreading.raceCondition.dSynchronization; import com.utilities.MultiThreadUtility; - import java.util.ArrayList; import java.util.List; import java.util.Random; /** - * Created by Nitin Chaurasia on 3/25/18 at 12:58 AM. - * Demo that the value of a counter is not incremented properly + * Created by Nitin Chaurasia on 3/25/18 at 12:58 AM. Demo that the value of a counter is not + * incremented properly */ public class S0NonSyncProblems { - private static int counter = 0;//Shared Variable + private static int counter = 0; // Shared Variable static ArrayList counterValues = new ArrayList<>(100); public static void main(String[] args) throws InterruptedException { - List threads = new ArrayList<>();; + List threads = new ArrayList<>(); + ; for (int i = 0; i < 100; i++) { - //100 threads trying to fill values in the array + // 100 threads trying to fill values in the array Thread t1 = new Thread(S0NonSyncProblems::task); t1.setName(STR."thread:\{i}"); threads.add(t1); } - for(Thread thread : threads){ + for (Thread thread : threads) { thread.start(); } - for(Thread thread : threads){ + for (Thread thread : threads) { thread.join(); } System.out.println("Finished execution : " + counterValues.size()); - //System.out.println(counterValues); + // System.out.println(counterValues); } private static void task() { - MultiThreadUtility.delay(new Random().nextInt(1000));//Random delay + MultiThreadUtility.delay(new Random().nextInt(1000)); // Random delay counterValues.add(++counter); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblemsSolved.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblemsSolved.java index 20a7d004..337aa52e 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblemsSolved.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0NonSyncProblemsSolved.java @@ -3,26 +3,24 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by Nitin Chaurasia on 3/25/18 at 1:07 AM. - */ +/** Created by Nitin Chaurasia on 3/25/18 at 1:07 AM. */ public class S0NonSyncProblemsSolved { - private static int counter = 0;//Common Resource + private static int counter = 0; // Common Resource static ArrayList counterValues = new ArrayList<>(); static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { - List processThreads = createThreads(100);//100 threads + List processThreads = createThreads(100); // 100 threads - //Start all threads - for(Thread thread : processThreads) - thread.start(); + // Start all threads + for (Thread thread : processThreads) thread.start(); - //Wait for all the threads to be over - for(Thread thread : processThreads) - thread.join(); + // Wait for all the threads to be over + for (Thread thread : processThreads) thread.join(); - System.out.println("Finished execution : " + counterValues.size());//Does not guarantee correct result each time + System.out.println( + "Finished execution : " + + counterValues.size()); // Does not guarantee correct result each time System.out.println(counterValues); } @@ -35,12 +33,12 @@ public static List createThreads(int numberOfThreads) { return threads; } - //Forcing only one thread at a time. Expensive operation + // Forcing only one thread at a time. Expensive operation public static void counter() { - synchronized (lock){ + synchronized (lock) { ++counter; counterValues.add(counter); } - //counterValues.add(counter);////Does not guarantee correct result each time + // counterValues.add(counter);////Does not guarantee correct result each time } } diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0SynchBasics.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0SynchBasics.java index 6481b414..fcf528a9 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0SynchBasics.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S0SynchBasics.java @@ -2,33 +2,38 @@ /** * Created by Nitin Chaurasia on 12/6/15 at 6:14 PM. - *

- * Synchronize acquire Locks on the Object instance and not on the method. Thus If one Lock is acquired by - * thread t1 for method m1, no other threads are allowed to execute even the non-sync method m3. * - *The lock is specific to the instance of the class. If you have multiple instances of Basics, + *

Synchronize acquire Locks on the Object instance and not on the method. Thus If one Lock is + * acquired by thread t1 for method m1, no other threads are allowed to execute even the non-sync + * method m3. + * + *

The lock is specific to the instance of the class. If you have multiple instances of Basics, * each instance has its own lock. Synchronization only applies to methods on the same instance. * - * Non-Synchronized Methods: These methods do not acquire the same lock and can - * be executed concurrently with synchronized methods or by other threads.\ + *

Non-Synchronized Methods: These methods do not acquire the same lock and can be executed + * concurrently with synchronized methods or by other threads.\ */ public class S0SynchBasics { public static void main(String[] args) throws InterruptedException { Basics basics = new Basics(); - Thread t1 = new Thread(() -> { - System.out.println("Thread 1 started."); - basics.m1(); - basics.m3(); - System.out.println("Thread 1 finished."); - }); + Thread t1 = + new Thread( + () -> { + System.out.println("Thread 1 started."); + basics.m1(); + basics.m3(); + System.out.println("Thread 1 finished."); + }); - Thread t2 = new Thread(() -> { - System.out.println("Thread 2 started."); - basics.m2(); - basics.m3(); - System.out.println("Thread 2 finished."); - }); + Thread t2 = + new Thread( + () -> { + System.out.println("Thread 2 started."); + basics.m2(); + basics.m3(); + System.out.println("Thread 2 finished."); + }); t1.start(); t2.start(); @@ -37,4 +42,3 @@ public static void main(String[] args) throws InterruptedException { t2.join(); } } - diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S1StaticSyncMethod.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S1StaticSyncMethod.java index f72f8627..de541207 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S1StaticSyncMethod.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S1StaticSyncMethod.java @@ -1,8 +1,6 @@ package nitin.multithreading.raceCondition.dSynchronization; -/** - * Created by Nitin Chaurasia on 12/6/15 at 7:03 PM. - */ +/** Created by Nitin Chaurasia on 12/6/15 at 7:03 PM. */ public class S1StaticSyncMethod { public static void main(String[] args) { Display d1 = new Display(); @@ -11,16 +9,16 @@ public static void main(String[] args) { Thread t1 = new MyThread(d1, "Thread1"); Thread t2 = new MyThread(d1, "Thread2"); -// t1.start(); -// t2.start(); + // t1.start(); + // t2.start(); caseStudy1(); } /** - * WHENEVER MULTIPLE THREADS ARE OPERATING ON SAME OBJECT, THEN ONLY SYNCHRONIZATION - * PLAYS A ROLE. IF THERE ARE TWO DIFFERENT OBJECTS ACCESSED MY TWO DIFFERENT THREADS - * THSRE IS NO ROLE OF SYNCHRONIZATION. + * WHENEVER MULTIPLE THREADS ARE OPERATING ON SAME OBJECT, THEN ONLY SYNCHRONIZATION PLAYS A + * ROLE. IF THERE ARE TWO DIFFERENT OBJECTS ACCESSED MY TWO DIFFERENT THREADS THSRE IS NO ROLE + * OF SYNCHRONIZATION. */ private static void caseStudy1() { Display1 d1 = new Display1(); @@ -39,16 +37,13 @@ private static void caseStudy1() { class Display1 { /** - * The Static Sync method puts a class level lock. - * When a thread executes a static Sync method then remaining threads are not allowed to - * execute ANY static Sync Method of that class simultaneously. - *

- * BUT remaining threads can execute following methods - * 1. normal static - * 2. normal instance - * 3. synchronized instance + * The Static Sync method puts a class level lock. When a thread executes a static Sync method + * then remaining threads are not allowed to execute ANY static Sync Method of that class + * simultaneously. + * + *

BUT remaining threads can execute following methods 1. normal static 2. normal instance 3. + * synchronized instance */ - public static synchronized void wish(String name) throws InterruptedException { for (int i = 0; i < 10; i++) { System.out.print("Hello - " + i); diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S2SyncInstanceMethods.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S2SyncInstanceMethods.java index 1197c995..ddbdbde6 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S2SyncInstanceMethods.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S2SyncInstanceMethods.java @@ -1,8 +1,6 @@ package nitin.multithreading.raceCondition.dSynchronization; -/** - * Created by Nitin Chaurasia on 12/3/15 at 6:02 AM. - */ +/** Created by Nitin Chaurasia on 12/3/15 at 6:02 AM. */ public class S2SyncInstanceMethods { public static void main(String[] args) throws InterruptedException { Worker w = new Worker(); @@ -10,7 +8,7 @@ public static void main(String[] args) throws InterruptedException { long start = System.currentTimeMillis(); - //10 Threads operating concurrently on a same a5object + // 10 Threads operating concurrently on a same a5object for (int i = 0; i < 10; i++) { t[i] = new Thread(w); t[i].start(); @@ -19,7 +17,7 @@ public static void main(String[] args) throws InterruptedException { // If join is not used, main thread will continue executing and count would be 0; // Thus wait here untill all the threads are done and then execute the sout w.count for (int i = 0; i < 10; i++) { - t[i].join();// Throws Interrupted Exception + t[i].join(); // Throws Interrupted Exception } long end = System.currentTimeMillis(); @@ -29,19 +27,20 @@ public static void main(String[] args) throws InterruptedException { } class Worker implements Runnable { - //Variable residing in the Heap, shared among all the threads + // Variable residing in the Heap, shared among all the threads int count = 0; @Override public void run() { for (int i = 0; i < 10000; i++) { // This is problamatic because concurrent executions may drop some changes - //count++; + // count++; count(); } } - //Synchronize will make sure that the value of count is always accessed by only one thread at once + // Synchronize will make sure that the value of count is always accessed by only one thread at + // once // This will increase the time of execution // Not using suync will decrease the reliability of the results. private void count() { diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S3SynchronizedMethodDemo.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S3SynchronizedMethodDemo.java index f33b687b..ab887936 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S3SynchronizedMethodDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S3SynchronizedMethodDemo.java @@ -1,8 +1,6 @@ package nitin.multithreading.raceCondition.dSynchronization; -/** - * Created by Nitin Chaurasia on 12/3/15 at 10:29 PM. - */ +/** Created by Nitin Chaurasia on 12/3/15 at 10:29 PM. */ public class S3SynchronizedMethodDemo { public static void main(String[] args) { Display d1 = new Display(); @@ -11,16 +9,16 @@ public static void main(String[] args) { Thread t1 = new MyThread(d1, "Thread1"); Thread t2 = new MyThread(d1, "Thread2"); -// t1.start(); -// t2.start(); + // t1.start(); + // t2.start(); caseStudy1(); } /** - * WHENEVER MULTIPLE THREADS ARE OPERATING ON SAME OBJECT, THEN ONLY SYNCHRONIZATION - * PLAYS A ROLE. IF THERE ARE TWO DIFFERENT OBJECTS ACCESSED bY TWO DIFFERENT THREADS - * THSRE IS NO ROLE OF SYNCHRONIZATION. + * WHENEVER MULTIPLE THREADS ARE OPERATING ON SAME OBJECT, THEN ONLY SYNCHRONIZATION PLAYS A + * ROLE. IF THERE ARE TWO DIFFERENT OBJECTS ACCESSED bY TWO DIFFERENT THREADS THSRE IS NO ROLE + * OF SYNCHRONIZATION. */ private static void caseStudy1() { Display d1 = new Display(); @@ -37,7 +35,7 @@ private static void caseStudy1() { class Display { - //If the synchronized method does not allow two simultaneous threads to execute + // If the synchronized method does not allow two simultaneous threads to execute // TRY: remove the synchronized keyword and see the effects; public synchronized void wish(String name) throws InterruptedException { for (int i = 0; i < 10; i++) { diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S4SynchronizedBlockDemo.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S4SynchronizedBlockDemo.java index d4a7f7e6..842a3c53 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S4SynchronizedBlockDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S4SynchronizedBlockDemo.java @@ -2,12 +2,10 @@ /** * Created by Nitin Chaurasia on 12/3/15 at 11:01 PM. - *

- * Synchronized(this) - To get lock on current a5object - * Synchronized(obj) - To get lock on obj + * + *

Synchronized(this) - To get lock on current a5object Synchronized(obj) - To get lock on obj * Synchronized(classname.class) - To get a class level Lock */ public class S4SynchronizedBlockDemo { - public static void main(String[] args) { - } -} \ No newline at end of file + public static void main(String[] args) {} +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S7CountDownLatch.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S7CountDownLatch.java index 598e0ef9..e087acd0 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S7CountDownLatch.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/S7CountDownLatch.java @@ -1,17 +1,15 @@ package nitin.multithreading.raceCondition.dSynchronization; -import com.utilities.MultiThreadUtility; +import static com.utilities.MultiThreadUtility.logMessage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import static com.utilities.MultiThreadUtility.logMessage; - /** * Created by Nitin Chaurasia on 12/5/15 at 10:39 PM. - *

- * Demonstrating + * + *

Demonstrating */ public class S7CountDownLatch { public static void main(String[] args) { @@ -32,14 +30,15 @@ public static void main(String[] args) { // Main thread waits until all worker threads have finished logMessage("Main thread is waiting for workers to finish."); try { - latch.await(); // This will block until latch count reaches zero + latch.await(); // This will block until latch count reaches zero } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.out.println("Main thread was interrupted while waiting."); } logMessage("All workers have finished. Main thread resumes."); } catch (Exception e) { - System.out.println("An error occurred while creating the ExecutorService: " + e.getMessage()); + System.out.println( + "An error occurred while creating the ExecutorService: " + e.getMessage()); } } @@ -57,4 +56,4 @@ private static void task(int workerId, CountDownLatch latch) { latch.countDown(); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedCounter.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedCounter.java index eaeaccb6..10b093d3 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedCounter.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedCounter.java @@ -5,7 +5,8 @@ public class SharedCounter { public void increment() { counter++; - System.out.println(Thread.currentThread().getName() + " incremented counter to: " + counter); + System.out.println( + Thread.currentThread().getName() + " incremented counter to: " + counter); } public int getCounter() { diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedResources.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedResources.java index f47785bf..07e0b136 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedResources.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/SharedResources.java @@ -2,18 +2,24 @@ public class SharedResources { public static void main(String[] args) throws InterruptedException { - InventoryCounter inventoryCounter = new InventoryCounter();//Shared resource + InventoryCounter inventoryCounter = new InventoryCounter(); // Shared resource - Thread incrementingThread = new Thread(() -> { - for (int i = 0; i < 10000; i++) { - inventoryCounter.incrementSynchronized();//inventoryCounter.increment(); - } - }); - Thread decrementingThread = new Thread(() -> { - for (int i = 0; i < 10000; i++) { - inventoryCounter.decrementSynchronized();//inventoryCounter.decrement(); - } - }); + Thread incrementingThread = + new Thread( + () -> { + for (int i = 0; i < 10000; i++) { + inventoryCounter + .incrementSynchronized(); // inventoryCounter.increment(); + } + }); + Thread decrementingThread = + new Thread( + () -> { + for (int i = 0; i < 10000; i++) { + inventoryCounter + .decrementSynchronized(); // inventoryCounter.decrement(); + } + }); incrementingThread.start(); decrementingThread.start(); @@ -48,16 +54,15 @@ public int getItemsSynchronized() { } public void increment() { - items++; + items++; } public void decrement() { - items--; + items--; } public int getItems() { return items; } } - -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CountdownLatchRunner.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CountdownLatchRunner.java index 60afbd8c..a308d0e8 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CountdownLatchRunner.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CountdownLatchRunner.java @@ -1,10 +1,9 @@ package nitin.multithreading.raceCondition.dSynchronization.runners; +import java.util.concurrent.CountDownLatch; import nitin.multithreading.raceCondition.dSynchronization.IncrementTaskCountDownLatch; import nitin.multithreading.raceCondition.dSynchronization.SharedCounter; -import java.util.concurrent.CountDownLatch; - public class CountdownLatchRunner { public static void main(String[] args) { SharedCounter sharedCounter = new SharedCounter(); @@ -12,7 +11,10 @@ public static void main(String[] args) { // Create 1000 tasks to increment the counter for (int i = 0; i < 1000; i++) { - Thread t = new Thread(new IncrementTaskCountDownLatch(sharedCounter, latch), "Thread " + (i + 1)); + Thread t = + new Thread( + new IncrementTaskCountDownLatch(sharedCounter, latch), + "Thread " + (i + 1)); t.start(); } diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CyclicBarrierRunner.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CyclicBarrierRunner.java index 43d66621..616b6f86 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CyclicBarrierRunner.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/CyclicBarrierRunner.java @@ -1,20 +1,25 @@ package nitin.multithreading.raceCondition.dSynchronization.runners; +import java.util.concurrent.CyclicBarrier; import nitin.multithreading.raceCondition.dSynchronization.IncrementTaskCyclicBarrier; import nitin.multithreading.raceCondition.dSynchronization.SharedCounter; -import java.util.concurrent.CyclicBarrier; - public class CyclicBarrierRunner { public static void main(String[] args) { SharedCounter sharedCounter = new SharedCounter(); - CyclicBarrier barrier = new CyclicBarrier(1000, () -> { - System.out.println("All threads reached the barrier"); - }); + CyclicBarrier barrier = + new CyclicBarrier( + 1000, + () -> { + System.out.println("All threads reached the barrier"); + }); // Create 1000 tasks to increment the counter for (int i = 0; i < 1000; i++) { - Thread t = new Thread(new IncrementTaskCyclicBarrier(sharedCounter, barrier), "Thread " + (i + 1)); + Thread t = + new Thread( + new IncrementTaskCyclicBarrier(sharedCounter, barrier), + "Thread " + (i + 1)); t.start(); } } diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/MutExRunner.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/MutExRunner.java index d700becb..6d7b1923 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/MutExRunner.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/MutExRunner.java @@ -1,10 +1,9 @@ package nitin.multithreading.raceCondition.dSynchronization.runners; -import nitin.multithreading.raceCondition.dSynchronization.IncrementTaskMutex; -import nitin.multithreading.raceCondition.dSynchronization.SharedCounter; - import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import nitin.multithreading.raceCondition.dSynchronization.IncrementTaskMutex; +import nitin.multithreading.raceCondition.dSynchronization.SharedCounter; public class MutExRunner { public static void main(String[] args) { @@ -26,4 +25,4 @@ public static void main(String[] args) { System.out.println("Final Counter: " + sharedCounter.getCounter()); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/SemaphoreRunner.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/SemaphoreRunner.java index 953ded24..26c9b156 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/SemaphoreRunner.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/runners/SemaphoreRunner.java @@ -1,11 +1,10 @@ package nitin.multithreading.raceCondition.dSynchronization.runners; -import nitin.multithreading.raceCondition.dSynchronization.IncrementTaskSemaphore; -import nitin.multithreading.raceCondition.dSynchronization.SharedCounter; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; +import nitin.multithreading.raceCondition.dSynchronization.IncrementTaskSemaphore; +import nitin.multithreading.raceCondition.dSynchronization.SharedCounter; public class SemaphoreRunner { public static void main(String[] args) { @@ -29,4 +28,4 @@ public static void main(String[] args) { System.out.println(STR."Final Counter: \{sharedCounter.getCounter()}"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikes.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikes.java index 035172d2..6c45d2cb 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikes.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikes.java @@ -1,8 +1,7 @@ package nitin.multithreading.raceCondition.dSynchronization.tests; - public class IncrementLikes { - private Integer likes = Integer.valueOf(0);//Initialzying from zero + private Integer likes = Integer.valueOf(0); // Initialzying from zero public Integer getCurrentLikesCount() { return likes; @@ -11,4 +10,4 @@ public Integer getCurrentLikesCount() { public Integer incrementLikes() { return likes++; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSemaphores.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSemaphores.java index 456c3adb..ccb41817 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSemaphores.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSemaphores.java @@ -3,7 +3,7 @@ import java.util.concurrent.Semaphore; public class IncrementLikesSemaphores extends IncrementLikes { - private final Semaphore semaphore = new Semaphore(1);//1 thread means it behaves as mutex. + private final Semaphore semaphore = new Semaphore(1); // 1 thread means it behaves as mutex. private final Integer likeBigDecimal = super.getCurrentLikesCount(); diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSynchronized.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSynchronized.java index da06c6e1..83af9bb8 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSynchronized.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/IncrementLikesSynchronized.java @@ -1,11 +1,9 @@ package nitin.multithreading.raceCondition.dSynchronization.tests; -import java.math.BigDecimal; - public class IncrementLikesSynchronized extends IncrementLikes { @Override public synchronized Integer incrementLikes() { return super.incrementLikes(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/Runner.java b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/Runner.java index af59e0e0..85fe6a4f 100644 --- a/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/Runner.java +++ b/src/main/java/nitin/multithreading/raceCondition/dSynchronization/tests/Runner.java @@ -1,10 +1,8 @@ package nitin.multithreading.raceCondition.dSynchronization.tests; -import lombok.NoArgsConstructor; -import lombok.RequiredArgsConstructor; - import java.util.*; import java.util.concurrent.*; +import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class Runner { @@ -15,7 +13,8 @@ public static void main(String[] args) throws ExecutionException, InterruptedExc Set uniqueSequences = getLikes(count, il); } - private static Set getLikes(int count, IncrementLikes il) throws InterruptedException, ExecutionException { + private static Set getLikes(int count, IncrementLikes il) + throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(10); Set uniqueSequences = new LinkedHashSet<>(); List> futures = new ArrayList<>(); @@ -26,7 +25,9 @@ private static Set getLikes(int count, IncrementLikes il) throws Interr } for (Future future : futures) { - Integer result = future.resultNow();//Future returns the datatype of the method thats been multithreaded + Integer result = + future.resultNow(); // Future returns the datatype of the method thats been + // multithreaded System.out.println("Result from Future " + result); uniqueSequences.add(result); } diff --git a/src/main/java/nitin/multithreading/raceCondition/deadLocks/DeadLockDemo.java b/src/main/java/nitin/multithreading/raceCondition/deadLocks/DeadLockDemo.java index b1e9cb41..db0b2c31 100644 --- a/src/main/java/nitin/multithreading/raceCondition/deadLocks/DeadLockDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/deadLocks/DeadLockDemo.java @@ -1,19 +1,17 @@ package nitin.multithreading.raceCondition.deadLocks; -import java.util.Random; - public class DeadLockDemo { /* - = - = - = -=======X====== - = - = - = - */ + = + = + = + =======X====== + = + = + = + */ public static void main(String[] args) { - //Intersection intersection = new IntersectionSync(); + // Intersection intersection = new IntersectionSync(); Intersection intersection = new IntersectionReentrantLocks(); Thread trainAThread = new Thread(() -> new Train(intersection, true).run(), "TrainA"); @@ -22,4 +20,4 @@ public static void main(String[] args) { trainAThread.start(); trainBThread.start(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/deadLocks/Intersection.java b/src/main/java/nitin/multithreading/raceCondition/deadLocks/Intersection.java index d54e8358..1037a8a4 100644 --- a/src/main/java/nitin/multithreading/raceCondition/deadLocks/Intersection.java +++ b/src/main/java/nitin/multithreading/raceCondition/deadLocks/Intersection.java @@ -2,6 +2,8 @@ public interface Intersection { public void takeNorthSouthTrack(); + public void takeEastWestTrack(); + public void passingTrain(); } diff --git a/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionReentrantLocks.java b/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionReentrantLocks.java index 0d9b8396..882f88e5 100644 --- a/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionReentrantLocks.java +++ b/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionReentrantLocks.java @@ -3,45 +3,45 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -public class IntersectionReentrantLocks implements Intersection{ - private final Lock northSouthLock = new ReentrantLock(); - private final Lock eastWestLock = new ReentrantLock(); +public class IntersectionReentrantLocks implements Intersection { + private final Lock northSouthLock = new ReentrantLock(); + private final Lock eastWestLock = new ReentrantLock(); - @Override - public void takeNorthSouthTrack() { - // Acquire locks in a consistent order to avoid deadlock - northSouthLock.lock(); + @Override + public void takeNorthSouthTrack() { + // Acquire locks in a consistent order to avoid deadlock + northSouthLock.lock(); + try { + System.out.println("NorthSouthTrack is GREEN : " + Thread.currentThread().getName()); + eastWestLock.lock(); try { - System.out.println("NorthSouthTrack is GREEN : " + Thread.currentThread().getName()); - eastWestLock.lock(); - try { - System.out.println("Train is passing through NorthSouthTrack"); - passingTrain(); - } finally { - eastWestLock.unlock(); - } + System.out.println("Train is passing through NorthSouthTrack"); + passingTrain(); } finally { - northSouthLock.unlock(); + eastWestLock.unlock(); } + } finally { + northSouthLock.unlock(); } + } - @Override - public void takeEastWestTrack() { - // Acquire locks in a consistent order to avoid deadlock - eastWestLock.lock();//Still deadlocks + @Override + public void takeEastWestTrack() { + // Acquire locks in a consistent order to avoid deadlock + eastWestLock.lock(); // Still deadlocks + try { + System.out.println("EastWestTrack is GREEN " + Thread.currentThread().getName()); + northSouthLock.lock(); try { - System.out.println("EastWestTrack is GREEN " + Thread.currentThread().getName()); - northSouthLock.lock(); - try { - System.out.println("Train is passing through EastWestTrack"); - passingTrain(); - } finally { - northSouthLock.unlock(); - } + System.out.println("Train is passing through EastWestTrack"); + passingTrain(); } finally { - eastWestLock.unlock(); + northSouthLock.unlock(); } + } finally { + eastWestLock.unlock(); } + } @Override public void passingTrain() { @@ -51,4 +51,4 @@ public void passingTrain() { Thread.currentThread().interrupt(); // Restore interrupted status } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionSync.java b/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionSync.java index 858ae7df..59fb7a0b 100644 --- a/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionSync.java +++ b/src/main/java/nitin/multithreading/raceCondition/deadLocks/IntersectionSync.java @@ -1,13 +1,14 @@ package nitin.multithreading.raceCondition.deadLocks; public class IntersectionSync implements Intersection { - private final Object northSouthLock = new Object();//Arbitrary object + private final Object northSouthLock = new Object(); // Arbitrary object private final Object eastWestLock = new Object(); @Override public void takeNorthSouthTrack() { synchronized (northSouthLock) { - System.out.println("NorthSouthTrack is locked by thread " + Thread.currentThread().getName()); + System.out.println( + "NorthSouthTrack is locked by thread " + Thread.currentThread().getName()); synchronized (eastWestLock) { System.out.println("Train is passing through NorthSouthTrack"); passingTrain(); @@ -17,8 +18,10 @@ public void takeNorthSouthTrack() { @Override public void takeEastWestTrack() { - synchronized (northSouthLock ) {//This will result in a deadlock. To avoid, keep the same sequence of Locks everywhere - System.out.println("EastWestTrack is locked by thread " + Thread.currentThread().getName()); + synchronized (northSouthLock) { // This will result in a deadlock. To avoid, keep the same + // sequence of Locks everywhere + System.out.println( + "EastWestTrack is locked by thread " + Thread.currentThread().getName()); synchronized (eastWestLock) { System.out.println("Train is passing through EastWestTrack"); passingTrain(); @@ -34,4 +37,4 @@ public void passingTrain() { Thread.currentThread().interrupt(); // Restore interrupted status } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/deadLocks/Train.java b/src/main/java/nitin/multithreading/raceCondition/deadLocks/Train.java index b37ed764..f83e253a 100644 --- a/src/main/java/nitin/multithreading/raceCondition/deadLocks/Train.java +++ b/src/main/java/nitin/multithreading/raceCondition/deadLocks/Train.java @@ -3,33 +3,33 @@ import java.util.Random; public class Train { - private final Intersection intersection; - private final boolean useNorthSouthTrack; - private final Random random = new Random(); + private final Intersection intersection; + private final boolean useNorthSouthTrack; + private final Random random = new Random(); - public Train(Intersection intersection, boolean useNorthSouthTrack) { - this.intersection = intersection; - this.useNorthSouthTrack = useNorthSouthTrack; - } + public Train(Intersection intersection, boolean useNorthSouthTrack) { + this.intersection = intersection; + this.useNorthSouthTrack = useNorthSouthTrack; + } - public void run() { - while (true) { - sleepRandomTime(); - if (useNorthSouthTrack) { - intersection.takeNorthSouthTrack(); - } else { - intersection.takeEastWestTrack(); - } + public void run() { + while (true) { + sleepRandomTime(); + if (useNorthSouthTrack) { + intersection.takeNorthSouthTrack(); + } else { + intersection.takeEastWestTrack(); } } + } - private void sleepRandomTime() { - try { - Thread.sleep(random.nextInt(5)); - //Thread.sleep(10000); + private void sleepRandomTime() { + try { + Thread.sleep(random.nextInt(5)); + // Thread.sleep(10000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); // Restore interrupted status - } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // Restore interrupted status } } +} diff --git a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRace.java b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRace.java index 6a01474e..15b7f01a 100644 --- a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRace.java +++ b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRace.java @@ -3,7 +3,7 @@ import static com.utilities.MultiThreadUtility.logShortMessage; public class DataRace { - //Data race can avoided by declaring the variables volatile + // Data race can avoided by declaring the variables volatile private volatile int x = 0; private volatile int y = 0; @@ -17,4 +17,4 @@ public void checkForDataRace() { logShortMessage("y > x - Data Race is detected" + " x = " + x + ", y = " + y); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRaceRunner.java b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRaceRunner.java index 4941b0ab..b861a610 100644 --- a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRaceRunner.java +++ b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/DataRaceRunner.java @@ -3,19 +3,23 @@ public class DataRaceRunner { public static void main(String[] args) { DataRace sharedClass = new DataRace(); - Thread thread1 = new Thread(() -> { - for (int i = 0; i < Integer.MAX_VALUE; i++) { - sharedClass.increment(); - } - }); + Thread thread1 = + new Thread( + () -> { + for (int i = 0; i < Integer.MAX_VALUE; i++) { + sharedClass.increment(); + } + }); - Thread checkerThread = new Thread(() -> { - for (int i = 0; i < Integer.MAX_VALUE; i++) { - sharedClass.checkForDataRace(); - } - }); + Thread checkerThread = + new Thread( + () -> { + for (int i = 0; i < Integer.MAX_VALUE; i++) { + sharedClass.checkForDataRace(); + } + }); thread1.start(); checkerThread.start(); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/R2Volatile.java b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/R2Volatile.java index dfc61ad4..e20e516c 100644 --- a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/R2Volatile.java +++ b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/R2Volatile.java @@ -1,9 +1,6 @@ package nitin.multithreading.raceCondition.eVolatileVar; -/** - * Created by Nitin Chaurasia on 12/3/15 at 6:31 AM. - * Modified on Aug 12 2024 - */ +/** Created by Nitin Chaurasia on 12/3/15 at 6:31 AM. Modified on Aug 12 2024 */ public class R2Volatile { public static void main(String[] args) throws InterruptedException { VolatileTest c = new VolatileTest(); @@ -12,7 +9,7 @@ public static void main(String[] args) throws InterruptedException { t[i] = new Thread(() -> c.task()); } for (int i = 0; i < 20; i++) { - t[i].setName("thread-"+i); + t[i].setName("thread-" + i); t[i].start(); } @@ -21,4 +18,4 @@ public static void main(String[] args) throws InterruptedException { // System.out.println("ss"); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatilePerformanceTest.java b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatilePerformanceTest.java index 757c0631..0110dca9 100644 --- a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatilePerformanceTest.java +++ b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatilePerformanceTest.java @@ -23,12 +23,14 @@ public void testVolatileReadWrite() { Thread[] threads = new Thread[NUM_THREADS]; long startTime = System.nanoTime(); for (int i = 0; i < NUM_THREADS; i++) { - threads[i] = new Thread(() -> { - for (int j = 0; j < NUM_ITERATIONS; j++) { - volatileCounter++; // Write - volatileCounter--; // Read - } - }); + threads[i] = + new Thread( + () -> { + for (int j = 0; j < NUM_ITERATIONS; j++) { + volatileCounter++; // Write + volatileCounter--; // Read + } + }); threads[i].start(); } @@ -53,12 +55,14 @@ public void testNonVolatileReadWrite() { Thread[] threads = new Thread[NUM_THREADS]; long startTime = System.nanoTime(); for (int i = 0; i < NUM_THREADS; i++) { - threads[i] = new Thread(() -> { - for (int j = 0; j < NUM_ITERATIONS; j++) { - nonVolatileCounter++; // Write - nonVolatileCounter--; // Read - } - }); + threads[i] = + new Thread( + () -> { + for (int j = 0; j < NUM_ITERATIONS; j++) { + nonVolatileCounter++; // Write + nonVolatileCounter--; // Read + } + }); threads[i].start(); } @@ -71,6 +75,7 @@ public void testNonVolatileReadWrite() { } } long endTime = System.nanoTime(); - System.out.println("Non-Volatile Read/Write Time: " + (endTime - startTime) + " nanoseconds"); + System.out.println( + "Non-Volatile Read/Write Time: " + (endTime - startTime) + " nanoseconds"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatileTest.java b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatileTest.java index 3671e08f..50cfc233 100644 --- a/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatileTest.java +++ b/src/main/java/nitin/multithreading/raceCondition/eVolatileVar/VolatileTest.java @@ -7,14 +7,14 @@ public class VolatileTest { * */ public volatile int counter = 0; - int classLevelVar = 0;// Normal Variable, read from CPU Cache + int classLevelVar = 0; // Normal Variable, read from CPU Cache volatile int v = 0; // Volatile variable, read from Main Memory public void task() { int i = 0; while (classLevelVar < 10) { try { - int local = 0;//Each thread reads and maintains its local copy + int local = 0; // Each thread reads and maintains its local copy local++; System.out.println(local + " local" + Thread.currentThread()); Thread.sleep(1000); @@ -22,12 +22,19 @@ public void task() { e.printStackTrace(); } - //Search atomic - System.out.println(" read classLevelVar: " + classLevelVar + - "\t v:" + v + "\t" + - "write ++classLevelVar : " + ++classLevelVar + - "\t ++v:" + ++v + - "\t" + Thread.currentThread()); + // Search atomic + System.out.println( + " read classLevelVar: " + + classLevelVar + + "\t v:" + + v + + "\t" + + "write ++classLevelVar : " + + ++classLevelVar + + "\t ++v:" + + ++v + + "\t" + + Thread.currentThread()); } } } diff --git a/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/A1Demo.java b/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/A1Demo.java index d593194e..a38424af 100644 --- a/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/A1Demo.java +++ b/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/A1Demo.java @@ -1,15 +1,6 @@ package nitin.multithreading.raceCondition.fAtomicVar; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Created by Nitin Chaurasia on 12/4/15 at 2:12 AM. - * modified aug 12 20024 - */ +/** Created by Nitin Chaurasia on 12/4/15 at 2:12 AM. modified aug 12 20024 */ public class A1Demo { - public static void main(String[] args) { - - } + public static void main(String[] args) {} } - - diff --git a/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/AtomicIntCounter.java b/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/AtomicIntCounter.java index 7b7424e8..946aca4d 100644 --- a/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/AtomicIntCounter.java +++ b/src/main/java/nitin/multithreading/raceCondition/fAtomicVar/AtomicIntCounter.java @@ -6,5 +6,5 @@ public class AtomicIntCounter { // x is initialized with 9 private final AtomicInteger x = new AtomicInteger(9); - //x.incrementAndGet + // x.incrementAndGet } diff --git a/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumer.java b/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumer.java index a04fd8d2..f46f2b88 100644 --- a/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumer.java +++ b/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumer.java @@ -1,12 +1,12 @@ package nitin.multithreading.raceCondition.semaphore; +import static com.utilities.MultiThreadUtility.logShortMessage; + import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.ReentrantLock; -import static com.utilities.MultiThreadUtility.logShortMessage; - public class ProducerConsumer { private static final int QUEUE_CAPACITY = 10; private static Semaphore emptySemaphore = new Semaphore(QUEUE_CAPACITY); diff --git a/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumerRunner.java b/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumerRunner.java index c4f554a2..9f3fc05a 100644 --- a/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumerRunner.java +++ b/src/main/java/nitin/multithreading/raceCondition/semaphore/ProducerConsumerRunner.java @@ -5,7 +5,6 @@ public class ProducerConsumerRunner { private static final int NUM_PRODUCERS = 3; private static final int NUM_CONSUMERS = 2; - public static void main(String[] args) { // Start producer threads diff --git a/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreReleaseDemo.java b/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreReleaseDemo.java index 6a485e2e..5e7127f1 100644 --- a/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreReleaseDemo.java +++ b/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreReleaseDemo.java @@ -2,7 +2,8 @@ public class SemaphoreReleaseDemo { public static void main(String[] args) { - SemaphoreTask task1 = new SemaphoreTask("Thread 1", true);//Ensuring only this thread acquired permit + SemaphoreTask task1 = + new SemaphoreTask("Thread 1", true); // Ensuring only this thread acquired permit // Create threads that will execute the tasks Thread thread1 = new Thread(() -> task1.runTask()); thread1.start(); diff --git a/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreTask.java b/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreTask.java index 2e48d3d9..0a94cffb 100644 --- a/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreTask.java +++ b/src/main/java/nitin/multithreading/raceCondition/semaphore/SemaphoreTask.java @@ -1,9 +1,9 @@ package nitin.multithreading.raceCondition.semaphore; -import java.util.concurrent.Semaphore; - import static com.utilities.MultiThreadUtility.logShortMessage; +import java.util.concurrent.Semaphore; + public class SemaphoreTask { private String name; private boolean acquirePermit; diff --git a/src/main/java/nitin/nestedClasses/ImportStaticInnerClass.java b/src/main/java/nitin/nestedClasses/ImportStaticInnerClass.java index ec83be91..c5b655d9 100644 --- a/src/main/java/nitin/nestedClasses/ImportStaticInnerClass.java +++ b/src/main/java/nitin/nestedClasses/ImportStaticInnerClass.java @@ -1,12 +1,11 @@ package nitin.nestedClasses; -// Importing Nested Static Class in a regular Way. Notice the Two classes in the end of the import statement +// Importing Nested Static Class in a regular Way. Notice the Two classes in the end of the import +// statement // Using Static import. SAME AS ABOVE -//import static com.nitin.a5advancedClassDesign.nestedClasses.StaticNestedClass.Nested; +// import static com.nitin.a5advancedClassDesign.nestedClasses.StaticNestedClass.Nested; -/** - * Created by Nitin C on 3/5/2016. - */ +/** Created by Nitin C on 3/5/2016. */ public class ImportStaticInnerClass { StaticNestedClass.Nested nested; } diff --git a/src/main/java/nitin/nestedClasses/StaticNestedClass.java b/src/main/java/nitin/nestedClasses/StaticNestedClass.java index 7ff6314b..4a8688f7 100644 --- a/src/main/java/nitin/nestedClasses/StaticNestedClass.java +++ b/src/main/java/nitin/nestedClasses/StaticNestedClass.java @@ -2,8 +2,8 @@ /** * Created by Nitin Chaurasia on 3/5/16 at 12:02 AM. - *

- * Static class defined at the member level + * + *

Static class defined at the member level */ public class StaticNestedClass { public static void main(String[] args) { diff --git a/src/main/java/nitin/nestedClasses/innerClass/I1MemberInnerClass.java b/src/main/java/nitin/nestedClasses/innerClass/I1MemberInnerClass.java index a43f2f51..1b1e61e7 100644 --- a/src/main/java/nitin/nestedClasses/innerClass/I1MemberInnerClass.java +++ b/src/main/java/nitin/nestedClasses/innerClass/I1MemberInnerClass.java @@ -1,8 +1,6 @@ package nitin.nestedClasses.innerClass; -/** - * Created by Nitin Chaurasia on 3/5/16 at 12:03 AM. - */ +/** Created by Nitin Chaurasia on 3/5/16 at 12:03 AM. */ public class I1MemberInnerClass { private final String name = "Nitin"; @@ -11,18 +9,19 @@ public static void main(String[] args) { i1MemberInnerClass.callInner(); System.out.println("\n@@@@@#@#@@@@@#@#@##@@"); - //Another way of Instantiating + // Another way of Instantiating I1MemberInnerClass test = new I1MemberInnerClass(); Inner inner = test.new Inner(); inner.m1(); System.out.println("\n@@@@@#@#@@@@@#@#@##@@"); I1MemberInnerClass testPrivateInterface = new I1MemberInnerClass(); - ImplementPrivateInterface innerInterface = testPrivateInterface.new ImplementPrivateInterface(); + ImplementPrivateInterface innerInterface = + testPrivateInterface.new ImplementPrivateInterface(); innerInterface.secretMethod(); } - //Have to instantiate Inner class to be of any use + // Have to instantiate Inner class to be of any use public void callInner() { Inner inner = new Inner(); inner.m1(); @@ -38,7 +37,7 @@ protected class Inner { public void m1() { for (int i = 0; i < 10; i++) { - System.out.print(name + " : ");//Inner class have access to outer class field + System.out.print(name + " : "); // Inner class have access to outer class field } } } diff --git a/src/main/java/nitin/nestedClasses/innerClass/I2LocalInnerClass.java b/src/main/java/nitin/nestedClasses/innerClass/I2LocalInnerClass.java index edae05c5..5f515f75 100644 --- a/src/main/java/nitin/nestedClasses/innerClass/I2LocalInnerClass.java +++ b/src/main/java/nitin/nestedClasses/innerClass/I2LocalInnerClass.java @@ -2,12 +2,11 @@ /** * Created by Nitin C on 3/5/2016. - *

- * Local Inner Classes have following properties - * 1. No access specifiers - * 2. Cannot be declared static and cannot declare static fields or methods - * 3. They have access of all the fields and methods of the enclosing class - * 4. ONLY have access to "local variable" which are final or effectively final + * + *

Local Inner Classes have following properties 1. No access specifiers 2. Cannot be declared + * static and cannot declare static fields or methods 3. They have access of all the fields and + * methods of the enclosing class 4. ONLY have access to "local variable" which are final or + * effectively final */ public class I2LocalInnerClass { int length = 5; @@ -20,8 +19,9 @@ public static void main(String[] args) { public void calculate() { int width = 20; // Effectively final local variable, as it is not reassigned - // width = 30; error as effectively final or only final variables are allowed inside inner class - length = 6;// Re assignment of instance variable + // width = 30; error as effectively final or only final variables are allowed inside inner + // class + length = 6; // Re assignment of instance variable class Inner { public void area() { @@ -29,6 +29,6 @@ public void area() { } } Inner inner = new Inner(); - inner.area();// Calling the area() of the inner with the method of the + inner.area(); // Calling the area() of the inner with the method of the } } diff --git a/src/main/java/nitin/nestedClasses/innerClass/I3AnonymousClassDemo.java b/src/main/java/nitin/nestedClasses/innerClass/I3AnonymousClassDemo.java index e07b0c38..8bb26d91 100644 --- a/src/main/java/nitin/nestedClasses/innerClass/I3AnonymousClassDemo.java +++ b/src/main/java/nitin/nestedClasses/innerClass/I3AnonymousClassDemo.java @@ -1,12 +1,9 @@ package nitin.nestedClasses.innerClass; /** - * Created by nitin on 1/14/16. - * Anonymous Inner Class is a local inner class that does not have a name - * Inner Class can only be accessed only through live instance of outer class + * Created by nitin on 1/14/16. Anonymous Inner Class is a local inner class that does not have a + * name Inner Class can only be accessed only through live instance of outer class */ - - interface Demo { void show(); } @@ -14,21 +11,21 @@ interface Demo { public class I3AnonymousClassDemo { public static void main(String[] args) { - Demo demo = new Demo() {//Anonymous Class - public void show() { - System.out.println("Show from Anonymous class..."); - } - }; - - I3AnonymousClassDemo ref = new I3AnonymousClassDemo() {//Anonymous inner Class - public void data() { - System.out.println("Anonymous Inner Class..."); - } - - public void display() { - System.out.println("Display of Outer..."); - } - }; + Demo demo = new Demo() { // Anonymous Class + public void show() { + System.out.println("Show from Anonymous class..."); + } + }; + + I3AnonymousClassDemo ref = new I3AnonymousClassDemo() { // Anonymous inner Class + public void data() { + System.out.println("Anonymous Inner Class..."); + } + + public void display() { + System.out.println("Display of Outer..."); + } + }; ref.data(); demo.show(); } diff --git a/src/main/java/nitin/nestedClasses/innerClass/InnerClassTest.java b/src/main/java/nitin/nestedClasses/innerClass/InnerClassTest.java index 03e84754..9395dc54 100644 --- a/src/main/java/nitin/nestedClasses/innerClass/InnerClassTest.java +++ b/src/main/java/nitin/nestedClasses/innerClass/InnerClassTest.java @@ -7,9 +7,7 @@ public static void main(String[] args) { MyOuter mo = new MyOuter(); MyOuter.MyInner inner = mo.new MyInner(); inner.seeOuter(); - } - } class MyOuter { @@ -21,5 +19,3 @@ public void seeOuter() { } } } - - diff --git a/src/main/java/nitin/optionals/NullabilityTest.java b/src/main/java/nitin/optionals/NullabilityTest.java index 38c96356..44edca8b 100644 --- a/src/main/java/nitin/optionals/NullabilityTest.java +++ b/src/main/java/nitin/optionals/NullabilityTest.java @@ -8,16 +8,15 @@ public static void main(String[] args) { String str = null; // Create an Optional that may or may not have a value - Optional optional = Optional.ofNullable(str);//Value expecting a String + Optional optional = Optional.ofNullable(str); // Value expecting a String - System.out.println(optional.get());//NoSuchElementException: No value present - System.out.println(optional.orElse("other"));//other - System.out.println(optional.orElseGet(String::new));//EMPTY String - System.out.println(optional.isPresent());//false + System.out.println(optional.get()); // NoSuchElementException: No value present + System.out.println(optional.orElse("other")); // other + System.out.println(optional.orElseGet(String::new)); // EMPTY String + System.out.println(optional.isPresent()); // false AtomicReference name = new AtomicReference<>(new String()); optional.ifPresentOrElse( - value -> name.set(value.toUpperCase()), - () -> new NullPointerException()); + value -> name.set(value.toUpperCase()), () -> new NullPointerException()); } } diff --git a/src/main/java/nitin/optionals/O1ofVsOfNullable.java b/src/main/java/nitin/optionals/O1ofVsOfNullable.java index 87295832..7113c526 100644 --- a/src/main/java/nitin/optionals/O1ofVsOfNullable.java +++ b/src/main/java/nitin/optionals/O1ofVsOfNullable.java @@ -2,44 +2,38 @@ import java.util.Optional; -/** - * Created by nichaurasia on Friday, May/29/2020 at 1:13 PM - */ - +/** Created by nichaurasia on Friday, May/29/2020 at 1:13 PM */ public class O1ofVsOfNullable { /** - * optional Provides a means for a function returning a value to indicate the - * value could possibly be null. - * Optional is a box that contains values in it - * Optional is of 16 bytes, and is an Object. creates a separate memory, excessive use should be avoided - * as it can create performance issues. - *

- * Optional is immutable. Once assigned, it cannot be reassigned. + * optional Provides a means for a function returning a value to indicate the value could + * possibly be null. Optional is a box that contains values in it Optional is of 16 bytes, and + * is an Object. creates a separate memory, excessive use should be avoided as it can create + * performance issues. + * + *

Optional is immutable. Once assigned, it cannot be reassigned. */ public static void main(String[] args) { String str = "String"; - //Declaration by Of, Can't take null + // Declaration by Of, Can't take null Optional strOptional = Optional.of(str); - //By Empty Optional, to be used later + // By Empty Optional, to be used later Optional emptyOptional = Optional.empty(); ofNullable(); - } private static void ofNullable() { Optional optionalString = Optional.ofNullable(null); - System.out.println(optionalString);//Optional.empty + System.out.println(optionalString); // Optional.empty - String isBooleanFlag = "true";//'undefined', 'false', 'anyStringValue ' + String isBooleanFlag = "true"; // 'undefined', 'false', 'anyStringValue ' boolean aBoolean = Boolean.parseBoolean(isBooleanFlag); - //By Nullable : if not sure whether the argument (str) is actually having a value or it's not. + // By Nullable : if not sure whether the argument (str) is actually having a value or it's + // not. Optional nullableOptional1 = Optional.ofNullable("str"); Optional nullableOptional2 = Optional.ofNullable(null); } - - } diff --git a/src/main/java/nitin/optionals/O2UnwrappingOptional.java b/src/main/java/nitin/optionals/O2UnwrappingOptional.java index 9ca7e9d2..ed767748 100644 --- a/src/main/java/nitin/optionals/O2UnwrappingOptional.java +++ b/src/main/java/nitin/optionals/O2UnwrappingOptional.java @@ -2,16 +2,13 @@ import java.util.Optional; -/** - * Created by nichaurasia on Friday, May/29/2020 at 4:31 PM - */ - +/** Created by nichaurasia on Friday, May/29/2020 at 4:31 PM */ public class O2UnwrappingOptional { public static void main(String[] args) { String str = "Test String"; String emptyString = null; - //Optional way + // Optional way Optional strOptional = Optional.of(str); // get() method System.out.println("1: " + strOptional.get()); @@ -20,7 +17,8 @@ public static void main(String[] args) { String ret = strOptional.isPresent() ? strOptional.get() : "val not present"; Optional emptyStringOptional = Optional.empty(); - String retEmpty = emptyStringOptional.isPresent() ? emptyStringOptional.get() : "Alternative Value"; + String retEmpty = + emptyStringOptional.isPresent() ? emptyStringOptional.get() : "Alternative Value"; System.out.println("2: " + ret); System.out.println("3: " + retEmpty); @@ -28,10 +26,10 @@ public static void main(String[] args) { String ret2 = emptyStringOptional.orElse("tasty treat"); System.out.println(ret2); - //OrElseGet needs a supplier + // OrElseGet needs a supplier String ret3 = emptyStringOptional.orElseGet(() -> "OrElseGet Testing"); - //OrElseThrow - String ret4 = emptyStringOptional.orElseThrow();//No such element exception + // OrElseThrow + String ret4 = emptyStringOptional.orElseThrow(); // No such element exception } } diff --git a/src/main/java/nitin/optionals/O3applyMapWithOptional.java b/src/main/java/nitin/optionals/O3applyMapWithOptional.java index 65d03321..d44e30b4 100644 --- a/src/main/java/nitin/optionals/O3applyMapWithOptional.java +++ b/src/main/java/nitin/optionals/O3applyMapWithOptional.java @@ -2,10 +2,7 @@ import java.util.Optional; -/** - * Created by nichaurasia on Monday, June/01/2020 at 10:52 PM - */ - +/** Created by nichaurasia on Monday, June/01/2020 at 10:52 PM */ public class O3applyMapWithOptional { public static void main(String[] args) { @@ -17,31 +14,32 @@ private static void demo2() { String[] cities = {("New York"), (null), ("Los Angeles"), ("Chicago")}; for (String city : cities) { - //Another Example, in a loop, adding city name from the Object obj and appending a comma if the city exist, else leaving the city name. - String test1 = Optional.ofNullable(city).isPresent() ? city.toUpperCase() + "," : "NO_CITY"; - //System.out.println(test1); + // Another Example, in a loop, adding city name from the Object obj and appending a + // comma if the city exist, else leaving the city name. + String test1 = + Optional.ofNullable(city).isPresent() ? city.toUpperCase() + "," : "NO_CITY"; + // System.out.println(test1); } System.out.println("Optional With Map"); for (String city : cities) { // Using Map, avoiding ternary operator - String str2 = Optional.ofNullable(city) - .map(obj -> obj.toUpperCase() + ",")//Advantage of using map - .orElse("NO_CITY"); + String str2 = + Optional.ofNullable(city) + .map(obj -> obj.toUpperCase() + ",") // Advantage of using map + .orElse("NO_CITY"); System.out.println(str2); } } private static void simpleDemo() { Optional stringOptional = Optional.of("Testing"); - //map - ACCEPTS A FUNCTION, TAKES SOME ARGUMENT AND PERFORM ACTION ON IT + // map - ACCEPTS A FUNCTION, TAKES SOME ARGUMENT AND PERFORM ACTION ON IT Optional map = stringOptional.map(x -> x.toUpperCase()); System.out.println(map.get()); Optional emptyStringOptional = Optional.empty(); - String emptyMap = emptyStringOptional - .map(x -> x.toUpperCase()) - .orElse("Empty Map"); + String emptyMap = emptyStringOptional.map(x -> x.toUpperCase()).orElse("Empty Map"); System.out.println(emptyMap); } } diff --git a/src/main/java/nitin/optionals/OptionalOrElse.java b/src/main/java/nitin/optionals/OptionalOrElse.java index 6108bbec..b66aeeaf 100644 --- a/src/main/java/nitin/optionals/OptionalOrElse.java +++ b/src/main/java/nitin/optionals/OptionalOrElse.java @@ -1,12 +1,9 @@ package nitin.optionals; -import lombok.*; -import org.apache.commons.lang3.StringUtils; - import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Optional; +import lombok.*; public class OptionalOrElse { public static void main(String[] args) { @@ -17,28 +14,28 @@ public static void main(String[] args) { /** * Potential Side Effects: * - * If patient is accessed or modified from different parts of your program concurrently, - * changes made to it in one place can affect its state in another place. - * This can lead to inconsistencies or unexpected behaviors. + *

If patient is accessed or modified from different parts of your program concurrently, + * changes made to it in one place can affect its state in another place. This can lead to + * inconsistencies or unexpected behaviors. */ // Process labTests to get a single valid result or an empty list labList.parallelStream() .filter(data -> null != data) .findFirst() - .ifPresentOrElse(//Shared Mutability + .ifPresentOrElse( // Shared Mutability value -> patient.setLabTests(Collections.singletonList(value)), - () -> patient.setLabTests(Collections.emptyList()) - ); + () -> patient.setLabTests(Collections.emptyList())); // Process medTests to get a single valid result or an empty list - List singleMed = medList.stream() - .filter(data -> data != null) - .findFirst() - .map(Collections::singletonList) - .orElse(Collections.emptyList()); - - patient.setMedTests(singleMed);//Avoiding Shared Mutability + List singleMed = + medList.stream() + .filter(data -> data != null) + .findFirst() + .map(Collections::singletonList) + .orElse(Collections.emptyList()); + + patient.setMedTests(singleMed); // Avoiding Shared Mutability System.out.println(patient); } diff --git a/src/main/java/nitin/performance/CompilationDemo.java b/src/main/java/nitin/performance/CompilationDemo.java index 2064ddc1..c5def8b5 100644 --- a/src/main/java/nitin/performance/CompilationDemo.java +++ b/src/main/java/nitin/performance/CompilationDemo.java @@ -1,8 +1,8 @@ package nitin.performance; public class CompilationDemo { - public CompilationDemo() { - } + public CompilationDemo() {} + // java -XX:+TieredCompilation -XX:+PrintCompilation CompilationDemo public static int compute(int x) { return x * x; @@ -11,10 +11,11 @@ public static int compute(int x) { // A method that repeatedly calls the compute method public static void main(String[] args) { for (int i = 0; i < 1000000; i++) { - //The repeated calls to the compute method simulate a scenario where certain methods become + // The repeated calls to the compute method simulate a scenario where certain methods + // become // hotspots and are prime candidates for compilation int compute = compute(i); - //System.out.println(compute); + // System.out.println(compute); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/performance/GarbageCollectionStats.java b/src/main/java/nitin/performance/GarbageCollectionStats.java index 30909698..16fa9c63 100644 --- a/src/main/java/nitin/performance/GarbageCollectionStats.java +++ b/src/main/java/nitin/performance/GarbageCollectionStats.java @@ -1,33 +1,42 @@ package nitin.performance; +import java.util.ArrayList; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.ArrayList; -import java.util.List; - public class GarbageCollectionStats { public static final String unit = "MB"; public static void main(String[] args) throws InterruptedException { Runtime runtime = Runtime.getRuntime(); - long bytesInMb = (1024*1024); - System.out.println("Available memory at start: " + runtime.freeMemory()/bytesInMb + unit); + long bytesInMb = (1024 * 1024); + System.out.println("Available memory at start: " + runtime.freeMemory() / bytesInMb + unit); // let's create lots of objects.... List customers = new ArrayList(); - for (int i=0; i<1_000_000; i++) { + for (int i = 0; i < 1_000_000; i++) { customers.add(new Customer("John")); } - System.out.println("Available memory when customers created: " + runtime.freeMemory()/bytesInMb + unit); + System.out.println( + "Available memory when customers created: " + + runtime.freeMemory() / bytesInMb + + unit); customers = new ArrayList<>(); - System.out.println("Available memory when customers no longer referenced: " + runtime.freeMemory()/bytesInMb + unit); + System.out.println( + "Available memory when customers no longer referenced: " + + runtime.freeMemory() / bytesInMb + + unit); Thread.sleep(1000); - System.out.println("Available memory 1 second later: " + runtime.freeMemory()/bytesInMb + unit); + System.out.println( + "Available memory 1 second later: " + runtime.freeMemory() / bytesInMb + unit); System.gc(); - System.out.println("Available memory after GC command post Java 11 Optimizations: " + runtime.freeMemory()/bytesInMb + unit); + System.out.println( + "Available memory after GC command post Java 11 Optimizations: " + + runtime.freeMemory() / bytesInMb + + unit); } } @@ -36,4 +45,4 @@ public static void main(String[] args) throws InterruptedException { @NoArgsConstructor class Customer { private String name; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/performance/Main.java b/src/main/java/nitin/performance/Main.java index c3c3e130..1ccdd56f 100644 --- a/src/main/java/nitin/performance/Main.java +++ b/src/main/java/nitin/performance/Main.java @@ -5,14 +5,14 @@ public class Main { - public static void main(String[] args) throws InterruptedException { - //Thread.sleep(20000);//For JConsole to work properly - System.out.println("starting the work..."); - Date start = new Date(); - PrimeNumbers primeNumbers = new PrimeNumbers(); - Integer max = Integer.parseInt("10000"); - List integerList = primeNumbers.generateNumbers(max); - Date end = new Date(); - System.out.println("Total Time = " + (end.getTime()-start.getTime()) + "ms"); - } -} \ No newline at end of file + public static void main(String[] args) throws InterruptedException { + // Thread.sleep(20000);//For JConsole to work properly + System.out.println("starting the work..."); + Date start = new Date(); + PrimeNumbers primeNumbers = new PrimeNumbers(); + Integer max = Integer.parseInt("10000"); + List integerList = primeNumbers.generateNumbers(max); + Date end = new Date(); + System.out.println("Total Time = " + (end.getTime() - start.getTime()) + "ms"); + } +} diff --git a/src/main/java/nitin/performance/PrimeNumbers.java b/src/main/java/nitin/performance/PrimeNumbers.java index ca3b6485..2c20fdd4 100644 --- a/src/main/java/nitin/performance/PrimeNumbers.java +++ b/src/main/java/nitin/performance/PrimeNumbers.java @@ -4,32 +4,32 @@ import java.util.List; public class PrimeNumbers { - private List primes; - - private Boolean isPrime(Integer testNumber) { - for (int i = 2; i < testNumber; i++) { - if (testNumber % i == 0) return false; - } - return true; - } - - private Integer getNextPrimeAbove(Integer previous) { - Integer testNumber = previous + 1; - while (!isPrime(testNumber)) { - testNumber++; - } - return testNumber; - } - - public List generateNumbers (Integer max) { - primes = new ArrayList(); - primes.add(2); + private List primes; - Integer next = 2; - while (primes.size() <= max) { - next = getNextPrimeAbove(next); - primes.add(next); - } - return primes; - } -} \ No newline at end of file + private Boolean isPrime(Integer testNumber) { + for (int i = 2; i < testNumber; i++) { + if (testNumber % i == 0) return false; + } + return true; + } + + private Integer getNextPrimeAbove(Integer previous) { + Integer testNumber = previous + 1; + while (!isPrime(testNumber)) { + testNumber++; + } + return testNumber; + } + + public List generateNumbers(Integer max) { + primes = new ArrayList(); + primes.add(2); + + Integer next = 2; + while (primes.size() <= max) { + next = getNextPrimeAbove(next); + primes.add(next); + } + return primes; + } +} diff --git a/src/main/java/nitin/performance/StringStats.java b/src/main/java/nitin/performance/StringStats.java index 4d27ceb5..195556c9 100644 --- a/src/main/java/nitin/performance/StringStats.java +++ b/src/main/java/nitin/performance/StringStats.java @@ -5,15 +5,15 @@ import java.util.List; public class StringStats { - //Pick up a prime number for the string table size - //Run with -XX:+PrintStringTableStatistics -XX:StringTableSize=120121 -Xms1g -Xmx4g + // Pick up a prime number for the string table size + // Run with -XX:+PrintStringTableStatistics -XX:StringTableSize=120121 -Xms1g -Xmx4g public static void main(String[] args) { List list = new ArrayList<>(); Date start = new Date(); for (Integer i = 0; i < 10_000_000; i++) { - list.add(i.toString().intern());//Faker.instance().name().fullName() + list.add(i.toString().intern()); // Faker.instance().name().fullName() } Date end = new Date(); - System.out.println("Time Taken : " + (end.getTime()- start.getTime()) + " ms"); + System.out.println("Time Taken : " + (end.getTime() - start.getTime()) + " ms"); } } diff --git a/src/main/java/nitin/performance/list/ArrayListVsLinkedList.java b/src/main/java/nitin/performance/list/ArrayListVsLinkedList.java index 2588b32c..87cd100e 100644 --- a/src/main/java/nitin/performance/list/ArrayListVsLinkedList.java +++ b/src/main/java/nitin/performance/list/ArrayListVsLinkedList.java @@ -1,18 +1,18 @@ package nitin.performance.list; +import static com.utilities.PerformanceUtility.*; + import com.github.javafaker.Book; import com.github.javafaker.Faker; - import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import static com.utilities.PerformanceUtility.*; - public class ArrayListVsLinkedList { public static void main(String[] args) { final int SIZE = 1_000_000; - Book bookName = Faker.instance().book();; + Book bookName = Faker.instance().book(); + ; List list = new ArrayList<>(SIZE); List linkedList = new LinkedList<>(); @@ -33,6 +33,5 @@ public static void main(String[] args) { System.out.println(book2); stopTimer(); resetTimer(); - } } diff --git a/src/main/java/nitin/performance/list/DynamicResizingImpact.java b/src/main/java/nitin/performance/list/DynamicResizingImpact.java index 97a6c01c..77377a97 100644 --- a/src/main/java/nitin/performance/list/DynamicResizingImpact.java +++ b/src/main/java/nitin/performance/list/DynamicResizingImpact.java @@ -1,18 +1,18 @@ package nitin.performance.list; +import static com.utilities.PerformanceUtility.*; + import com.github.javafaker.Book; import com.github.javafaker.Faker; - import java.util.ArrayList; import java.util.List; -import static com.utilities.PerformanceUtility.*; - public class DynamicResizingImpact { public static void main(String[] args) { final int SIZE = 1_000_000; - Book bookName = Faker.instance().book();; + Book bookName = Faker.instance().book(); + ; List defaultList = new ArrayList<>(); startTimer(); for (int i = 0; i < SIZE; i++) { @@ -21,7 +21,6 @@ public static void main(String[] args) { stopTimer(); resetTimer(); - List initialSizeList = new ArrayList<>(SIZE); startTimer(); for (int i = 0; i < SIZE; i++) { diff --git a/src/main/java/nitin/performance/softLeaks/Consumer.java b/src/main/java/nitin/performance/softLeaks/Consumer.java index 1a4bf036..17884867 100644 --- a/src/main/java/nitin/performance/softLeaks/Consumer.java +++ b/src/main/java/nitin/performance/softLeaks/Consumer.java @@ -4,30 +4,27 @@ public class Consumer implements Runnable { -private CustomerManager cm; - - public Consumer(CustomerManager cm) { - this.cm = cm; - } - - @Override - public void run() { - while (true) { + private CustomerManager cm; - Optional customer = cm.getNextCustomer(); - if (!customer.isPresent()) { - //no customers in queue so pause for half a second - try { - Thread.sleep((50)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - else { - //Processing takes place here - } - } + public Consumer(CustomerManager cm) { + this.cm = cm; + } - } + @Override + public void run() { + while (true) { + Optional customer = cm.getNextCustomer(); + if (!customer.isPresent()) { + // no customers in queue so pause for half a second + try { + Thread.sleep((50)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + // Processing takes place here + } + } + } } diff --git a/src/main/java/nitin/performance/softLeaks/Customer.java b/src/main/java/nitin/performance/softLeaks/Customer.java index c92e71b6..2ace1afd 100644 --- a/src/main/java/nitin/performance/softLeaks/Customer.java +++ b/src/main/java/nitin/performance/softLeaks/Customer.java @@ -1,22 +1,20 @@ package nitin.performance.softLeaks; + public class Customer { - private int id; - private String name; - - public void setId(int id) { - this.id = id; - } - - public String toString() { - return id + " : " + name; - } - - public Customer(String name) { - super(); - this.name = name; - } + private int id; + private String name; - -} + public void setId(int id) { + this.id = id; + } + public String toString() { + return id + " : " + name; + } + + public Customer(String name) { + super(); + this.name = name; + } +} diff --git a/src/main/java/nitin/performance/softLeaks/CustomerManager.java b/src/main/java/nitin/performance/softLeaks/CustomerManager.java index d0145708..9025ef9a 100644 --- a/src/main/java/nitin/performance/softLeaks/CustomerManager.java +++ b/src/main/java/nitin/performance/softLeaks/CustomerManager.java @@ -5,34 +5,34 @@ import java.util.List; import java.util.Optional; - public class CustomerManager { - private List customers = new ArrayList(); - private int nextAvalailbleId = 0; - private int lastProcessedId = -1; + private List customers = new ArrayList(); + private int nextAvalailbleId = 0; + private int lastProcessedId = -1; - public void addCustomer(Customer customer) { - synchronized (this) { - customer.setId(nextAvalailbleId); - synchronized(customers) { - customers.add(customer); - } - nextAvalailbleId++; - } - } + public void addCustomer(Customer customer) { + synchronized (this) { + customer.setId(nextAvalailbleId); + synchronized (customers) { + customers.add(customer); + } + nextAvalailbleId++; + } + } - public Optional getNextCustomer() { - if (lastProcessedId + 1 > nextAvalailbleId) { - lastProcessedId++; - return Optional.of(customers.get(lastProcessedId)); - } - return Optional.empty(); - } + public Optional getNextCustomer() { + if (lastProcessedId + 1 > nextAvalailbleId) { + lastProcessedId++; + return Optional.of(customers.get(lastProcessedId)); + } + return Optional.empty(); + } - public void howManyCustomers() { - int size = 0; - size = customers.size(); - System.out.println("" + new Date() + " Customers in queue : " + size + " of " + nextAvalailbleId); - } -} \ No newline at end of file + public void howManyCustomers() { + int size = 0; + size = customers.size(); + System.out.println( + "" + new Date() + " Customers in queue : " + size + " of " + nextAvalailbleId); + } +} diff --git a/src/main/java/nitin/performance/softLeaks/CustomerRunner_JMH.java b/src/main/java/nitin/performance/softLeaks/CustomerRunner_JMH.java index 20461917..41621d86 100644 --- a/src/main/java/nitin/performance/softLeaks/CustomerRunner_JMH.java +++ b/src/main/java/nitin/performance/softLeaks/CustomerRunner_JMH.java @@ -1,24 +1,26 @@ package nitin.performance.softLeaks; + public class CustomerRunner_JMH { - - public static void main(String[] args) throws InterruptedException { - CustomerManager cm = new CustomerManager(); - Producer producerTask = new Producer(cm); - Consumer consumerTask = new Consumer(cm); - - for (int i = 0; i < 10; i++) { - Thread t = new Thread(producerTask); - t.start(); - } - Thread t = new Thread(consumerTask);// Consumer - t.start(); - - //main thread is now acting as the monitoring thread - while (true) { - Thread.sleep(5000); - cm.howManyCustomers(); - System.out.println("Available memory: " + Runtime.getRuntime().freeMemory() / 1024 + "k"); - } - } -} \ No newline at end of file + public static void main(String[] args) throws InterruptedException { + CustomerManager cm = new CustomerManager(); + Producer producerTask = new Producer(cm); + Consumer consumerTask = new Consumer(cm); + + for (int i = 0; i < 10; i++) { + Thread t = new Thread(producerTask); + t.start(); + } + + Thread t = new Thread(consumerTask); // Consumer + t.start(); + + // main thread is now acting as the monitoring thread + while (true) { + Thread.sleep(5000); + cm.howManyCustomers(); + System.out.println( + "Available memory: " + Runtime.getRuntime().freeMemory() / 1024 + "k"); + } + } +} diff --git a/src/main/java/nitin/performance/softLeaks/GC_Verbose.java b/src/main/java/nitin/performance/softLeaks/GC_Verbose.java index 4fb74b4d..65ba028a 100644 --- a/src/main/java/nitin/performance/softLeaks/GC_Verbose.java +++ b/src/main/java/nitin/performance/softLeaks/GC_Verbose.java @@ -1,26 +1,23 @@ package nitin.performance.softLeaks; import com.github.javafaker.Faker; - import java.util.ArrayList; import java.util.List; public class GC_Verbose { - public static void main(String[] args) throws InterruptedException { - //Run with -Xmx5m -verbose:gc - int size = 10000; - List customers = new ArrayList(); - while(true) { - Customer c = new Customer(Faker.instance().harryPotter().character()); - customers.add(c); - if (customers.size() > size) - for (int i = 0; i < size/2; i++) - customers.remove(0);//simulating the conditions to run GC - - //Thread.sleep(10); - } - - } + public static void main(String[] args) throws InterruptedException { + // Run with -Xmx5m -verbose:gc + int size = 10000; + List customers = new ArrayList(); + while (true) { + Customer c = new Customer(Faker.instance().harryPotter().character()); + customers.add(c); + if (customers.size() > size) + for (int i = 0; i < size / 2; i++) + customers.remove(0); // simulating the conditions to run GC + // Thread.sleep(10); + } + } } diff --git a/src/main/java/nitin/performance/softLeaks/Producer.java b/src/main/java/nitin/performance/softLeaks/Producer.java index 2033a212..66b7a2b1 100644 --- a/src/main/java/nitin/performance/softLeaks/Producer.java +++ b/src/main/java/nitin/performance/softLeaks/Producer.java @@ -1,27 +1,23 @@ package nitin.performance.softLeaks; -import lombok.AllArgsConstructor; - import java.util.UUID; +import lombok.AllArgsConstructor; @AllArgsConstructor public class Producer implements Runnable { - private CustomerManager cm; + private CustomerManager cm; - @Override - public void run() { - while (true) { - try { - //This is just to slow things down so we can see what's going on! - Thread.sleep(2); - } catch (InterruptedException e) { - } - String name = UUID.randomUUID().toString(); - Customer c = new Customer(name); - cm.addCustomer(c); - } - } + @Override + public void run() { + while (true) { + try { + // This is just to slow things down so we can see what's going on! + Thread.sleep(2); + } catch (InterruptedException e) { + } + String name = UUID.randomUUID().toString(); + Customer c = new Customer(name); + cm.addCustomer(c); + } + } } - - - diff --git a/src/main/java/nitin/reactiveProgramming/HelloRxJava.java b/src/main/java/nitin/reactiveProgramming/HelloRxJava.java index a6982021..1ba1877d 100644 --- a/src/main/java/nitin/reactiveProgramming/HelloRxJava.java +++ b/src/main/java/nitin/reactiveProgramming/HelloRxJava.java @@ -2,18 +2,15 @@ import io.reactivex.Observable; - -/** - * Created by nichaurasia on Friday, June/05/2020 at 6:40 PM - */ - +/** Created by nichaurasia on Friday, June/05/2020 at 6:40 PM */ public class HelloRxJava { public static void main(String[] args) { - Observable observable = Observable.create( - emitter -> { - emitter.onNext("Hello World Practise from RxJava"); - emitter.onNext("Mic Testing 1....2.....3..."); - }); + Observable observable = + Observable.create( + emitter -> { + emitter.onNext("Hello World Practise from RxJava"); + emitter.onNext("Mic Testing 1....2.....3..."); + }); for (int i = 0; i < 10; i++) { int finalI = i; diff --git a/src/main/java/nitin/reactiveProgramming/ObservableNObserver.java b/src/main/java/nitin/reactiveProgramming/ObservableNObserver.java index c78ae88a..08c382e2 100644 --- a/src/main/java/nitin/reactiveProgramming/ObservableNObserver.java +++ b/src/main/java/nitin/reactiveProgramming/ObservableNObserver.java @@ -8,48 +8,50 @@ import io.reactivex.disposables.Disposable; import io.reactivex.internal.operators.observable.ObservableCreate; -/** - * Created by nichaurasia on Friday, June/05/2020 at 7:32 PM - */ - +/** Created by nichaurasia on Friday, June/05/2020 at 7:32 PM */ public class ObservableNObserver { public static void main(String[] args) { - Observable observable = new ObservableCreate(new ObservableOnSubscribe() { - - @Override - public void subscribe(@NonNull ObservableEmitter observableEmitter) throws Exception { - try { - observableEmitter.onNext(100); - observableEmitter.onNext(200); - observableEmitter.onComplete(); - } catch (Throwable t) { - observableEmitter.onError(t); - } - } - }); - - Observer observer = new Observer() { - @Override - public void onSubscribe(Disposable disposable) { - System.out.println("Subscribed : " + disposable); - } - - @Override - public void onNext(Integer integer) { - System.out.println("On Next : " + integer); - } - - @Override - public void onError(Throwable throwable) { - throwable.printStackTrace(); - } - - @Override - public void onComplete() { - System.out.println("On Complete Invoked : "); - } - }; + Observable observable = + new ObservableCreate( + new ObservableOnSubscribe() { + + @Override + public void subscribe( + @NonNull ObservableEmitter observableEmitter) + throws Exception { + try { + observableEmitter.onNext(100); + observableEmitter.onNext(200); + observableEmitter.onComplete(); + } catch (Throwable t) { + observableEmitter.onError(t); + } + } + }); + + Observer observer = + new Observer() { + @Override + public void onSubscribe(Disposable disposable) { + System.out.println("Subscribed : " + disposable); + } + + @Override + public void onNext(Integer integer) { + System.out.println("On Next : " + integer); + } + + @Override + public void onError(Throwable throwable) { + throwable.printStackTrace(); + } + + @Override + public void onComplete() { + System.out.println("On Complete Invoked : "); + } + }; observable.subscribe(observer); } diff --git a/src/main/java/nitin/reactiveProgramming/reactorLib/R1MonoDemo.java b/src/main/java/nitin/reactiveProgramming/reactorLib/R1MonoDemo.java index 042681be..585208f0 100644 --- a/src/main/java/nitin/reactiveProgramming/reactorLib/R1MonoDemo.java +++ b/src/main/java/nitin/reactiveProgramming/reactorLib/R1MonoDemo.java @@ -2,24 +2,29 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; -import reactor.core.publisher.Mono; - import java.util.List; import java.util.Optional; +import reactor.core.publisher.Mono; public class R1MonoDemo { public static void main(String[] args) { - Optional> simpleEmployees = Optional.of(SampleData.getSimpleEmployees()); + Optional> simpleEmployees = + Optional.of(SampleData.getSimpleEmployees()); - //Creating Publisher + // Creating Publisher Mono> employeeJust = Mono.just(SampleData.getSimpleEmployees()); - //Evaluated only when subscibed. just like Streams Lazy evaluation + // Evaluated only when subscibed. just like Streams Lazy evaluation - //Single Subscribe - employeeJust.subscribe(empList -> empList - .stream() - .forEach(singleEmployee -> - System.out.println(singleEmployee.getName() + "::" + singleEmployee.getSalary()))); + // Single Subscribe + employeeJust.subscribe( + empList -> + empList.stream() + .forEach( + singleEmployee -> + System.out.println( + singleEmployee.getName() + + "::" + + singleEmployee.getSalary()))); } } diff --git a/src/main/java/nitin/reactiveProgramming/reactorLib/R2MultiSubscribe.java b/src/main/java/nitin/reactiveProgramming/reactorLib/R2MultiSubscribe.java index 4d13dea3..a4989be1 100644 --- a/src/main/java/nitin/reactiveProgramming/reactorLib/R2MultiSubscribe.java +++ b/src/main/java/nitin/reactiveProgramming/reactorLib/R2MultiSubscribe.java @@ -5,31 +5,32 @@ public class R2MultiSubscribe { public static void main(String[] args) { - //Creating Publisher -// Mono> employeeJust = Mono.just(SampleData.getSimpleEmployees()) -// .map(employeeSimples -> employeeSimples.stream().filter()); + // Creating Publisher + // Mono> employeeJust = + // Mono.just(SampleData.getSimpleEmployees()) + // .map(employeeSimples -> employeeSimples.stream().filter()); - //Evaluated only when subscibed. just like Streams Lazy evaluation + // Evaluated only when subscibed. just like Streams Lazy evaluation - //Single Subscribe -// employeeJust.subscribe(empList -> empList -// .stream() -// .forEach(singleEmployee -> -// System.out.println(singleEmployee.getName() + "::" + singleEmployee.getSalary()))); + // Single Subscribe + // employeeJust.subscribe(empList -> empList + // .stream() + // .forEach(singleEmployee -> + // System.out.println(singleEmployee.getName() + "::" + + // singleEmployee.getSalary()))); String fakeName = Faker.instance().funnyName().name(); - Mono stringMono = Mono - .just(fakeName) - .map(fName -> fName + " : " + fName.length() / 0); + Mono stringMono = + Mono.just(fakeName).map(fName -> fName + " : " + fName.length() / 0); - //Subscribe with single parameter + // Subscribe with single parameter stringMono.subscribe(item -> System.out.println("Received from Publisher :: " + item)); // stringMono.subscribe( - item -> System.out.println(item),//onNext, consumer - err -> System.out.println(err.getMessage()),//onError, Throwable - () -> System.out.println("-- Completed --")//onComplete, Runnable - ); + item -> System.out.println(item), // onNext, consumer + err -> System.out.println(err.getMessage()), // onError, Throwable + () -> System.out.println("-- Completed --") // onComplete, Runnable + ); } } diff --git a/src/main/java/nitin/reactiveProgramming/reactorLib/R3MonoFromSupplier.java b/src/main/java/nitin/reactiveProgramming/reactorLib/R3MonoFromSupplier.java index 35666043..d8c63e82 100644 --- a/src/main/java/nitin/reactiveProgramming/reactorLib/R3MonoFromSupplier.java +++ b/src/main/java/nitin/reactiveProgramming/reactorLib/R3MonoFromSupplier.java @@ -1,17 +1,16 @@ package nitin.reactiveProgramming.reactorLib; import com.github.javafaker.Faker; -import reactor.core.publisher.Mono; - import java.util.concurrent.CompletableFuture; +import reactor.core.publisher.Mono; public class R3MonoFromSupplier { public static void main(String[] args) { - //JUST : Use only what the data is available already - //Mono.just(nameRepo()); + // JUST : Use only what the data is available already + // Mono.just(nameRepo()); - //Will not be invoked until the subscriber subscribe to it. Lasy behaviour + // Will not be invoked until the subscriber subscribe to it. Lasy behaviour Mono fromSupplier = Mono.fromSupplier(() -> nameRepo()); Mono fromCallable = Mono.fromCallable(() -> nameRepo()); Mono fromFuture = Mono.fromFuture(nameRepoCompletableFuture()); @@ -20,20 +19,22 @@ public static void main(String[] args) { fromFuture.subscribe(name -> System.out.println(name)); System.out.println("================================"); - //Mono from runnable (doesnt take in, doesnt take out), helpful in Notifying things - Mono fromRunnable = Mono.fromRunnable(() -> System.out.println("Some time consuming Operations")); + // Mono from runnable (doesnt take in, doesnt take out), helpful in Notifying things + Mono fromRunnable = + Mono.fromRunnable(() -> System.out.println("Some time consuming Operations")); - fromRunnable.subscribe(data -> System.out.println(data), + fromRunnable.subscribe( + data -> System.out.println(data), error -> System.out.println(error.getMessage()), - () -> System.out.println("Process completed :: Sending emails") - ); + () -> System.out.println("Process completed :: Sending emails")); - Mono fromRunnable2 = Mono.fromRunnable(() -> System.out.println("Some time consuming Operations 2")); + Mono fromRunnable2 = + Mono.fromRunnable(() -> System.out.println("Some time consuming Operations 2")); - fromRunnable2.subscribe(data -> System.out.println(data), + fromRunnable2.subscribe( + data -> System.out.println(data), error -> System.out.println(error.getMessage()), - () -> System.out.println("Process completed 2 :: Sending emails") - ); + () -> System.out.println("Process completed 2 :: Sending emails")); } private static String nameRepo() { @@ -43,6 +44,7 @@ private static String nameRepo() { private static CompletableFuture nameRepoCompletableFuture() { System.out.println("Fetching name from Completable Future : "); - return CompletableFuture.supplyAsync(() -> "From Comp fut :: " + Faker.instance().name().fullName()); + return CompletableFuture.supplyAsync( + () -> "From Comp fut :: " + Faker.instance().name().fullName()); } } diff --git a/src/main/java/nitin/reactiveProgramming/reactorLib/R4FluxCreation.java b/src/main/java/nitin/reactiveProgramming/reactorLib/R4FluxCreation.java index d9b8346b..0cdb5e02 100644 --- a/src/main/java/nitin/reactiveProgramming/reactorLib/R4FluxCreation.java +++ b/src/main/java/nitin/reactiveProgramming/reactorLib/R4FluxCreation.java @@ -1,44 +1,46 @@ package nitin.reactiveProgramming.reactorLib; import com.utilities.ReactorUtils; -import reactor.core.publisher.Flux; - import java.util.List; import java.util.stream.Stream; +import reactor.core.publisher.Flux; public class R4FluxCreation { public static void main(String[] args) { - //single emelent flux + // single emelent flux Flux stringFlux = Flux.just(ReactorUtils.faker().animal().name()); - stringFlux.subscribe(ReactorUtils.onNext(), - ReactorUtils.onError(), - ReactorUtils.onComplete() - ); + stringFlux.subscribe( + ReactorUtils.onNext(), ReactorUtils.onError(), ReactorUtils.onComplete()); - //Multi Element Flux - Flux multiStringFlux = Flux.just( - ReactorUtils.faker().book().title(), - ReactorUtils.faker().book().title(), - ReactorUtils.faker().book().title()); + // Multi Element Flux + Flux multiStringFlux = + Flux.just( + ReactorUtils.faker().book().title(), + ReactorUtils.faker().book().title(), + ReactorUtils.faker().book().title()); multiStringFlux.subscribe(ReactorUtils.onNext("Subscriber 1")); multiStringFlux.subscribe(ReactorUtils.onNext("Subscriber 2")); System.out.println("------ From List ------"); - //Flux from ArrayList - List titles = List.of(ReactorUtils.faker().book().title(), - ReactorUtils.faker().book().title(), - ReactorUtils.faker().book().title()); + // Flux from ArrayList + List titles = + List.of( + ReactorUtils.faker().book().title(), + ReactorUtils.faker().book().title(), + ReactorUtils.faker().book().title()); Flux fromIterable = Flux.fromIterable(titles); fromIterable.subscribe(ReactorUtils.onNext()); System.out.println("------ From Array ------"); - //Flux from Arrays - String[] title = {ReactorUtils.faker().book().title(), - ReactorUtils.faker().book().title(), - ReactorUtils.faker().book().title()}; + // Flux from Arrays + String[] title = { + ReactorUtils.faker().book().title(), + ReactorUtils.faker().book().title(), + ReactorUtils.faker().book().title() + }; Flux fromArray = Flux.fromArray(title); fromArray.subscribe(ReactorUtils.onNext()); @@ -48,14 +50,10 @@ public static void main(String[] args) { fromStream.subscribe(ReactorUtils.onNext()); System.out.println("------ From Range (Integer) ------"); - Flux range = Flux.range(6, 5);//Get counts + Flux range = Flux.range(6, 5); // Get counts range.subscribe(ReactorUtils.onNext()); - Flux rangeNames = Flux - .range(6, 5) - .log() - .map(iterator -> ReactorUtils.faker().book().title()) - .log(); + Flux rangeNames = + Flux.range(6, 5).log().map(iterator -> ReactorUtils.faker().book().title()).log(); rangeNames.subscribe(ReactorUtils.onNext()); - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/recursion/PrintDigitChar.java b/src/main/java/nitin/recursion/PrintDigitChar.java index c07d0b40..f81e116d 100644 --- a/src/main/java/nitin/recursion/PrintDigitChar.java +++ b/src/main/java/nitin/recursion/PrintDigitChar.java @@ -4,7 +4,7 @@ public class PrintDigitChar { public static void main(String[] args) { int n = 532164327; System.out.println(n); - //printDigitCharZeroBase(5321); + // printDigitCharZeroBase(5321); printDigitChar(n); } diff --git a/src/main/java/nitin/recursion/TowerOfHanoi.java b/src/main/java/nitin/recursion/TowerOfHanoi.java index d9f52491..f61558ea 100644 --- a/src/main/java/nitin/recursion/TowerOfHanoi.java +++ b/src/main/java/nitin/recursion/TowerOfHanoi.java @@ -5,27 +5,28 @@ public class TowerOfHanoi { public static void main(String[] args) { int n = 3; - //towerOfHanoi(n, "A", "B", "Temp"); + // towerOfHanoi(n, "A", "B", "Temp"); towerOfHanoiZeroBase(n, "A", "B", "Temp"); } private static void towerOfHanoi(int n, String start, String end, String temp) { - if(n == 1) { - System.out.println("Move disk 1 from " + start + " to " + end + " :: move = " + count++); - }else { - towerOfHanoi(n-1, start, temp, end); + if (n == 1) { + System.out.println( + "Move disk 1 from " + start + " to " + end + " :: move = " + count++); + } else { + towerOfHanoi(n - 1, start, temp, end); System.out.println("Move disk from " + start + " to " + end + " :: move = " + count++); - towerOfHanoi(n-1,temp, end, start); + towerOfHanoi(n - 1, temp, end, start); } } private static void towerOfHanoiZeroBase(int n, String start, String end, String temp) { - if(n == 0) { + if (n == 0) { return; } else { - towerOfHanoiZeroBase(n-1, start, temp, end); + towerOfHanoiZeroBase(n - 1, start, temp, end); System.out.println("Move disk from " + start + " to " + end + " :: move = " + count++); - towerOfHanoiZeroBase(n-1,temp, end, start); + towerOfHanoiZeroBase(n - 1, temp, end, start); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/reflectionAPI/Address.java b/src/main/java/nitin/reflectionAPI/Address.java index e34d94bc..8a1fb5ff 100644 --- a/src/main/java/nitin/reflectionAPI/Address.java +++ b/src/main/java/nitin/reflectionAPI/Address.java @@ -1,11 +1,8 @@ package nitin.reflectionAPI; -/** - * Created by Nitin Chaurasia on 12/4/15 at 12:04 AM. - */ +/** Created by Nitin Chaurasia on 12/4/15 at 12:04 AM. */ public class Address { String add; String city; int apt; } - diff --git a/src/main/java/nitin/reflectionAPI/R1BasicRefAPITest.java b/src/main/java/nitin/reflectionAPI/R1BasicRefAPITest.java index 3e95f0f6..9c9611f4 100644 --- a/src/main/java/nitin/reflectionAPI/R1BasicRefAPITest.java +++ b/src/main/java/nitin/reflectionAPI/R1BasicRefAPITest.java @@ -1,4 +1,5 @@ package nitin.reflectionAPI; + /* Package Name has to be deleted because the Class.forName method is not recognizing the Class From Default package it is recognizing. @@ -7,28 +8,23 @@ */ -import lombok.Getter; -import lombok.Setter; - import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import lombok.Getter; +import lombok.Setter; /** * Created by com.nitin.a23reflectionAPI.Nitin Chaurasia on 12/3/15 at 11:54 PM. - *

- * There are 3 ways to get the instance of Class class. They are as follows: - * forName() method of Class class - * getClass() method of Object class - * the .class syntax + * + *

There are 3 ways to get the instance of Class class. They are as follows: forName() method of + * Class class getClass() method of Object class the .class syntax */ public class R1BasicRefAPITest { - public static void main(String[] args) throws - IllegalAccessException, - InstantiationException, - ClassNotFoundException { + public static void main(String[] args) + throws IllegalAccessException, InstantiationException, ClassNotFoundException { - //Instance to access non-static methods + // Instance to access non-static methods R1BasicRefAPITest t = new R1BasicRefAPITest(); /* @@ -43,19 +39,19 @@ public static void main(String[] args) throws System.out.println(c.getClass()); t.printMetadata(c); - //Type 2: Creating the Instance when the Class name and a5object name both are known!! + // Type 2: Creating the Instance when the Class name and a5object name both are known!! Nitin n = (Nitin) c.newInstance(); // Can use n just like an created with new keyword // Type 3: When only the Object Name is known. Nitin nObj = new Nitin(); /* - It should be used if you know the type. - Moreover, .getClass can be used with primitives. - */ + It should be used if you know the type. + Moreover, .getClass can be used with primitives. + */ Class c1 = nObj.getClass(); - //Case Study for the equality of the Objects + // Case Study for the equality of the Objects t.caseStudy(); } @@ -66,7 +62,7 @@ private void caseStudy() throws ClassNotFoundException { Class c2 = Class.forName("nitin.reflectionAPI.Nitin"); Class c3 = n.getClass(); - //All the three references points to the same a5object. + // All the three references points to the same a5object. if (c1 == c2) { System.out.println(" equal"); } @@ -74,13 +70,12 @@ private void caseStudy() throws ClassNotFoundException { System.out.println("c1" + " " + c1); System.out.println("c2" + " " + c2); System.out.println("c3" + " " + c3); - } - //When Class name is Known, Class.forName() method is preferred + // When Class name is Known, Class.forName() method is preferred private void printMetadata(Class c) { - //Discovering the methods of a class: + // Discovering the methods of a class: Method[] m = c.getDeclaredMethods(); System.out.println("METHODS IN CLASS ARE :- "); for (Method method : m) { @@ -88,7 +83,7 @@ private void printMetadata(Class c) { } System.out.println("---------------------------"); - //Discovering the fields of a class: + // Discovering the fields of a class: Field[] f = c.getDeclaredFields(); System.out.println("FIELDS IN CLASS ARE :- "); for (Field field : f) { @@ -96,7 +91,7 @@ private void printMetadata(Class c) { } System.out.println("---------------------------"); - //Constructor in the Class are + // Constructor in the Class are Constructor[] cons = c.getDeclaredConstructors(); System.out.println("CONSTRUCTORS IN THE CLASS ARE :- "); for (Constructor constructor : cons) { @@ -105,14 +100,13 @@ private void printMetadata(Class c) { System.out.println("---------------------------"); Field[] fields = c.getFields(); - //Methods for super class as well + // Methods for super class as well System.out.println("Fields IN THE CLASS ARE (getFields method):- "); for (Field fld : fields) { System.out.println(fld); } System.out.println("---------------------------"); - Method[] methods = c.getMethods(); System.out.println("methods IN THE CLASS ARE :- "); for (Method mtd : methods) { @@ -120,7 +114,7 @@ private void printMetadata(Class c) { } System.out.println("---------------------------"); - //Discovering the interfaces implemented by a class: + // Discovering the interfaces implemented by a class: Class[] interfaces = c.getInterfaces(); System.out.println("INTERFACES IN THE CLASS ARE :- "); for (Class i : interfaces) { @@ -128,12 +122,11 @@ private void printMetadata(Class c) { } System.out.println("---------------------------"); - - //Getting the superclass : + // Getting the superclass : Class s = c.getSuperclass(); System.out.println(s); - //Getting the class name: + // Getting the class name: String str = c.getName(); System.out.println(str); System.out.println("---------------------------"); @@ -141,42 +134,35 @@ private void printMetadata(Class c) { System.out.println(c.getClassLoader()); System.out.println(c.getFields().toString()); System.out.println("---------------------------"); - } } -/** - * Class Written for the Reflection API Testing - */ - +/** Class Written for the Reflection API Testing */ class Nitin { int x; Child s; - Nitin() { - } + Nitin() {} Nitin(int a, String b, boolean c) { - //A Constructor + // A Constructor } public void m1() { - //Any method + // Any method } public int m2() { - //Any other method + // Any other method return 0; } } -/** - * Data Class Containing only data. - */ +/** Data Class Containing only data. */ @Getter @Setter class Child { private int kid; private String name; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/reflectionAPI/Student.java b/src/main/java/nitin/reflectionAPI/Student.java index 6aed1c14..3214e6b3 100644 --- a/src/main/java/nitin/reflectionAPI/Student.java +++ b/src/main/java/nitin/reflectionAPI/Student.java @@ -1,18 +1,17 @@ package nitin.reflectionAPI; -/** - * Created by Nitin Chaurasia on 12/4/15 at 12:03 AM. - */ +/** Created by Nitin Chaurasia on 12/4/15 at 12:03 AM. */ public class Student { int age; String name; - //Address addr; -// Student(age,name,addr){ -// this.age = age; -// this.name = name; -// this.addr = addr; -// } + // Address addr; + + // Student(age,name,addr){ + // this.age = age; + // this.name = name; + // this.addr = addr; + // } public void prinntStudent() { System.out.println(this.name); diff --git a/src/main/java/nitin/regex/RegexSmall.java b/src/main/java/nitin/regex/RegexSmall.java index 03353e89..b20516cd 100644 --- a/src/main/java/nitin/regex/RegexSmall.java +++ b/src/main/java/nitin/regex/RegexSmall.java @@ -11,7 +11,5 @@ public static void main(String[] args) { while (m.find()) { System.out.print(m.start() + " "); } - } - } diff --git a/src/main/java/nitin/regex/TokenExtractor.java b/src/main/java/nitin/regex/TokenExtractor.java index 1e7b035f..fa30fdae 100644 --- a/src/main/java/nitin/regex/TokenExtractor.java +++ b/src/main/java/nitin/regex/TokenExtractor.java @@ -8,18 +8,18 @@ public class TokenExtractor { public static void main(String[] args) { String[] inputStrings = { - "Non-Reactive", - "Reactive", - "0.8", - "0.8 Reactive", - "<=0.8", - ">0.8", - "<0.8", - ">=0.8", - "<=0.8 Reactive", - ">0.8 Reactive", - "<0.8 Reactive", - ">=0.8 Reactive" + "Non-Reactive", + "Reactive", + "0.8", + "0.8 Reactive", + "<=0.8", + ">0.8", + "<0.8", + ">=0.8", + "<=0.8 Reactive", + ">0.8 Reactive", + "<0.8 Reactive", + ">=0.8 Reactive" }; for (String input : inputStrings) { @@ -41,7 +41,8 @@ private static List extractTokens(String input) { // Extract tokens from the input string and store in a list List tokens = new ArrayList<>(); while (matcher.find()) { - String relationalOperator = matcher.group(1); // Extract the first capturing group ([<>]=?|=) + String relationalOperator = + matcher.group(1); // Extract the first capturing group ([<>]=?|=) if (relationalOperator != null && !relationalOperator.isEmpty()) { tokens.add(relationalOperator); } @@ -67,7 +68,8 @@ private static List extractTokens2(String input) { // Extract tokens from the input string and store in a list List tokens = new ArrayList<>(); while (matcher.find()) { - String relationalOperator = matcher.group(1); // Extract the first capturing group ([<>]=?|=) + String relationalOperator = + matcher.group(1); // Extract the first capturing group ([<>]=?|=) if (relationalOperator != null && !relationalOperator.isEmpty()) { tokens.add(relationalOperator); } @@ -97,11 +99,13 @@ private static List extractTokens3(String input) { // Extract tokens from the input string and store in a list List tokens = new ArrayList<>(); while (matcher.find()) { - String reactiveStatus = matcher.group(1); // Extract the first capturing group (Reactive|Non-Reactive) + String reactiveStatus = + matcher.group(1); // Extract the first capturing group (Reactive|Non-Reactive) if (reactiveStatus != null && !reactiveStatus.isEmpty()) { tokens.add(reactiveStatus); } - String relationalOperator = matcher.group(2); // Extract the second capturing group ([<>]=?|=) + String relationalOperator = + matcher.group(2); // Extract the second capturing group ([<>]=?|=) if (relationalOperator != null && !relationalOperator.isEmpty()) { tokens.add(relationalOperator); } diff --git a/src/main/java/nitin/serialization/Account.java b/src/main/java/nitin/serialization/Account.java index 7ecc84ee..64121da6 100644 --- a/src/main/java/nitin/serialization/Account.java +++ b/src/main/java/nitin/serialization/Account.java @@ -4,24 +4,22 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -/** - * Created by Nitin Chaurasia on 8/2/15 at 12:37 AM. - */ +/** Created by Nitin Chaurasia on 8/2/15 at 12:37 AM. */ public class Account implements Serializable { String un = "Durga"; transient String pwd = "Anushka"; /* Automatically executed at the time of Serialization */ public void writeObject(ObjectOutputStream os) throws Exception { - os.defaultWriteObject();//perform default serialization (Durga...null) - String epwd = "123" + pwd; //Encrypting the password (123Anushka) - os.writeObject(epwd);// write it as a separate a5object + os.defaultWriteObject(); // perform default serialization (Durga...null) + String epwd = "123" + pwd; // Encrypting the password (123Anushka) + os.writeObject(epwd); // write it as a separate a5object } /* Automatically executed at the time of De-Serialization */ public void readObject(ObjectInputStream is) throws Exception { is.defaultReadObject(); String epwd = (String) is.readObject(); - pwd = epwd.substring(3);//Decripting the password + pwd = epwd.substring(3); // Decripting the password } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/serialization/JacksonMapperTest.java b/src/main/java/nitin/serialization/JacksonMapperTest.java index 8cc4a4a0..8eb6a42e 100644 --- a/src/main/java/nitin/serialization/JacksonMapperTest.java +++ b/src/main/java/nitin/serialization/JacksonMapperTest.java @@ -1,7 +1,6 @@ package nitin.serialization; import com.fasterxml.jackson.databind.ObjectMapper; - import java.io.File; import java.io.IOException; @@ -9,20 +8,30 @@ public class JacksonMapperTest { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); - //Serializing Object - TestSerial testSerial = TestSerial.builder() - .name("Katie")//The transient variable does not participate in the serialization process. It takes defalut values - .age(5) - .password("TESTING") - .someChar('%') - .finalTransientString("Final Transient String showing")//Testing final transient. Final overpowers and thus there is no effect of transient - .build(); - + // Serializing Object + TestSerial testSerial = + TestSerial.builder() + .name("Katie") // The transient variable does not participate in the + // serialization process. It takes defalut values + .age(5) + .password("TESTING") + .someChar('%') + .finalTransientString( + "Final Transient String showing") // Testing final transient. Final + // overpowers and thus there is no + // effect of transient + .build(); - mapper.writeValue(new File("src/main/java/nitin/serialization/serialObjectTransient.txt"), TestSerial.class); + mapper.writeValue( + new File("src/main/java/nitin/serialization/serialObjectTransient.txt"), + TestSerial.class); - TestSerial c = mapper.readValue(new File("src/main/java/nitin/serialization/serialObjectTransient.txt"), TestSerial.class); - System.out.println("*********************** After Deserialization ****************************"); + TestSerial c = + mapper.readValue( + new File("src/main/java/nitin/serialization/serialObjectTransient.txt"), + TestSerial.class); + System.out.println( + "*********************** After Deserialization ****************************"); System.out.println(c); } } diff --git a/src/main/java/nitin/serialization/S1BasicSerialization.java b/src/main/java/nitin/serialization/S1BasicSerialization.java index d0ccf00f..db55df6b 100644 --- a/src/main/java/nitin/serialization/S1BasicSerialization.java +++ b/src/main/java/nitin/serialization/S1BasicSerialization.java @@ -2,28 +2,27 @@ import java.io.*; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class S1BasicSerialization { private static final String FILE_NAME = "src/com/nitin/a21serialization/serialObject.txt"; public static void main(String[] args) throws IOException, ClassNotFoundException { Dog d = new Dog(); - //Obtaining the File name + // Obtaining the File name File f = new File(FILE_NAME); - //Checking if the File exists or not + // Checking if the File exists or not if (!f.exists()) { f.createNewFile(); - //If file by that name does not exist, then create the file + // If file by that name does not exist, then create the file System.out.println("Created File..."); } - /** The Process of Serialization needs File Output Stream to write the Object into the File + /** + * The Process of Serialization needs File Output Stream to write the Object into the File * The Object is written onto the FOS, which inturns writes it in the File - * */ + */ // File Output Stream is needed by ObjectOutputStream FileOutputStream fileOutputStream = new FileOutputStream(f); @@ -34,9 +33,11 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio objectOutputStream.writeObject(d); objectOutputStream.close(); - /** The Process of Deserialization needs File Input Stream to be able to read the Object from the File - * The Object is written onto the FIS, which inturns gives it back to the OIS (ObjectInputStream) - * */ + /** + * The Process of Deserialization needs File Input Stream to be able to read the Object from + * the File The Object is written onto the FIS, which inturns gives it back to the OIS + * (ObjectInputStream) + */ // Opening the Input Stream FileInputStream fileInputStream = new FileInputStream(f); @@ -44,7 +45,7 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio // Opening the ObjectInput Stream ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); - //Read the Object + // Read the Object Dog d2 = (Dog) objectInputStream.readObject(); objectInputStream.close(); @@ -54,11 +55,10 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio System.out.println(d2.hashCode()); System.out.println(d.hashCode()); - } } -//IF serializable is not implemented then you get NotSerializableException +// IF serializable is not implemented then you get NotSerializableException class Dog implements Serializable { String name = "Jackie"; int age = 10; @@ -68,4 +68,3 @@ public String toString() { return (this.name + " : " + this.age); } } - diff --git a/src/main/java/nitin/serialization/S2TransientSerializable.java b/src/main/java/nitin/serialization/S2TransientSerializable.java index 0865897e..6d4d855d 100644 --- a/src/main/java/nitin/serialization/S2TransientSerializable.java +++ b/src/main/java/nitin/serialization/S2TransientSerializable.java @@ -4,23 +4,32 @@ /** * Created by nitin on 1/2/16. - *

- * Transient does not work when Static or Final is used + * + *

Transient does not work when Static or Final is used */ public class S2TransientSerializable { public static void main(String[] args) { - //Serializing Object - TestSerial testSerial = TestSerial.builder() - .name("Katie")//The transient variable does not participate in the serialization process. It takes defalut values - .age(5) - .password("TESTING") - .someChar('%') - .finalTransientString("Final Transient String showing")//Testing final transient. Final overpowers and thus there is no effect of transient - .build(); + // Serializing Object + TestSerial testSerial = + TestSerial.builder() + .name("Katie") // The transient variable does not participate in the + // serialization process. It takes defalut values + .age(5) + .password("TESTING") + .someChar('%') + .finalTransientString( + "Final Transient String showing") // Testing final transient. Final + // overpowers and thus there is no + // effect of transient + .build(); - //Testing for the Final - try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("src/main/java/nitin/serialization/serialObjectTransient.txt")))) { + // Testing for the Final + try (ObjectOutputStream oos = + new ObjectOutputStream( + new FileOutputStream( + new File( + "src/main/java/nitin/serialization/serialObjectTransient.txt")))) { oos.writeObject(testSerial); System.out.println(testSerial); } catch (FileNotFoundException e) { @@ -29,12 +38,16 @@ public static void main(String[] args) { e.printStackTrace(); } - - //Deserialization - try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("src/main/java/nitin/serialization/serialObjectTransient.txt")))) { + // Deserialization + try (ObjectInputStream ois = + new ObjectInputStream( + new FileInputStream( + new File( + "src/main/java/nitin/serialization/serialObjectTransient.txt")))) { TestSerial c = (TestSerial) ois.readObject(); ois.close(); - System.out.println("*********************** After Deserialization ****************************"); + System.out.println( + "*********************** After Deserialization ****************************"); System.out.println(c); } catch (FileNotFoundException e) { e.printStackTrace(); @@ -43,4 +56,3 @@ public static void main(String[] args) { } } } - diff --git a/src/main/java/nitin/serialization/S3ObjectGraphSerialization.java b/src/main/java/nitin/serialization/S3ObjectGraphSerialization.java index 097957ad..2a2d90f5 100644 --- a/src/main/java/nitin/serialization/S3ObjectGraphSerialization.java +++ b/src/main/java/nitin/serialization/S3ObjectGraphSerialization.java @@ -2,23 +2,26 @@ import java.io.*; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class S3ObjectGraphSerialization { public static void main(String[] args) throws IOException, ClassNotFoundException { - //Serializing Object - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("src/com/nitin/a21serialization/serialObjectGraph.txt"))); + // Serializing Object + ObjectOutputStream oos = + new ObjectOutputStream( + new FileOutputStream( + new File("src/com/nitin/a21serialization/serialObjectGraph.txt"))); oos.writeObject(new Animal()); oos.close(); - //Deserialization - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("src/com/nitin/a21serialization/serialObjectGraph.txt"))); + // Deserialization + ObjectInputStream ois = + new ObjectInputStream( + new FileInputStream( + new File("src/com/nitin/a21serialization/serialObjectGraph.txt"))); Animal c = (Animal) ois.readObject(); ois.close(); System.out.println(c.fla.h.toString()); - } } @@ -26,7 +29,9 @@ class Animal implements Serializable { FourLeggedAnimal fla = new FourLeggedAnimal(); } -class FourLeggedAnimal implements Serializable { // if implements serializable is not used : java.io.NotSerializableException: com.nitin.a21serialization.FourLeggedAnimal +class FourLeggedAnimal implements Serializable { // if implements serializable is not used : + // java.io.NotSerializableException: + // com.nitin.a21serialization.FourLeggedAnimal Horse h = new Horse(); } @@ -36,8 +41,6 @@ class Horse implements Serializable { @Override public String toString() { - return "Horse{" + - "name='" + name + '\'' + - '}'; + return "Horse{" + "name='" + name + '\'' + '}'; } } diff --git a/src/main/java/nitin/serialization/S4CustomizedSerialization.java b/src/main/java/nitin/serialization/S4CustomizedSerialization.java index 558f509e..aad76b89 100644 --- a/src/main/java/nitin/serialization/S4CustomizedSerialization.java +++ b/src/main/java/nitin/serialization/S4CustomizedSerialization.java @@ -3,21 +3,28 @@ import java.io.*; /** - * Created by nitin on 1/2/16. - * Transient Keyword leads to the Loss of Information, - * This can be controlled by Customized Serialization + * Created by nitin on 1/2/16. Transient Keyword leads to the Loss of Information, This can be + * controlled by Customized Serialization */ public class S4CustomizedSerialization { public static void main(String[] args) throws IOException, ClassNotFoundException { - //Serializing Object - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("src/com/nitin/a21serialization/serialObjectCoustomized.txt"))); + // Serializing Object + ObjectOutputStream oos = + new ObjectOutputStream( + new FileOutputStream( + new File( + "src/com/nitin/a21serialization/serialObjectCoustomized.txt"))); Login l = new Login(); // Call the overridden writeObject from the class Login oos.writeObject(l); oos.close(); - //Deserialization - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("src/com/nitin/a21serialization/serialObjectCoustomized.txt"))); + // Deserialization + ObjectInputStream ois = + new ObjectInputStream( + new FileInputStream( + new File( + "src/com/nitin/a21serialization/serialObjectCoustomized.txt"))); // Call the overridden readObject from the class Login Login c = (Login) ois.readObject(); @@ -30,22 +37,23 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio class Login implements Serializable { String uname = "Nitin"; - transient String pwd = "123@abc##";//Passwords are transient because do not sent over inter net as a string + transient String pwd = + "123@abc##"; // Passwords are transient because do not sent over inter net as a string - //Automatically executed at the time of Serialization. PRIVATE METHOD, NOT PUBLIC + // Automatically executed at the time of Serialization. PRIVATE METHOD, NOT PUBLIC private void writeObject(ObjectOutputStream os) throws Exception { - //perform default a21serialization (Nitin...null)
 + // perform default a21serialization (Nitin...null) os.defaultWriteObject(); - //Encrypting the password (!@#@$123@abc##)
 + // Encrypting the password (!@#@$123@abc##) String epwd = "!@#@$" + pwd; - os.writeObject(epwd);// write it as a separate a5object
 + os.writeObject(epwd); // write it as a separate a5object
 } // Automatically executed at the time of De-Serialization private void readObject(ObjectInputStream is) throws Exception { is.defaultReadObject(); String epwd = (String) is.readObject(); - pwd = epwd.substring(5);//Decripting the password
 + pwd = epwd.substring(5); // Decripting the password
 } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/serialization/S5ParentSerChildNot.java b/src/main/java/nitin/serialization/S5ParentSerChildNot.java index b9e04439..b93ca28d 100644 --- a/src/main/java/nitin/serialization/S5ParentSerChildNot.java +++ b/src/main/java/nitin/serialization/S5ParentSerChildNot.java @@ -2,12 +2,14 @@ import java.io.*; -/** - * Created by nitin on 1/2/16. - */ +/** Created by nitin on 1/2/16. */ public class S5ParentSerChildNot { public static void main(String[] args) throws IOException, ClassNotFoundException { - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("src/com/nitin/a21serialization/serialObjectInherited.txt"))); + ObjectOutputStream oos = + new ObjectOutputStream( + new FileOutputStream( + new File( + "src/com/nitin/a21serialization/serialObjectInherited.txt"))); DecidiousPlants dp = new DecidiousPlants(); ConiferousPlants cp = new ConiferousPlants(); @@ -16,8 +18,12 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio oos.writeObject(cp); oos.close(); - //Deserialization - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("src/com/nitin/a21serialization/serialObjectInherited.txt"))); + // Deserialization + ObjectInputStream ois = + new ObjectInputStream( + new FileInputStream( + new File( + "src/com/nitin/a21serialization/serialObjectInherited.txt"))); /* Since we know the ORDER of insertion in Serialization, no exception else ClassCastException */ DecidiousPlants decidiousPlants = (DecidiousPlants) ois.readObject(); @@ -32,22 +38,20 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio class Plants implements Serializable { int a = 90; - } -//Since Parent has Serializable implemeted, Chine need not be so +// Since Parent has Serializable implemeted, Chine need not be so class DecidiousPlants extends Plants { int b = 45; @Override public String toString() { - return "DecidiousPlants{" + - "b=" + b + - '}'; + return "DecidiousPlants{" + "b=" + b + '}'; } } -//Now we don't want this child class to be Serialised, so throw NotSerializableException from the over ridden writeObject Class +// Now we don't want this child class to be Serialised, so throw NotSerializableException from the +// over ridden writeObject Class class ConiferousPlants extends Plants { int c = 40; @@ -57,8 +61,6 @@ private void writeObject(ObjectOutputStream os) throws NotSerializableException @Override public String toString() { - return "ConiferousPlants{" + - "c=" + c + - '}'; + return "ConiferousPlants{" + "c=" + c + '}'; } } diff --git a/src/main/java/nitin/serialization/S6ParentNotSerChildSer.java b/src/main/java/nitin/serialization/S6ParentNotSerChildSer.java index 1969420a..e59c78db 100644 --- a/src/main/java/nitin/serialization/S6ParentNotSerChildSer.java +++ b/src/main/java/nitin/serialization/S6ParentNotSerChildSer.java @@ -2,23 +2,29 @@ import java.io.*; -/** - * Created by nitin on 1/3/16. - */ +/** Created by nitin on 1/3/16. */ public class S6ParentNotSerChildSer { public static void main(String[] args) throws IOException, ClassNotFoundException { - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("src/com/nitin/a21serialization/serialObjectInherited.txt"))); + ObjectOutputStream oos = + new ObjectOutputStream( + new FileOutputStream( + new File( + "src/com/nitin/a21serialization/serialObjectInherited.txt"))); FourVehicle dp = new FourVehicle(); - //This will be serialized + // This will be serialized dp.b = 244224; - //Super class is not serialised, this this will not go + // Super class is not serialised, this this will not go dp.a = 10; oos.writeObject(dp); oos.close(); - //Deserialization - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("src/com/nitin/a21serialization/serialObjectInherited.txt"))); + // Deserialization + ObjectInputStream ois = + new ObjectInputStream( + new FileInputStream( + new File( + "src/com/nitin/a21serialization/serialObjectInherited.txt"))); FourVehicle c = (FourVehicle) ois.readObject(); System.out.println(c); ois.close(); @@ -28,23 +34,17 @@ public static void main(String[] args) throws IOException, ClassNotFoundExceptio class Vehicle { int a = 90; - Vehicle() { - } + Vehicle() {} } -//Since Parent has Serializable implemeted, Chine need not be so +// Since Parent has Serializable implemeted, Chine need not be so class FourVehicle extends Vehicle implements Serializable { int b = 45; - FourVehicle() { - - } + FourVehicle() {} @Override public String toString() { - return "FourVehicle{" + - "b=" + b + - "super.a=" + a + - '}'; + return "FourVehicle{" + "b=" + b + "super.a=" + a + '}'; } } diff --git a/src/main/java/nitin/serialization/S7SUIDConcepts.java b/src/main/java/nitin/serialization/S7SUIDConcepts.java index 27ba0616..d3a03b96 100644 --- a/src/main/java/nitin/serialization/S7SUIDConcepts.java +++ b/src/main/java/nitin/serialization/S7SUIDConcepts.java @@ -2,24 +2,20 @@ import java.io.*; -/** - * Created by nitin on 1/3/16. - */ +/** Created by nitin on 1/3/16. */ public class S7SUIDConcepts { - public static void main(String[] args) throws IOException, - ClassNotFoundException { + public static void main(String[] args) throws IOException, ClassNotFoundException { File f = new File("src/com/nitin/a21serialization/suidTest.out"); Serialtest st1 = new Serialtest(1000); Serialtest st2 = new Serialtest(1000); - // serialize -// FileOutputStream fos = new FileOutputStream(f); -// ObjectOutputStream oos = new ObjectOutputStream(fos); -// System.out.println("Serialization done."); -// oos.writeObject(st1); -// oos.close(); + // FileOutputStream fos = new FileOutputStream(f); + // ObjectOutputStream oos = new ObjectOutputStream(fos); + // System.out.println("Serialization done."); + // oos.writeObject(st1); + // oos.close(); // helpful in deep a22cloning // deserialize @@ -41,24 +37,20 @@ class Serialtest implements Serializable { // serialversionuid is computed by compiler int a; int f; - transient int y = 0;// transient variables are not serialized + transient int y = 0; // transient variables are not serialized int bb = 0; int newVarAfterDeclaringSUID = 9; - - //Named Constructor + // Named Constructor public Serialtest(int a) { this.a = a; // similarly methods are not serialized } - //Methods - public void f1() { + // Methods + public void f1() {} - } - - public void m1new() { - } + public void m1new() {} public void m2() { System.out.println(" changes done to methos check and compare with saved a5object"); @@ -73,12 +65,17 @@ public void m4() { @Override public String toString() { - return "Serialtest{" + - "a=" + a + - ", f=" + f + - ", y=" + y + - ", bb=" + bb + - ", newvariableafterdeclaringserialversiouid=" + newVarAfterDeclaringSUID + - '}'; + return "Serialtest{" + + "a=" + + a + + ", f=" + + f + + ", y=" + + y + + ", bb=" + + bb + + ", newvariableafterdeclaringserialversiouid=" + + newVarAfterDeclaringSUID + + '}'; } } diff --git a/src/main/java/nitin/serialization/TestSerial.java b/src/main/java/nitin/serialization/TestSerial.java index 9f081fac..0fb3938f 100644 --- a/src/main/java/nitin/serialization/TestSerial.java +++ b/src/main/java/nitin/serialization/TestSerial.java @@ -1,23 +1,22 @@ package nitin.serialization; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.ToString; -import java.io.Serializable; - @Data @ToString @Builder @AllArgsConstructor @JsonIgnoreProperties public class TestSerial implements Serializable { - //Testing for the Static variable. Static variables are NOT The part of Object, - //The are the part of Class + // Testing for the Static variable. Static variables are NOT The part of Object, + // The are the part of Class private static int staticInt = 342324; - //Similarly there is no effect of static transient + // Similarly there is no effect of static transient private static String staticTransientString = "Static Transient String showing"; private final transient String finalTransientString; private String name; diff --git a/src/main/java/nitin/socketTCP/GreetingClient.java b/src/main/java/nitin/socketTCP/GreetingClient.java index 48cda7c8..40a7b55f 100644 --- a/src/main/java/nitin/socketTCP/GreetingClient.java +++ b/src/main/java/nitin/socketTCP/GreetingClient.java @@ -1,6 +1,6 @@ package nitin.socketTCP; -//File Name GreetingClient.java +// File Name GreetingClient.java import java.io.DataInputStream; import java.io.DataOutputStream; @@ -9,9 +9,9 @@ public class GreetingClient { public static void main(String[] args) throws IOException { - //args[0] = 127.0.0.1, args[1] = 1234 - //String serverName = args[0]; - //int port = Integer.parseInt(args[1]); + // args[0] = 127.0.0.1, args[1] = 1234 + // String serverName = args[0]; + // int port = Integer.parseInt(args[1]); String serverName = "localhost"; int port = 1234; DataInputStream in = null; @@ -22,12 +22,12 @@ public static void main(String[] args) throws IOException { System.out.println("Connecting to Server" + serverName + " on port " + port); client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); - //Writes data to the socket + // Writes data to the socket out = new DataOutputStream(client.getOutputStream()); - //in = new DataInputStream(new BufferedInputStream(client.getInputStream())); - //Take the input from Terminal + // in = new DataInputStream(new BufferedInputStream(client.getInputStream())); + // Take the input from Terminal in = new DataInputStream(System.in); - //Sending data to the server + // Sending data to the server } catch (IOException e) { e.printStackTrace(); } @@ -42,12 +42,11 @@ public static void main(String[] args) throws IOException { e.printStackTrace(); } System.out.println("Sending to Server " + sendToServer); - //System.out.println("Server says " + in.readUTF()); + // System.out.println("Server says " + in.readUTF()); } out.close(); client.close(); in.close(); - } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/socketTCP/GreetingServer.java b/src/main/java/nitin/socketTCP/GreetingServer.java index 22f25564..90cffb81 100644 --- a/src/main/java/nitin/socketTCP/GreetingServer.java +++ b/src/main/java/nitin/socketTCP/GreetingServer.java @@ -1,6 +1,6 @@ package nitin.socketTCP; -//File Name GreetingServer.java +// File Name GreetingServer.java import java.io.BufferedInputStream; import java.io.DataInputStream; @@ -19,7 +19,7 @@ public GreetingServer(int port) throws IOException { } public static void main(String[] args) { - //int port = Integer.parseInt(args[0]); + // int port = Integer.parseInt(args[0]); int port = 1234; try { Thread t = new GreetingServer(port); @@ -45,7 +45,7 @@ public void run() { } catch (SocketTimeoutException s) { System.out.println("Socket timed out!"); - //break; + // break; } catch (IOException e) { e.printStackTrace(); // break; @@ -63,7 +63,8 @@ public void run() { System.out.println("Closing connection"); try { - //out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); + // out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + + // "\nGoodbye!"); server.close(); in.close(); out.close(); @@ -71,4 +72,4 @@ public void run() { e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/F7ImplementUnaryBinaryOperators.java b/src/main/java/nitin/streams/F7ImplementUnaryBinaryOperators.java index d5fae110..2368bc3e 100644 --- a/src/main/java/nitin/streams/F7ImplementUnaryBinaryOperators.java +++ b/src/main/java/nitin/streams/F7ImplementUnaryBinaryOperators.java @@ -4,9 +4,8 @@ import java.util.function.UnaryOperator; /** - * Created by Nitin C on 3/3/2016. - * Unary and Binary are the special case of a Function where all input parameter - * and return value are all of Same type + * Created by Nitin C on 3/3/2016. Unary and Binary are the special case of a Function where all + * input parameter and return value are all of Same type */ public class F7ImplementUnaryBinaryOperators { public static void main(String[] args) { diff --git a/src/main/java/nitin/streams/LexicalScopingClosures/HigherOrderPredicate.java b/src/main/java/nitin/streams/LexicalScopingClosures/HigherOrderPredicate.java index 0f0db838..ce6f37a9 100644 --- a/src/main/java/nitin/streams/LexicalScopingClosures/HigherOrderPredicate.java +++ b/src/main/java/nitin/streams/LexicalScopingClosures/HigherOrderPredicate.java @@ -7,7 +7,8 @@ public class HigherOrderPredicate { - public static final List namesList = Arrays.asList("Adrian", "Briana", "Chetan", "Neil", "Nitin", "Mukesh"); + public static final List namesList = + Arrays.asList("Adrian", "Briana", "Chetan", "Neil", "Nitin", "Mukesh"); // Method returning a function. Filter accepts a Predicate & this method is // made to return a predicate, to be used within filter @@ -18,7 +19,7 @@ public static Predicate checkIfStartsWith(final String letter) { public static void main(final String[] args) { - //Simple Predicates + // Simple Predicates final Predicate startsWithN = name -> name.startsWith("N"); final Predicate startsWithB = name -> name.startsWith("B"); @@ -30,7 +31,6 @@ public static void main(final String[] args) { System.out.println(namesList.stream().filter(checkIfStartsWith("A")).count()); System.out.println(namesList.stream().filter(checkIfStartsWith("B")).count()); - // Function, taking in a String and returning a Predicate, as expected by a filter final Function> startsWithLetterFunction = (String letter) -> { @@ -42,7 +42,6 @@ public static void main(final String[] args) { System.out.println(namesList.stream().filter(startsWithLetterFunction.apply("N")).count()); System.out.println(namesList.stream().filter(startsWithLetterFunction.apply("B")).count()); - // Higher Order function :: Function returning a function. Same as block 3 function final Function> startsWithLetter = (String letter) -> (String name) -> name.startsWith(letter); @@ -52,7 +51,7 @@ public static void main(final String[] args) { System.out.println(namesList.stream().filter(startsWithLetter.apply("B")).count()); // Higher Order function :: Function returning a function, with concise code - //Same as block 3 and 4 Functions + // Same as block 3 and 4 Functions final Function> startsWithLetterConcise = letter -> name -> name.startsWith(letter); @@ -60,4 +59,4 @@ public static void main(final String[] args) { System.out.println(namesList.stream().filter(startsWithLetterConcise.apply("N")).count()); System.out.println(namesList.stream().filter(startsWithLetterConcise.apply("B")).count()); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/LexicalScopingClosures/PlayWithDataMuse.java b/src/main/java/nitin/streams/LexicalScopingClosures/PlayWithDataMuse.java index 66c83fc7..3481ec96 100644 --- a/src/main/java/nitin/streams/LexicalScopingClosures/PlayWithDataMuse.java +++ b/src/main/java/nitin/streams/LexicalScopingClosures/PlayWithDataMuse.java @@ -1,66 +1,57 @@ package nitin.streams.LexicalScopingClosures; -import com.utilities.InternetUtilities; +import static java.util.stream.Collectors.*; +import com.utilities.InternetUtilities; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; -import static java.util.stream.Collectors.*; - -/** - * Created by nitin on Saturday, February/15/2020 at 11:26 PM - */ +/** Created by nitin on Saturday, February/15/2020 at 11:26 PM */ public class PlayWithDataMuse { public static void main(String[] args) { InternetUtilities internetUtilities = new InternetUtilities(); - List words = InternetUtilities.getWords(new String[]{"loathe", "1000"}); + List words = InternetUtilities.getWords(new String[] {"loathe", "1000"}); System.out.println("Total words received :: " + words.stream().count()); - //Function taking a String as input and returning a Predicate + // Function taking a String as input and returning a Predicate final Function> startsWithLetter = (String letter) -> (String word) -> word.startsWith(letter); Map> wordsByLength = - words.stream() - .collect(groupingBy(String::length)); - //System.out.println("Group by Length : " + wordsByLength ); + words.stream().collect(groupingBy(String::length)); + // System.out.println("Group by Length : " + wordsByLength ); - //Print Word count of each word, based on Length + // Print Word count of each word, based on Length Map wordsByLengthCount = - words.stream() - .collect(groupingBy(String::length, counting())); + words.stream().collect(groupingBy(String::length, counting())); System.out.println(wordsByLengthCount); - //filtering(s -> !s.contains("c") - /* Map> wordsByCharacter= + // filtering(s -> !s.contains("c") + /* Map> wordsByCharacter= words.stream() .collect(groupingBy(String::length, filtering(x->x.length() == 7,toList()))); System.out.println(wordsByCharacter);*/ - /*var result = words.stream() - .collect( - groupingBy(String::length, - mapping(toStringList(), - flatMapping(s -> s.stream().distinct(), - filtering(s -> s.length() > 0, - mapping(String::toUpperCase, - reducing("", (s, s2) -> s + s2))))) - ));*/ + .collect( + groupingBy(String::length, + mapping(toStringList(), + flatMapping(s -> s.stream().distinct(), + filtering(s -> s.length() > 0, + mapping(String::toUpperCase, + reducing("", (s, s2) -> s + s2))))) + ));*/ // System.out.println(result); } private static Function> toStringList() { - return s -> s.chars() - .mapToObj(c -> (char) c) - .map(Object::toString) - .collect(toList()); + return s -> s.chars().mapToObj(c -> (char) c).map(Object::toString).collect(toList()); } } diff --git a/src/main/java/nitin/streams/MapWithStreams.java b/src/main/java/nitin/streams/MapWithStreams.java index d955e80e..d9ea2565 100644 --- a/src/main/java/nitin/streams/MapWithStreams.java +++ b/src/main/java/nitin/streams/MapWithStreams.java @@ -6,17 +6,18 @@ public class MapWithStreams { public static void main(String[] args) { - String str = "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy."; + String str = + "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy."; Map map = new HashMap<>(); - for (String s : str.split(" ")) {//String array + for (String s : str.split(" ")) { // String array map.put(s, map.getOrDefault(s, 0) + 1); } - Map filteredMap = map.entrySet() - .stream() - .filter(entry -> entry.getValue() > 1) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map filteredMap = + map.entrySet().stream() + .filter(entry -> entry.getValue() > 1) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // Use map.forEach to iterate over the map entries filteredMap.forEach((key, value) -> System.out.println(key + ": " + value)); diff --git a/src/main/java/nitin/streams/MyFunction.java b/src/main/java/nitin/streams/MyFunction.java index af14d3eb..9fe55aca 100644 --- a/src/main/java/nitin/streams/MyFunction.java +++ b/src/main/java/nitin/streams/MyFunction.java @@ -1,10 +1,8 @@ package nitin.streams; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ -//Three input parameters and the last one is the Output parameter +// Three input parameters and the last one is the Output parameter public interface MyFunction extends FunctionalInterface { R apply(T t, U u, V v); } diff --git a/src/main/java/nitin/streams/S1Introduction.java b/src/main/java/nitin/streams/S1Introduction.java index a8113921..63ac6ee7 100644 --- a/src/main/java/nitin/streams/S1Introduction.java +++ b/src/main/java/nitin/streams/S1Introduction.java @@ -5,16 +5,14 @@ import java.util.stream.Stream; /** - * Created by Nitin C on 3/3/2016. - * A stream in Java is a sequence of data - * A Stream Pileline is the operation (STREAM OPERATIONS) that run on a stream to produce a result - * Finite Streams have a limit - * infinite Streams are like sunrise/sunset cycle - *

- * SOURCE : Where the stream comes from - * INTERMEDIATE OPERATIONS : Transforms the stream into another stream. STREAMS USE LAZY EVALUATION. - * The intermediate operations do not run until the terminal operation runs. - * TERMINAL OPERATION: Actually produces a result. Stream becomes invalid after terminal operation + * Created by Nitin C on 3/3/2016. A stream in Java is a sequence of data A Stream Pileline is the + * operation (STREAM OPERATIONS) that run on a stream to produce a result Finite Streams have a + * limit infinite Streams are like sunrise/sunset cycle + * + *

SOURCE : Where the stream comes from INTERMEDIATE OPERATIONS : Transforms the stream into + * another stream. STREAMS USE LAZY EVALUATION. The intermediate operations do not run until the + * terminal operation runs. TERMINAL OPERATION: Actually produces a result. Stream becomes invalid + * after terminal operation */ public class S1Introduction { public static void main(String[] args) { @@ -23,14 +21,14 @@ public static void main(String[] args) { System.out.println(empty); List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); - //Creating a Stream from a list + // Creating a Stream from a list Stream fromList = list.stream(); - //Creating a parallel Stream + // Creating a parallel Stream Stream fromListParallel = list.parallelStream(); Stream randoms = Stream.generate(() -> Math.random()); - randoms.forEach(System.out::println);//Infinite Stream of Random numbers + randoms.forEach(System.out::println); // Infinite Stream of Random numbers // randoms.forEach((element) -> System.out.println(element)); } } diff --git a/src/main/java/nitin/streams/S2puttingTogetherThePipeline.java b/src/main/java/nitin/streams/S2puttingTogetherThePipeline.java index 9c9c6bdf..262eabe2 100644 --- a/src/main/java/nitin/streams/S2puttingTogetherThePipeline.java +++ b/src/main/java/nitin/streams/S2puttingTogetherThePipeline.java @@ -6,9 +6,7 @@ import java.util.function.Predicate; import java.util.stream.Stream; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class S2puttingTogetherThePipeline { public static void main(String[] args) { m1(); @@ -23,7 +21,7 @@ private static void m1() { Predicate gtThan = (n -> n > 30); Predicate ltThan = (n -> n < 500); - //Predicate if number is even and greater than 30 and less than 500 + // Predicate if number is even and greater than 30 and less than 500 Predicate doublePredicate = even.and(gtThan).and(ltThan); // The same functionality as below declarative can be implemented as imparative @@ -31,7 +29,7 @@ private static void m1() { list.stream() .filter(doublePredicate) .sorted() - //.limit(2) + // .limit(2) .forEach(System.out::println); } diff --git a/src/main/java/nitin/streams/StreamAssignment.java b/src/main/java/nitin/streams/StreamAssignment.java index 4ba8f764..ce7ce12b 100644 --- a/src/main/java/nitin/streams/StreamAssignment.java +++ b/src/main/java/nitin/streams/StreamAssignment.java @@ -1,36 +1,44 @@ package nitin.streams; import com.utilities.StringUtility; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.ToString; -import org.apache.commons.lang3.StringUtils; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.ToString; +import org.apache.commons.lang3.StringUtils; public class StreamAssignment { public static void main(String[] args) { List list = Arrays.asList("Great", "Grand", "Uncle"); List resultList = new ArrayList<>(); -// for (String str:list) { -// resultList.add(new StringDto(com.utilities.StringUtils.reverseString(StringUtils.upperCase(str)), Math.round(Math.random()))); -// } - - resultList = list.stream() - .map(item -> new StringDto(StringUtility.reverseString(StringUtils.upperCase(item)), Math.round(Math.random()))) - .collect(Collectors.toList()); + // for (String str:list) { + // resultList.add(new + // StringDto(com.utilities.StringUtils.reverseString(StringUtils.upperCase(str)), + // Math.round(Math.random()))); + // } + + resultList = + list.stream() + .map( + item -> + new StringDto( + StringUtility.reverseString( + StringUtils.upperCase(item)), + Math.round(Math.random()))) + .collect(Collectors.toList()); resultList.stream().forEach(item -> System.out.println(item)); System.out.println("+++++++++++++++++++++++++++++++++++++++++"); // Example 2 List resultList2 = new ArrayList<>(); - resultList2 = list.stream() - .map(item -> new SomeDto(StringUtility.reverseString((item)))) - .collect(Collectors.toList()); + resultList2 = + list.stream() + .map(item -> new SomeDto(StringUtility.reverseString((item)))) + .collect(Collectors.toList()); resultList2.stream().forEach(item -> System.out.println(item)); } @@ -49,4 +57,4 @@ class StringDto { @ToString class SomeDto { private String str; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/StreamExamples.java b/src/main/java/nitin/streams/StreamExamples.java index f97d1965..fc64701c 100755 --- a/src/main/java/nitin/streams/StreamExamples.java +++ b/src/main/java/nitin/streams/StreamExamples.java @@ -5,61 +5,47 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; -//import java.util.stream.Stream; Not needed. See commented-out line below. -/** - * Solutions to first set of Stream exercises from Java 8 tutorial at - */ +// import java.util.stream.Stream; Not needed. See commented-out line below. +/** Solutions to first set of Stream exercises from Java 8 tutorial at */ public class StreamExamples { public static void main(String[] args) { - List words = - Arrays.asList("hi", "hello", "ho la", "bye", "goodbye", "adios"); + List words = Arrays.asList("hi", "hello", "ho la", "bye", "goodbye", "adios"); // Stream wordStream = words.stream(); Then, reuse the Stream. NO!! Why not? // Problem 1 Predicate wordsWithSpace = s -> s.contains(" "); System.out.println("Words (with spaces):"); - words - .stream() - .filter(wordsWithSpace) - .forEach(s -> System.out.println(" " + s)); + words.stream().filter(wordsWithSpace).forEach(s -> System.out.println(" " + s)); // Problem 2 System.out.println("Words (no spaces):"); - words - .stream() - .filter(wordsWithSpace.negate()) - .forEach(System.out::println); + words.stream().filter(wordsWithSpace.negate()).forEach(System.out::println); // Problem 3 - List excitingWords = words.stream() - .map(s -> s + "!") - .collect(Collectors.toList()); + List excitingWords = words.stream().map(s -> s + "!").collect(Collectors.toList()); System.out.printf("Exciting words: %s.%n", excitingWords); - List eyeWords = words.stream() - .map(s -> s.replace("i", "eye")) - .collect(Collectors.toList()); + List eyeWords = + words.stream().map(s -> s.replace("i", "eye")).collect(Collectors.toList()); System.out.printf("Eye words: %s.%n", eyeWords); - List upperCaseWords = words.stream() - .map(String::toUpperCase) // or .map(s -> s.toUpperCase()) - .collect(Collectors.toList()); + List upperCaseWords = + words.stream() + .map(String::toUpperCase) // or .map(s -> s.toUpperCase()) + .collect(Collectors.toList()); System.out.printf("Uppercase words: %s.%n", upperCaseWords); // Problem 4 - List shortWords = words.stream() - .filter(s -> s.length() < 4) - .collect(Collectors.toList()); + List shortWords = + words.stream().filter(s -> s.length() < 4).collect(Collectors.toList()); System.out.printf("Short words: %s.%n", shortWords); - List wordsWithB = words.stream() - .filter(s -> s.contains("b")) - .collect(Collectors.toList()); + List wordsWithB = + words.stream().filter(s -> s.contains("b")).collect(Collectors.toList()); System.out.printf("B words: %s.%n", wordsWithB); - List evenLengthWords = words.stream() - .filter(s -> (s.length() % 2) == 0) - .collect(Collectors.toList()); + List evenLengthWords = + words.stream().filter(s -> (s.length() % 2) == 0).collect(Collectors.toList()); System.out.printf("Even-length words: %s.%n", evenLengthWords); // Problem 5, using helper method to avoid repeating code @@ -74,28 +60,28 @@ public static void main(String[] args) { System.out.println("Uppercasing " + s); return (s.toUpperCase()); }; - String result3 = words.stream() - .map(toUpper) - .filter(s -> s.length() < 4) - .filter(s -> s.contains("E")) - .findFirst().orElse("No match"); + String result3 = + words.stream() + .map(toUpper) + .filter(s -> s.length() < 4) + .filter(s -> s.contains("E")) + .findFirst() + .orElse("No match"); System.out.println("Uppercase short word with 'E': " + result3); // Problem 7 - String[] excitingWords2 = words.stream() - .map(s -> s + "!") - .toArray(String[]::new); + String[] excitingWords2 = words.stream().map(s -> s + "!").toArray(String[]::new); System.out.printf("Exciting words as array: %s.%n", Arrays.asList(excitingWords2)); } - public static String firstFunnyString(List words, - String containedTest) { + public static String firstFunnyString(List words, String containedTest) { String result = words.stream() .map(String::toUpperCase) .filter(s -> s.length() < 4) .filter(s -> s.contains(containedTest)) - .findFirst().orElse("No match"); + .findFirst() + .orElse("No match"); return (result); } } diff --git a/src/main/java/nitin/streams/StreamsWRTInheritance/StringToChar.java b/src/main/java/nitin/streams/StreamsWRTInheritance/StringToChar.java index 6a366527..4c20f0a4 100644 --- a/src/main/java/nitin/streams/StreamsWRTInheritance/StringToChar.java +++ b/src/main/java/nitin/streams/StreamsWRTInheritance/StringToChar.java @@ -1,14 +1,11 @@ package nitin.streams.StreamsWRTInheritance; -/** - * Created by nitin on Thursday, February/13/2020 at 10:26 PM - */ +/** Created by nitin on Thursday, February/13/2020 at 10:26 PM */ public class StringToChar { public static void main(String[] args) { final String str = "w00t"; - str.chars() - .forEach(aChar -> System.out.println(Character.toChars(aChar))); + str.chars().forEach(aChar -> System.out.println(Character.toChars(aChar))); str.chars() .filter(ch -> Character.isDigit(ch)) diff --git a/src/main/java/nitin/streams/StreamsWRTInheritance/StudentRunner.java b/src/main/java/nitin/streams/StreamsWRTInheritance/StudentRunner.java index ed54aa9a..1162ebde 100644 --- a/src/main/java/nitin/streams/StreamsWRTInheritance/StudentRunner.java +++ b/src/main/java/nitin/streams/StreamsWRTInheritance/StudentRunner.java @@ -2,23 +2,21 @@ import com.entity.SampleData; import com.entity.Student; - import java.util.List; import java.util.stream.Collectors; /** - * @author Created by nichaurasia - * Created on Tuesday, September/29/2020 at 10:24 PM + * @author Created by nichaurasia Created on Tuesday, September/29/2020 at 10:24 PM */ - public class StudentRunner { public static void main(String[] args) { List studentList = SampleData.getStudents(); - studentList = studentList.stream() - .filter(student -> student.getFirstName().startsWith("A")).collect(Collectors.toList()); + studentList = + studentList.stream() + .filter(student -> student.getFirstName().startsWith("A")) + .collect(Collectors.toList()); - studentList.stream() - .forEach(x -> System.out.println(x)); + studentList.stream().forEach(x -> System.out.println(x)); } } diff --git a/src/main/java/nitin/streams/StreamsWRTInheritance/TestNullability.java b/src/main/java/nitin/streams/StreamsWRTInheritance/TestNullability.java index ac244880..dd9f199a 100644 --- a/src/main/java/nitin/streams/StreamsWRTInheritance/TestNullability.java +++ b/src/main/java/nitin/streams/StreamsWRTInheritance/TestNullability.java @@ -1,8 +1,6 @@ package nitin.streams.StreamsWRTInheritance; - import com.entity.Student; - import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; @@ -18,27 +16,43 @@ public static void main(String[] args) { ZonedDateTime timeInNashville = ZonedDateTime.now(zone); - String zonedDateTime = Optional.ofNullable(timeInNashville) - .map(time -> { - String sb = "Time in " + zone + " : " + - time.format(DateTimeFormatter.ofPattern(myDateTimePattern)) + - "\n" + - "Time in " + india + " : " + - ZonedDateTime.now(india).format(DateTimeFormatter.ofPattern(myDateTimePattern)); - return sb; - }) - .orElse(""); + String zonedDateTime = + Optional.ofNullable(timeInNashville) + .map( + time -> { + String sb = + "Time in " + + zone + + " : " + + time.format( + DateTimeFormatter.ofPattern( + myDateTimePattern)) + + "\n" + + "Time in " + + india + + " : " + + ZonedDateTime.now(india) + .format( + DateTimeFormatter.ofPattern( + myDateTimePattern)); + return sb; + }) + .orElse(""); System.out.println(zonedDateTime); } public static void logStudent(Student student) { - String sb = "Result is " + - Optional.of(student.getFirstName()).orElse("") + "," + - (null != student.getLastName() ? student.getLastName() : "") + "," + - (null != student.getAddress() ? student.getAddress() : "") + "," + - (null != student.getDob() ? student.getDob() : ""); + String sb = + "Result is " + + Optional.of(student.getFirstName()).orElse("") + + "," + + (null != student.getLastName() ? student.getLastName() : "") + + "," + + (null != student.getAddress() ? student.getAddress() : "") + + "," + + (null != student.getDob() ? student.getDob() : ""); System.out.println(sb); } diff --git a/src/main/java/nitin/streams/collectors/AdvancedGrouping.java b/src/main/java/nitin/streams/collectors/AdvancedGrouping.java index 6a072984..c2a308ee 100644 --- a/src/main/java/nitin/streams/collectors/AdvancedGrouping.java +++ b/src/main/java/nitin/streams/collectors/AdvancedGrouping.java @@ -1,22 +1,21 @@ package nitin.streams.collectors; +import static com.utilities.JsonUtils.getJsonStringFromFile; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import lombok.extern.slf4j.Slf4j; -import nitin.streams.collectors.model.*; - import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; - -import static com.utilities.JsonUtils.getJsonStringFromFile; +import lombok.extern.slf4j.Slf4j; +import nitin.streams.collectors.model.*; @Slf4j public class AdvancedGrouping { @@ -27,20 +26,20 @@ public static void main(String[] args) { List> data = new ArrayList<>(); try { String response = getJsonStringFromFile("src/main/resources/json/groupingBy.json"); - data = mapper.readValue(response, new TypeReference<>() { - }); + data = mapper.readValue(response, new TypeReference<>() {}); } catch (IOException e) { log.info(e.getMessage()); } List> finalJson = generateCrossTab(data); try { - String writeValueAsString = new ObjectMapper() - .registerModule(new JavaTimeModule()) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - .setSerializationInclusion(JsonInclude.Include.ALWAYS) - .writerWithDefaultPrettyPrinter() - .writeValueAsString(finalJson); + String writeValueAsString = + new ObjectMapper() + .registerModule(new JavaTimeModule()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .setSerializationInclusion(JsonInclude.Include.ALWAYS) + .writerWithDefaultPrettyPrinter() + .writeValueAsString(finalJson); System.out.println(writeValueAsString); } catch (JsonProcessingException e) { throw new RuntimeException(e); @@ -51,11 +50,13 @@ public static List> generateCrossTab(List header = findLast13Months(); Map dto = null; - List labs = null;//list that contains elements of a type that is either LabBase or any subtype of LabBase + List labs = + null; // list that contains elements of a type that is either LabBase or any subtype + // of LabBase Function, Map> buildLabDetailsMap = null; - List additionalLabsDto = mapper.convertValue(data, new TypeReference>() { - }); + List additionalLabsDto = + mapper.convertValue(data, new TypeReference>() {}); labs = additionalLabsDto; return getMaps(labs, header); @@ -66,8 +67,8 @@ public static List> generateCrossTabPdf(List> getMaps(List labs, List

header) { + private static List> getMaps( + List labs, List
header) { Function, Map> buildLabDetailsMap; buildLabDetailsMap = AdvancedGrouping::buildLabDetailsMap; @@ -75,22 +76,24 @@ private static List> getMaps(List labs, L return returnList; } - private static List> getCrossTabMaps(List labs, - Function, Map> buildLabDetailsMap, - List
header) { + private static List> getCrossTabMaps( + List labs, + Function, Map> buildLabDetailsMap, + List
header) { - labs.sort(Comparator - .comparing(LabBase::getSortOrder, Comparator.naturalOrder()) - .thenComparing(LabBase::getDateTime, Comparator.reverseOrder())); + labs.sort( + Comparator.comparing(LabBase::getSortOrder, Comparator.naturalOrder()) + .thenComparing(LabBase::getDateTime, Comparator.reverseOrder())); Map labDetailsMap = buildLabDetailsMap.apply(labs); - CrossTable crossTable = CrossTable.builder() - .header(header) - .labDetails(new ArrayList<>(labDetailsMap.values())) - .build(); - Map additionalLabsMap = mapper.convertValue(crossTable, new TypeReference>() { - }); + CrossTable crossTable = + CrossTable.builder() + .header(header) + .labDetails(new ArrayList<>(labDetailsMap.values())) + .build(); + Map additionalLabsMap = + mapper.convertValue(crossTable, new TypeReference>() {}); List> returnList = new ArrayList<>(); returnList.add(additionalLabsMap); @@ -100,21 +103,22 @@ private static List> getCrossTabMaps(List private static Map buildLabDetailsMap(List labs) { // Group model labs by name and uom and maintain insertion order return labs.stream() - .collect(Collectors.groupingBy(lab -> lab.getName() + lab.getUom(),//Key for the Map + .collect( + Collectors.groupingBy( + lab -> lab.getName() + lab.getUom(), // Key for the Map LinkedHashMap::new, // Use LinkedHashMap as the Map implementation Collectors.collectingAndThen( - Collectors.toList(), list -> { - LabBase base = list.get(0); // Assuming first element is representative + Collectors.toList(), + list -> { + LabBase base = list.get(0); // Assuming first element is + // representative return LabDetail.builder() .name(base.getName()) .uom(base.getUom()) .sortOrder(base.getSortOrder()) .labs(createLabDataForEachRow(list)) .build(); - } - ) - ) - ); + }))); } private static List createLabDataForEachRow(List labs) { @@ -124,15 +128,17 @@ private static List createLabDataForEachRow(List labs) { for (int i = 0; i < 13; i++) { LocalDate month = currentMonth.minusMonths(i); String monthString = month.format(DateTimeFormatter.ofPattern("MMM yyyy")); - List labsForMonth = labs.stream() - .filter(lab -> lab.getDateTime().getMonth().equals(month.getMonth()) && - lab.getDateTime().getYear() == month.getYear()) - .collect(Collectors.toList()); - - Lab lab = Lab.builder() - .month(monthString) - .labsData(createLabsData(labsForMonth)) - .build(); + List labsForMonth = + labs.stream() + .filter( + lab -> + lab.getDateTime().getMonth().equals(month.getMonth()) + && lab.getDateTime().getYear() + == month.getYear()) + .collect(Collectors.toList()); + + Lab lab = + Lab.builder().month(monthString).labsData(createLabsData(labsForMonth)).build(); labDataList.add(lab); } @@ -141,11 +147,12 @@ private static List createLabDataForEachRow(List labs) { private static List createLabsData(List labs) { return labs.stream() - .map(lab -> { - LabsDatum labsDatum = new LabsDatum(); - labsDatum.setValue(lab.getValue()); - return labsDatum; - }) + .map( + lab -> { + LabsDatum labsDatum = new LabsDatum(); + labsDatum.setValue(lab.getValue()); + return labsDatum; + }) .collect(Collectors.toList()); } @@ -164,4 +171,4 @@ private static List
findLast13Months() { return header; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/C1Introduction.java b/src/main/java/nitin/streams/collectors/C1Introduction.java index c2e33106..a58acddf 100644 --- a/src/main/java/nitin/streams/collectors/C1Introduction.java +++ b/src/main/java/nitin/streams/collectors/C1Introduction.java @@ -2,43 +2,43 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.*; import java.util.stream.Collectors; public class C1Introduction { public static void main(String[] args) { - sharedMutabilityWrapper();//DO NOT DO THIS - sharedMutabilityClass();//Do not Do - sharedMutabilityReduce();//Thread safe with reduce - usingCollector();//Thread safe with collectors - creatingMap();//using key mapper adn value mapper FUNCTION + sharedMutabilityWrapper(); // DO NOT DO THIS + sharedMutabilityClass(); // Do not Do + sharedMutabilityReduce(); // Thread safe with reduce + usingCollector(); // Thread safe with collectors + creatingMap(); // using key mapper adn value mapper FUNCTION unmodifiableList(); commaSeparatedList(); - } private static void commaSeparatedList() { List employees = SampleData.getSimpleEmployees(); - //Off-by-one error + // Off-by-one error String commaSeparatedNamesWithExtra = ""; for (EmployeeSimple employeeSimple : employees) { - commaSeparatedNamesWithExtra = commaSeparatedNamesWithExtra + employeeSimple.getName() + " ,"; + commaSeparatedNamesWithExtra = + commaSeparatedNamesWithExtra + employeeSimple.getName() + " ,"; } System.out.println(commaSeparatedNamesWithExtra); - //Remove the last comma -> unnecessary smell in the code - //Write logic to remove + // Remove the last comma -> unnecessary smell in the code + // Write logic to remove - //Avoid off-by-one error,mm using joining + // Avoid off-by-one error,mm using joining String commaSeparatedNames = ""; - commaSeparatedNames = employees.stream() - .map(employeeSimple -> employeeSimple.getName()) - .filter(Objects::nonNull) - //.map(String::toUpperCase) - .collect(Collectors.joining(", ")); + commaSeparatedNames = + employees.stream() + .map(employeeSimple -> employeeSimple.getName()) + .filter(Objects::nonNull) + // .map(String::toUpperCase) + .collect(Collectors.joining(", ")); System.out.println(commaSeparatedNames); } @@ -46,18 +46,21 @@ private static void commaSeparatedList() { private static void unmodifiableList() { List employees = SampleData.getSimpleEmployees(); - //Return a map with name as key and age as value + // Return a map with name as key and age as value List ages = new ArrayList<>(); ages = Collections.unmodifiableList(ages); - ages = employees.stream() - .filter(Objects::nonNull).filter(employee -> null != employee.getAge()) - .map(employeeSimple -> employeeSimple.getAge()) - //.collect(Collectors.toList()); - .collect(Collectors.toUnmodifiableList()); + ages = + employees.stream() + .filter(Objects::nonNull) + .filter(employee -> null != employee.getAge()) + .map(employeeSimple -> employeeSimple.getAge()) + // .collect(Collectors.toList()); + .collect(Collectors.toUnmodifiableList()); - //Boom - ages.add(999);//mutability with regular collection, can be avoided by using unmodifiable list + // Boom + ages.add(999); // mutability with regular collection, can be avoided by using unmodifiable + // list System.out.println(ages); } @@ -65,14 +68,17 @@ private static void unmodifiableList() { private static void creatingMap() { List employees = SampleData.getSimpleEmployees(); - //Return a map with name as key and age as value + // Return a map with name as key and age as value Map nameAgeMap = new HashMap<>(); - nameAgeMap = employees.stream().parallel() - .filter(employee -> null != employee.getAge()) - //.collect(Collectors.toMap(keyFunction, valueFunction)); - //.collect(Collectors.toMap(employee -> employee.getName(),employee -> employee.getAge())) - .collect(Collectors.toMap(EmployeeSimple::getName, EmployeeSimple::getAge)); + nameAgeMap = + employees.stream() + .parallel() + .filter(employee -> null != employee.getAge()) + // .collect(Collectors.toMap(keyFunction, valueFunction)); + // .collect(Collectors.toMap(employee -> employee.getName(),employee -> + // employee.getAge())) + .collect(Collectors.toMap(EmployeeSimple::getName, EmployeeSimple::getAge)); System.out.println(nameAgeMap); } @@ -80,54 +86,60 @@ private static void creatingMap() { private static void usingCollector() { List employees = SampleData.getSimpleEmployees(); - //Return the list of names of employees, in upper case, younger than 25 + // Return the list of names of employees, in upper case, younger than 25 List youngEmployees = new ArrayList<>(); - youngEmployees = employees.stream() - .filter(Objects::nonNull) - .filter(employee -> null != employee.getAge()) - .filter(employee -> employee.getAge() < 25) - .map(EmployeeSimple::getName)//get the name - //.map(str -> str.toUpperCase()) - .map(String::toUpperCase)//convert to upper case - .collect(Collectors.toList());//ThreadSafe and can handle concurrency easily - //toSet can also be done with just one change + youngEmployees = + employees.stream() + .filter(Objects::nonNull) + .filter(employee -> null != employee.getAge()) + .filter(employee -> employee.getAge() < 25) + .map(EmployeeSimple::getName) // get the name + // .map(str -> str.toUpperCase()) + .map(String::toUpperCase) // convert to upper case + .collect( + Collectors + .toList()); // ThreadSafe and can handle concurrency easily + // toSet can also be done with just one change } private static void sharedMutabilityReduce() { List employees = SampleData.getSimpleEmployees(); - //Return the list of names of employees, in upper case, younger than 25 + // Return the list of names of employees, in upper case, younger than 25 List youngEmployees = new ArrayList<>(); - youngEmployees = employees.stream().parallel() - .filter(Objects::isNull) - .filter(employee -> employee.getAge() < 25) - .map(EmployeeSimple::getName)//get the name - .map(String::toUpperCase)//convert to upper case - .reduce(//Can work with parallel streams - new ArrayList(),//Local mutability, internal mutability, no outside arrayList is used - (names, name) -> {//there is no side effect - names.add(name); - return names; - }, - (names1, names2) -> {//Add all the mini lists into a bigger list - names1.addAll(names2); - return names1; - } - ); + youngEmployees = + employees.stream() + .parallel() + .filter(Objects::isNull) + .filter(employee -> employee.getAge() < 25) + .map(EmployeeSimple::getName) // get the name + .map(String::toUpperCase) // convert to upper case + .reduce( // Can work with parallel streams + new ArrayList< + String>(), // Local mutability, internal mutability, no + // outside arrayList is used + (names, name) -> { // there is no side effect + names.add(name); + return names; + }, + (names1, names2) -> { // Add all the mini lists into a bigger list + names1.addAll(names2); + return names1; + }); } private static void sharedMutabilityWrapper() { List numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - //Create a list of double of even numbers + // Create a list of double of even numbers List doubleOfEven = new ArrayList<>(); numbers.stream() .filter(e -> e % 2 == 0) .map(e -> e * 2) - .forEach(e -> doubleOfEven.add(e));//Shared mutability. + .forEach(e -> doubleOfEven.add(e)); // Shared mutability. System.out.println(doubleOfEven); } @@ -135,15 +147,19 @@ private static void sharedMutabilityWrapper() { private static void sharedMutabilityClass() { List employees = SampleData.getSimpleEmployees(); - //Return the list of names of employees, in upper case, younger than 25 + // Return the list of names of employees, in upper case, younger than 25 List youngEmployees = new ArrayList<>(); - employees.stream().parallel() + employees.stream() + .parallel() .filter(Objects::isNull) .filter(employee -> employee.getAge() < 25) - .map(EmployeeSimple::getName)//get the name - .map(String::toUpperCase)//convert to upper case - .forEach(upprCaseEmp -> youngEmployees.add(upprCaseEmp)); //Don't do this. Shared mutabilty is evil. - //This code can't ever be parallelized and it will misbehave. + .map(EmployeeSimple::getName) // get the name + .map(String::toUpperCase) // convert to upper case + .forEach( + upprCaseEmp -> + youngEmployees.add( + upprCaseEmp)); // Don't do this. Shared mutabilty is evil. + // This code can't ever be parallelized and it will misbehave. } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/TransactionFlatMapAndGroupByMonthExample.java b/src/main/java/nitin/streams/collectors/TransactionFlatMapAndGroupByMonthExample.java index 40e1d744..d81389e9 100644 --- a/src/main/java/nitin/streams/collectors/TransactionFlatMapAndGroupByMonthExample.java +++ b/src/main/java/nitin/streams/collectors/TransactionFlatMapAndGroupByMonthExample.java @@ -4,10 +4,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; - import java.io.File; import java.io.IOException; import java.time.LocalDate; @@ -15,6 +11,9 @@ import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; public class TransactionFlatMapAndGroupByMonthExample { static ObjectMapper objectMapper = new ObjectMapper(); @@ -23,37 +22,53 @@ public static void main(String[] args) throws IOException { objectMapper.registerModule(new JavaTimeModule()); String filePath = "src/main/resources/json/transactions.json"; - List transactions = objectMapper.readValue(new File(filePath), new TypeReference>() { - }); + List transactions = + objectMapper.readValue( + new File(filePath), new TypeReference>() {}); // FlatMap transactions to items, sum by item name, and then group totals by month - Map> sortedMap = transactions.stream() - .flatMap(transaction -> transaction.getItems().stream() - .map(item -> new TransactionItem( - YearMonth.from(transaction.getDate()), - item.getName(), item.getAmount()))) - .collect(Collectors.groupingBy( - TransactionItem::getMonthAndYear, - TreeMap::new, // Use TreeMap to sort by key (YearMonth) - Collectors.groupingBy( - TransactionItem::getItemName, - Collectors.summingInt(TransactionItem::getAmount)) - )); + Map> sortedMap = + transactions.stream() + .flatMap( + transaction -> + transaction.getItems().stream() + .map( + item -> + new TransactionItem( + YearMonth.from( + transaction + .getDate()), + item.getName(), + item.getAmount()))) + .collect( + Collectors.groupingBy( + TransactionItem::getMonthAndYear, + TreeMap::new, // Use TreeMap to sort by key (YearMonth) + Collectors.groupingBy( + TransactionItem::getItemName, + Collectors.summingInt( + TransactionItem::getAmount)))); // Sort the amounts for each item within each month in decreasing order - sortedMap.replaceAll((month, itemTotals) -> - itemTotals.entrySet().stream() - .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) - .collect(Collectors.toMap( - Map.Entry::getKey, Map.Entry::getValue, - (oldValue, newValue) -> oldValue, LinkedHashMap::new))); + sortedMap.replaceAll( + (month, itemTotals) -> + itemTotals.entrySet().stream() + .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (oldValue, newValue) -> oldValue, + LinkedHashMap::new))); // Print the sorted map - sortedMap.forEach((month, itemTotals) -> { - System.out.println("Month: " + month.format(DateTimeFormatter.ofPattern("MMM yyyy"))); - itemTotals.forEach((item, total) -> - System.out.println(" " + item + ": $" + total)); - }); + sortedMap.forEach( + (month, itemTotals) -> { + System.out.println( + "Month: " + month.format(DateTimeFormatter.ofPattern("MMM yyyy"))); + itemTotals.forEach( + (item, total) -> System.out.println(" " + item + ": $" + total)); + }); } } @@ -64,6 +79,7 @@ public static void main(String[] args) throws IOException { class Transaction { @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate date; + private List items; } @@ -84,4 +100,4 @@ class TransactionItem { private YearMonth monthAndYear; // Custom key combining month and year private String itemName; private int amount; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/c1collect/ParentDto.java b/src/main/java/nitin/streams/collectors/c1collect/ParentDto.java index 77be74b3..7e030aba 100644 --- a/src/main/java/nitin/streams/collectors/c1collect/ParentDto.java +++ b/src/main/java/nitin/streams/collectors/c1collect/ParentDto.java @@ -1,12 +1,11 @@ package nitin.streams.collectors.c1collect; +import java.util.List; import lombok.Builder; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.List; - @Getter @Setter @Builder diff --git a/src/main/java/nitin/streams/collectors/c1collect/ParentDtoSingletonList.java b/src/main/java/nitin/streams/collectors/c1collect/ParentDtoSingletonList.java index c91ee774..4a18ec2c 100644 --- a/src/main/java/nitin/streams/collectors/c1collect/ParentDtoSingletonList.java +++ b/src/main/java/nitin/streams/collectors/c1collect/ParentDtoSingletonList.java @@ -5,10 +5,13 @@ public class ParentDtoSingletonList { public static void main(String[] args) { - ParentDto parentDto = ParentDto.builder() - .integerList(Arrays.asList(3, 1, 8, 6, 9, 7)) - .stringList(Arrays.asList("quit", "squid", "book", "bookkeeper", "keep", "steep")) - .build(); + ParentDto parentDto = + ParentDto.builder() + .integerList(Arrays.asList(3, 1, 8, 6, 9, 7)) + .stringList( + Arrays.asList( + "quit", "squid", "book", "bookkeeper", "keep", "steep")) + .build(); Integer i = parentDto.getIntegerList().get(0); parentDto.setIntegerList(Collections.singletonList(i)); diff --git a/src/main/java/nitin/streams/collectors/c1collect/S1collect_toList_toMap.java b/src/main/java/nitin/streams/collectors/c1collect/S1collect_toList_toMap.java index 276b88a0..e0406337 100644 --- a/src/main/java/nitin/streams/collectors/c1collect/S1collect_toList_toMap.java +++ b/src/main/java/nitin/streams/collectors/c1collect/S1collect_toList_toMap.java @@ -1,46 +1,43 @@ package nitin.streams.collectors.c1collect; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.*; + import java.util.List; import java.util.Map; -import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.*; - -/** - * Created by Nitin Chaurasia on 1/31/18 at 12:05 AM. - */ +/** Created by Nitin Chaurasia on 1/31/18 at 12:05 AM. */ public class S1collect_toList_toMap { public static void main(String[] args) { List list = List.of("Pawan", "Chiranjeevi", "RaviTeja", "Venkatesh", "Nagarjuna"); System.out.println(list); - //Create a now list with actors having names longer than 9 characters - List l = list.stream() - .filter(str -> str.length() >= 9) - .toList(); - //System.out.println(l); + // Create a now list with actors having names longer than 9 characters + List l = list.stream().filter(str -> str.length() >= 9).toList(); + // System.out.println(l); - //Defining boolean predicate to test if the string is shorter than 9 characters + // Defining boolean predicate to test if the string is shorter than 9 characters Predicate strShort = (str -> str.length() < 9); - //Create another list of short characters - List l1 = list.stream() - .filter(strShort) - .toList(); - //System.out.println(l1); + // Create another list of short characters + List l1 = list.stream().filter(strShort).toList(); + // System.out.println(l1); /* MAP */ - //Change all the names to uppercase + // Change all the names to uppercase // Using a function as a return value is expected - Map map = list.stream() - .collect(Collectors.toMap(identity(), String::length)); + Map map = + list.stream().collect(Collectors.toMap(identity(), String::length)); System.out.println(map); - Map> collect = list.stream() - .collect(groupingBy(str -> str.length(), mapping(str->str.toUpperCase(),toList()))); + Map> collect = + list.stream() + .collect( + groupingBy( + str -> str.length(), + mapping(str -> str.toUpperCase(), toList()))); System.out.println(collect); } } diff --git a/src/main/java/nitin/streams/collectors/c1collect/S2CollectorToSet.java b/src/main/java/nitin/streams/collectors/c1collect/S2CollectorToSet.java index 02f5dede..f05297c7 100644 --- a/src/main/java/nitin/streams/collectors/c1collect/S2CollectorToSet.java +++ b/src/main/java/nitin/streams/collectors/c1collect/S2CollectorToSet.java @@ -9,10 +9,10 @@ public class S2CollectorToSet { public static void main(String[] args) { List intList = Arrays.asList(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - Set intSet = intList - .stream() - //do Whatever you like - .collect(Collectors.toSet()); + Set intSet = + intList.stream() + // do Whatever you like + .collect(Collectors.toSet()); System.out.println(intList); System.out.println(intSet); diff --git a/src/main/java/nitin/streams/collectors/c1collect/S2collectUnmodifiable.java b/src/main/java/nitin/streams/collectors/c1collect/S2collectUnmodifiable.java index b18ac01f..bd68e5c9 100644 --- a/src/main/java/nitin/streams/collectors/c1collect/S2collectUnmodifiable.java +++ b/src/main/java/nitin/streams/collectors/c1collect/S2collectUnmodifiable.java @@ -2,16 +2,15 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.List; import java.util.stream.Collectors; public class S2collectUnmodifiable { public static void main(String[] args) { List simpleEmployees = SampleData.getSimpleEmployees(); - List collect = simpleEmployees - .stream() - .collect(Collectors.toUnmodifiableList()); - collect.add(new EmployeeSimple()); //throws UnsupportedOperationException because we are collecting simpleEmployeeList as a unmodifiable list + List collect = + simpleEmployees.stream().collect(Collectors.toUnmodifiableList()); + collect.add(new EmployeeSimple()); // throws UnsupportedOperationException because we are + // collecting simpleEmployeeList as a unmodifiable list } } diff --git a/src/main/java/nitin/streams/collectors/c1collect/S3ColectorToMap.java b/src/main/java/nitin/streams/collectors/c1collect/S3ColectorToMap.java index f2995a00..ede51922 100644 --- a/src/main/java/nitin/streams/collectors/c1collect/S3ColectorToMap.java +++ b/src/main/java/nitin/streams/collectors/c1collect/S3ColectorToMap.java @@ -10,9 +10,9 @@ public class S3ColectorToMap { public static void main(String[] args) { List intList = Arrays.asList(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - Map map = intList - .stream() - .collect(Collectors.toMap(Function.identity(), x -> x + x));//Check + Map map = + intList.stream() + .collect(Collectors.toMap(Function.identity(), x -> x + x)); // Check System.out.println(map); } diff --git a/src/main/java/nitin/streams/collectors/c2partitioning/Intro.java b/src/main/java/nitin/streams/collectors/c2partitioning/Intro.java index eacbf419..e69e2a0f 100644 --- a/src/main/java/nitin/streams/collectors/c2partitioning/Intro.java +++ b/src/main/java/nitin/streams/collectors/c2partitioning/Intro.java @@ -1,9 +1,9 @@ package nitin.streams.collectors.c2partitioning; +import static java.util.stream.Collectors.partitioningBy; import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.Arrays; import java.util.List; import java.util.Map; @@ -11,20 +11,19 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import static java.util.stream.Collectors.partitioningBy; - public class Intro { public static void main(String[] args) { List list = Arrays.asList(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - //Splits in true list and false list. Keys = Boolean - Map> collect = list.stream() - .collect(partitioningBy(number -> number % 2 == 0)); - System.out.println(collect);//{false=[1, 1, 3, 3, 5, 7, 5, 3, 1], true=[2, 4, 6, 8, 6, 4, 2]} + // Splits in true list and false list. Keys = Boolean + Map> collect = + list.stream().collect(partitioningBy(number -> number % 2 == 0)); + System.out.println( + collect); // {false=[1, 1, 3, 3, 5, 7, 5, 3, 1], true=[2, 4, 6, 8, 6, 4, 2]} - List employees = SampleData.getSimpleEmployees();//Call from DB - //Split the list into 2 sub list based on even and odd age + List employees = SampleData.getSimpleEmployees(); // Call from DB + // Split the list into 2 sub list based on even and odd age splitEmpList(employees); doNotDo(employees); @@ -33,25 +32,32 @@ public static void main(String[] args) { private static void splitEmpList(List employees) { Predicate evenAgedEmpPredicate = emp -> emp.getAge() % 2 == 0; - Map> listMap = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()) - .filter(emp -> null != emp.getAge()) - //.collect(partitioningBy(x -> evenAgedEmpPredicate.test(x))); - .collect(partitioningBy(evenAgedEmpPredicate));//⌘Cmd ⌥Opt V Declare the variable - + Map> listMap = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getAge()) + // .collect(partitioningBy(x -> evenAgedEmpPredicate.test(x))); + .collect( + partitioningBy( + evenAgedEmpPredicate)); // ⌘Cmd ⌥Opt V Declare the variable System.out.println(listMap); } private static void doNotDo(List employees) { - List evenAgedEmp = employees.stream() - .filter(Objects::isNull).filter(emp -> null != emp.getAge()) - .filter(employee -> employee.getAge() % 2 == 0) - .collect(Collectors.toList()); - - List oddAgedEmp = employees.stream() - .filter(Objects::isNull).filter(emp -> null != emp.getAge()) - .filter(employee -> employee.getAge() % 2 != 0) - .collect(Collectors.toList()); + List evenAgedEmp = + employees.stream() + .filter(Objects::isNull) + .filter(emp -> null != emp.getAge()) + .filter(employee -> employee.getAge() % 2 == 0) + .collect(Collectors.toList()); + + List oddAgedEmp = + employees.stream() + .filter(Objects::isNull) + .filter(emp -> null != emp.getAge()) + .filter(employee -> employee.getAge() % 2 != 0) + .collect(Collectors.toList()); } } diff --git a/src/main/java/nitin/streams/collectors/c3groupby/C3GroupBy.java b/src/main/java/nitin/streams/collectors/c3groupby/C3GroupBy.java index 116202eb..3b2a203c 100644 --- a/src/main/java/nitin/streams/collectors/c3groupby/C3GroupBy.java +++ b/src/main/java/nitin/streams/collectors/c3groupby/C3GroupBy.java @@ -1,115 +1,174 @@ package nitin.streams.collectors.c3groupby; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.*; + import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.*; - public class C3GroupBy { public static void main(String[] args) { List list = Arrays.asList(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - Function, List> numbers = Function.identity(); //returns function that always returns its input argument + Function, List> numbers = + Function.identity(); // returns function that always returns its input argument List inputNumbers = numbers.apply(list); System.out.println(inputNumbers); groupStringsBySize(); findFrequencyOfRepeatedNumbers(); - empGroupByName();//Group By Name + empGroupByName(); // Group By Name ageByName(); - countByName();//Name and its count (frequency - countIntByName();//Name and its count (frequency)- collectingAndThen + countByName(); // Name and its count (frequency + countIntByName(); // Name and its count (frequency)- collectingAndThen groupByAge(); } private static void groupStringsBySize() { List strings = Arrays.asList("apple", "banana", "cherry", "date"); // The Map will have the lengths as keys and lists of strings with those lengths as values - Map> categorizedByLength = strings.stream() - //.collect(Collectors.groupingBy(str -> str.length(), Collectors.toList()));//Two-Argument groupingBy: Uses the classifier function and a specified downstream collector to determine how the grouped elements are collected. - .collect(Collectors.groupingBy(String::length));//Single-Argument groupingBy: Uses the classifier function and defaults to collecting elements into a List. - System.out.println(categorizedByLength);//{4=[date], 5=[apple], 6=[banana, cherry]} + Map> categorizedByLength = + strings.stream() + // .collect(Collectors.groupingBy(str -> str.length(), + // Collectors.toList()));//Two-Argument groupingBy: Uses the classifier + // function and a specified downstream collector to determine how the + // grouped elements are collected. + .collect( + Collectors.groupingBy( + String::length)); // Single-Argument groupingBy: Uses the + // classifier function and defaults to + // collecting elements into a List. + System.out.println(categorizedByLength); // {4=[date], 5=[apple], 6=[banana, cherry]} } private static void findFrequencyOfRepeatedNumbers() { List list = getEvenNumberList(); - //Find frequency of all the numbers - Map map = list.stream() - //.collect(groupingBy(element -> element, counting()));// Function.identity() Equivalent to an i in a for loop - .collect(groupingBy(identity(), counting()));//collect takes a COLLECTOR as parameter(with single argument overloaded method). any method that returns a collector can be used - - System.out.println(map);//{1=3, 2=2, 3=3, 4=2, 5=2, 6=2, 7=1, 8=1} + // Find frequency of all the numbers + Map map = + list.stream() + // .collect(groupingBy(element -> element, counting()));// + // Function.identity() Equivalent to an i in a for loop + .collect( + groupingBy( + identity(), + counting())); // collect takes a COLLECTOR as parameter(with + // single argument overloaded method). any + // method that returns a collector can be used + + System.out.println(map); // {1=3, 2=2, 3=3, 4=2, 5=2, 6=2, 7=1, 8=1} } private static void empGroupByName() { List employees = SampleData.getSimpleEmployees(); - Map> byName = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()) - //.collect(Collectors.groupingBy(emp -> emp.getName())); - .collect(groupingBy(EmployeeSimple::getName));//Grouping By -> Taking function as a parameter + Map> byName = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + // .collect(Collectors.groupingBy(emp -> emp.getName())); + .collect( + groupingBy( + EmployeeSimple + ::getName)); // Grouping By -> Taking function as a + // parameter System.out.println("By Name :: " + byName); } private static void ageByName() { List employees = SampleData.getSimpleEmployees(); -// Map> byName = employees.stream() -// .map(emp -> emp.getAge())//Lost it... from Stream of Emp it becomes Stream of String. Age is lost - - Map> byName = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - .collect(groupingBy(EmployeeSimple::getName, - Collectors.mapping(EmployeeSimple::getAge, Collectors.toList())));//Grouping By Overloaded -> Taking function as a parameter and another collector - - //Recursive Structure - //Collector(Function, Collector(Function, Collector)) - System.out.println("Age By Name :: "+byName); - Map> byNameSet = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - .collect( - groupingBy(EmployeeSimple::getName, - Collectors.mapping(EmployeeSimple::getAge, Collectors.toSet())));//Grouping By Overloaded -> Taking function as a parameter and another collector - - //Recursive Structure - //Collector(Function, Collector(Function, Collector)) + // Map> byName = employees.stream() + // .map(emp -> emp.getAge())//Lost it... from Stream of Emp it becomes Stream + // of String. Age is lost + + Map> byName = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + .collect( + groupingBy( + EmployeeSimple::getName, + Collectors.mapping( + EmployeeSimple::getAge, + Collectors.toList()))); // Grouping By Overloaded -> + // Taking function as a + // parameter and another + // collector + + // Recursive Structure + // Collector(Function, Collector(Function, Collector)) + System.out.println("Age By Name :: " + byName); + Map> byNameSet = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + .collect( + groupingBy( + EmployeeSimple::getName, + Collectors.mapping( + EmployeeSimple::getAge, + Collectors.toSet()))); // Grouping By Overloaded -> + // Taking function as a + // parameter and another + // collector + + // Recursive Structure + // Collector(Function, Collector(Function, Collector)) System.out.println("Age By Name (Set):: " + byNameSet); } private static void countByName() { List employees = SampleData.getSimpleEmployees(); - Map byName = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - .collect(groupingBy(EmployeeSimple::getName, counting()));//Grouping By Overloaded -> Taking function as a parameter and another collector - - System.out.println("Count By Name : "+byName); + Map byName = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + .collect( + groupingBy( + EmployeeSimple::getName, + counting())); // Grouping By Overloaded -> Taking function + // as a parameter and another collector + + System.out.println("Count By Name : " + byName); } private static void countIntByName() { List employees = SampleData.getSimpleEmployees(); - //groupingBy and mapping (apply a Function, and then Collector as a second argument) - //collectingAndThen (Collection, then use a Function as a second argument) - Map byName = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - //.collect(groupingBy(EmployeeSimple::getName, collectingAndThen(counting(), value -> value.intValue()))); - .collect(groupingBy(EmployeeSimple::getName, collectingAndThen(counting(), Long::intValue)));//Perform a transformation and then keep in the bucket - - System.out.println("Name and its count (frequency) : "+byName); + // groupingBy and mapping (apply a Function, and then Collector as a second argument) + // collectingAndThen (Collection, then use a Function as a second argument) + Map byName = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + // .collect(groupingBy(EmployeeSimple::getName, + // collectingAndThen(counting(), value -> value.intValue()))); + .collect( + groupingBy( + EmployeeSimple::getName, + collectingAndThen( + counting(), + Long::intValue))); // Perform a transformation + // and then keep in the + // bucket + + System.out.println("Name and its count (frequency) : " + byName); } private static List getEvenNumberList() { List list = List.of(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - List evenNumberList = list.stream() - .collect(filtering(number -> number % 2 == 0, toList())); - //System.out.println(evenNumberList);//[2, 4, 6, 8, 6, 4, 2] + List evenNumberList = + list.stream().collect(filtering(number -> number % 2 == 0, toList())); + // System.out.println(evenNumberList);//[2, 4, 6, 8, 6, 4, 2] return list; } @@ -119,11 +178,14 @@ private static void groupByAge() { Predicate ageNotNull = emp -> null != emp.getAge(); Predicate salaryNotNull = emp -> null != emp.getSalary(); - Map> expByAge = empSimple - .stream() - .filter(ageNotNull) - .filter(salaryNotNull) - .collect(groupingBy(EmployeeSimple::getAge, mapping(EmployeeSimple::getExperience, toSet()))); + Map> expByAge = + empSimple.stream() + .filter(ageNotNull) + .filter(salaryNotNull) + .collect( + groupingBy( + EmployeeSimple::getAge, + mapping(EmployeeSimple::getExperience, toSet()))); System.out.println("experience by age" + expByAge); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/c3groupby/FrequencyCalc.java b/src/main/java/nitin/streams/collectors/c3groupby/FrequencyCalc.java index cbcc2680..c9f1674d 100644 --- a/src/main/java/nitin/streams/collectors/c3groupby/FrequencyCalc.java +++ b/src/main/java/nitin/streams/collectors/c3groupby/FrequencyCalc.java @@ -1,27 +1,22 @@ package nitin.streams.collectors.c3groupby; -import com.entity.EmployeeSimple; -import com.entity.SampleData; +import static java.util.stream.Collectors.*; import java.util.*; import java.util.function.Function; -import java.util.function.Predicate; import java.util.stream.Collectors; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.*; - public class FrequencyCalc { public static void main(String[] args) { List list = Arrays.asList(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - //Find frequency of all the numbers using groupBy and streams + // Find frequency of all the numbers using groupBy and streams frequencyByGroupingBy(list); - //Collectors is available Since: 1.8 - //Collections class is a member of the Java Collections Framework Since: 1.2 + // Collectors is available Since: 1.8 + // Collections class is a member of the Java Collections Framework Since: 1.2 - //Counting By frequency : Collections.frequency() + // Counting By frequency : Collections.frequency() freqWithCollectionsFrequency(list); // Imperative Style frequency calculation @@ -30,16 +25,22 @@ public static void main(String[] args) { } private static void frequencyByGroupingBy(List list) { - Map freqMapStreams = list.stream() - //.collect(groupingBy(element -> element, counting()));// Function.identity() Equivalent to an i in a for loop - .collect(Collectors.groupingBy(Function.identity(), counting()));//collect takes a COLLECTOR as parameter. any method that returns a collector can be used - System.out.println(freqMapStreams);//{1=3, 2=2, 3=3, 4=2, 5=2, 6=2, 7=1, 8=1} + Map freqMapStreams = + list.stream() + // .collect(groupingBy(element -> element, counting()));// + // Function.identity() Equivalent to an i in a for loop + .collect( + Collectors.groupingBy( + Function.identity(), + counting())); // collect takes a COLLECTOR as parameter. any + // method that returns a collector can be used + System.out.println(freqMapStreams); // {1=3, 2=2, 3=3, 4=2, 5=2, 6=2, 7=1, 8=1} } private static void frequencyWithGetOrDefault(List list) { Map map = new HashMap<>(); for (Integer x : list) { - map.put(x, map.getOrDefault(x, 0) + 1);//default to 0 and adding 1 + map.put(x, map.getOrDefault(x, 0) + 1); // default to 0 and adding 1 } System.out.println(map); } @@ -54,15 +55,13 @@ private static void freqWithCollectionsFrequency(List list) { } private static void frequencyWithMap_Old(List list) { - //Old way of doing + // Old way of doing Map freqMap = new HashMap<>(); for (Integer i : list) { - //freqMap.put(i, freqMap.getOrDefault(i, 0) + 1); - if (freqMap.containsKey(i)) - freqMap.put(i, freqMap.get(i) + 1); - else - freqMap.put(i, 1); + // freqMap.put(i, freqMap.getOrDefault(i, 0) + 1); + if (freqMap.containsKey(i)) freqMap.put(i, freqMap.get(i) + 1); + else freqMap.put(i, 1); } System.out.println(freqMap); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/c4filteringAndMapping/F1MappingNfiltering.java b/src/main/java/nitin/streams/collectors/c4filteringAndMapping/F1MappingNfiltering.java index 0a35e72f..567911d6 100644 --- a/src/main/java/nitin/streams/collectors/c4filteringAndMapping/F1MappingNfiltering.java +++ b/src/main/java/nitin/streams/collectors/c4filteringAndMapping/F1MappingNfiltering.java @@ -1,26 +1,25 @@ package nitin.streams.collectors.c4filteringAndMapping; +import static java.util.stream.Collectors.*; + import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; -import static java.util.stream.Collectors.*; - public class F1MappingNfiltering { public static void main(String[] args) { tests(); } private static void tests() { - //return a map (age : names as value) with names greater than 4 characters. + // return a map (age : names as value) with names greater than 4 characters. List employees = SampleData.getSimpleEmployees(); - //mapListObject(employees); + // mapListObject(employees); listAge_Name_UsingMapping(employees); setAge_Name_usingMapping(employees); @@ -28,40 +27,59 @@ private static void tests() { } private static void listAge_Name_UsingMapping_withFilter(List employees) { - Map> collect3 = employees - .parallelStream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(groupingBy(EmployeeSimple::getAge, - mapping(EmployeeSimple::getName, - filtering(name -> name.length() < 4, - flatMapping(name -> List.of(name, name.toUpperCase(), name.toLowerCase()).stream(), toSet()) - ) - ) - ) - ); + Map> collect3 = + employees.parallelStream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .collect( + groupingBy( + EmployeeSimple::getAge, + mapping( + EmployeeSimple::getName, + filtering( + name -> name.length() < 4, + flatMapping( + name -> + List.of( + name, + name.toUpperCase(), + name.toLowerCase()) + .stream(), + toSet()))))); System.out.println(collect3); - } private static void setAge_Name_usingMapping(List employees) { - Map> collect3 = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()) - .collect(groupingBy(EmployeeSimple::getAge, mapping(e -> e.getName(), toList()))); + Map> collect3 = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .collect( + groupingBy( + EmployeeSimple::getAge, + mapping(e -> e.getName(), toList()))); System.out.println(collect3); } private static void listAge_Name_UsingMapping(List employees) { - Map> collect = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()) - .collect(groupingBy(EmployeeSimple::getAge, mapping(e -> e.getName(), Collectors.toSet()))); + Map> collect = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .collect( + groupingBy( + EmployeeSimple::getAge, + mapping(e -> e.getName(), Collectors.toSet()))); System.out.println(collect); } private static void mapListObject(List employees) { - Map> collect1 = employees.stream() - .filter(Objects::nonNull) - .filter(emp -> null != emp.getAge()) - .collect(groupingBy(EmployeeSimple::getAge)); + Map> collect1 = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .collect(groupingBy(EmployeeSimple::getAge)); System.out.println(collect1); } } diff --git a/src/main/java/nitin/streams/collectors/c5flatMapping/C6FlatMapping.java b/src/main/java/nitin/streams/collectors/c5flatMapping/C6FlatMapping.java index d1fb2610..5462c6af 100644 --- a/src/main/java/nitin/streams/collectors/c5flatMapping/C6FlatMapping.java +++ b/src/main/java/nitin/streams/collectors/c5flatMapping/C6FlatMapping.java @@ -1,32 +1,32 @@ package nitin.streams.collectors.c5flatMapping; +import static java.util.stream.Collectors.*; + import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.List; import java.util.Objects; import java.util.stream.Collectors; -import static java.util.stream.Collectors.*; - public class C6FlatMapping { // Stream flatMap(Function> mapper); // Stream map (Function mapper); - //groupingBy, mapping, filtering -> taking first argument (function or predicate) and second argument as Collector + // groupingBy, mapping, filtering -> taking first argument (function or predicate) and second + // argument as Collector // It means, first apply the function or Predicate and then Collect - //collectingAndThen -> Collector as first argument adn then Function as second argument + // collectingAndThen -> Collector as first argument adn then Function as second argument - //map first and flattening later -> mapFlattening -> flatMap + // map first and flattening later -> mapFlattening -> flatMap public static void main(String[] args) { List numbers = List.of(1, 2, 3, 4); one2one(numbers); one2Many(numbers); one2manyFlatMap(numbers); - //Find the age and unique characters in employees name + // Find the age and unique characters in employees name findAgeAndUniqueChars(); } @@ -34,47 +34,53 @@ private static void findAgeAndUniqueChars() { List employees = SampleData.getSimpleEmployees(); System.out.println( - employees - .stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(groupingBy(EmployeeSimple::getAge, - mapping(EmployeeSimple::getName, - //filtering(name -> name.length() < 4, - Collectors.flatMapping(name -> List.of(name.split("")).stream(), toList()) - //) - ) - ) - ) - ); - + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .collect( + groupingBy( + EmployeeSimple::getAge, + mapping( + EmployeeSimple::getName, + // filtering(name -> name.length() < 4, + Collectors.flatMapping( + name -> List.of(name.split("")).stream(), + toList()) + // ) + )))); } private static void one2manyFlatMap(List numbers) { - //one-to-many function - //Stream.map(oneToManyFunction) ==> Stream (not Stream of List of R) - List one2manyflatMap = numbers.stream() - .flatMap(element -> List.of(element + 1, element - 1).stream()) - .collect(Collectors.toList()); - //FlatMap is MapFlatten, map first then flat, takes an iterator and a Stream is a iterator + // one-to-many function + // Stream.map(oneToManyFunction) ==> Stream (not Stream of List of R) + List one2manyflatMap = + numbers.stream() + .flatMap(element -> List.of(element + 1, element - 1).stream()) + .collect(Collectors.toList()); + // FlatMap is MapFlatten, map first then flat, takes an iterator and a Stream is a iterator System.out.println(one2manyflatMap); } private static void one2Many(List numbers) { - //one-to-many - //Stream.map(oneToManyFunction) ==> Stream> - List> one2many = numbers.stream() - .map(element -> List.of(element + 1, element - 1)) - .collect(Collectors.toList()); - //use Case : Given a list of employees, give the personal email id's + // one-to-many + // Stream.map(oneToManyFunction) ==> Stream> + List> one2many = + numbers.stream() + .map(element -> List.of(element + 1, element - 1)) + .collect(Collectors.toList()); + // use Case : Given a list of employees, give the personal email id's System.out.println(one2many); } private static void one2one(List numbers) { - //one-to-one function - //Stream.map(oneToOneFunction) ==> Stream - List one2one = numbers.stream() - .map(element -> element * 2)//Takes a Stream of and returns a Stream of - .collect(Collectors.toList()); + // one-to-one function + // Stream.map(oneToOneFunction) ==> Stream + List one2one = + numbers.stream() + .map(element -> element * 2) // Takes a Stream of and returns a Stream + // of + .collect(Collectors.toList()); System.out.println(one2one); } } diff --git a/src/main/java/nitin/streams/collectors/c5flatMapping/FlatMappingString.java b/src/main/java/nitin/streams/collectors/c5flatMapping/FlatMappingString.java index 4784316c..c0cf28ba 100644 --- a/src/main/java/nitin/streams/collectors/c5flatMapping/FlatMappingString.java +++ b/src/main/java/nitin/streams/collectors/c5flatMapping/FlatMappingString.java @@ -1,20 +1,22 @@ package nitin.streams.collectors.c5flatMapping; +import static java.util.stream.Collectors.toList; + import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; -import static java.util.stream.Collectors.toList; - public class FlatMappingString { public static void main(String[] args) { - List list = List.of("one", "two wings", "three tyres", "four turbo combustion engine"); - //Fnd a list of each word separated without space - List collect = list.stream() - .collect(Collectors - .flatMapping(str -> Stream.of(str.split(" ")), toList()) - ); + List list = + List.of("one", "two wings", "three tyres", "four turbo combustion engine"); + // Fnd a list of each word separated without space + List collect = + list.stream() + .collect( + Collectors.flatMapping(str -> Stream.of(str.split(" ")), toList())); - System.out.println(collect);//[one, two, wings, three, tyres, four, turbo, combustion, engine] + System.out.println( + collect); // [one, two, wings, three, tyres, four, turbo, combustion, engine] } } diff --git a/src/main/java/nitin/streams/collectors/c5flatMapping/Mapping.java b/src/main/java/nitin/streams/collectors/c5flatMapping/Mapping.java index 658da297..26ffb7a3 100644 --- a/src/main/java/nitin/streams/collectors/c5flatMapping/Mapping.java +++ b/src/main/java/nitin/streams/collectors/c5flatMapping/Mapping.java @@ -7,9 +7,10 @@ public class Mapping { public static void main(String[] args) { List list = List.of(1, 2, 1, 3, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3, 2, 1); - List doubleNumberList = list.stream() - .distinct()//Finds unique elements - .collect(Collectors.mapping(number -> number * 2, Collectors.toList())); - System.out.println(doubleNumberList);//[2, 4, 6, 8, 10, 12, 14, 16] + List doubleNumberList = + list.stream() + .distinct() // Finds unique elements + .collect(Collectors.mapping(number -> number * 2, Collectors.toList())); + System.out.println(doubleNumberList); // [2, 4, 6, 8, 10, 12, 14, 16] } } diff --git a/src/main/java/nitin/streams/collectors/c6joining/JoinTest.java b/src/main/java/nitin/streams/collectors/c6joining/JoinTest.java index 48505585..b41ebdad 100644 --- a/src/main/java/nitin/streams/collectors/c6joining/JoinTest.java +++ b/src/main/java/nitin/streams/collectors/c6joining/JoinTest.java @@ -7,10 +7,9 @@ public class JoinTest { public static void main(String[] args) { List strings = List.of("java", "is", "cool"); String message = String.join(" ", strings); - System.out.println(message);//Java is cool + System.out.println(message); // Java is cool - String test = strings.stream() - .collect(Collectors.joining(",")); - System.out.println(test);//java,is,cool + String test = strings.stream().collect(Collectors.joining(",")); + System.out.println(test); // java,is,cool } } diff --git a/src/main/java/nitin/streams/collectors/c7collectingAndThen/F2ThenComposing.java b/src/main/java/nitin/streams/collectors/c7collectingAndThen/F2ThenComposing.java index 69078f02..d6601ba7 100644 --- a/src/main/java/nitin/streams/collectors/c7collectingAndThen/F2ThenComposing.java +++ b/src/main/java/nitin/streams/collectors/c7collectingAndThen/F2ThenComposing.java @@ -1,49 +1,56 @@ package nitin.streams.collectors.c7collectingAndThen; +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.groupingBy; + import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; -import static java.util.stream.Collectors.collectingAndThen; -import static java.util.stream.Collectors.groupingBy; - public class F2ThenComposing { public static void main(String[] args) { - //groupingBy, mapping, filtering -> taking first argument (function or predicate) and second argument as Collector + // groupingBy, mapping, filtering -> taking first argument (function or predicate) and + // second argument as Collector // It means, first apply the function or Predicate and then Collect - //collectingAndThen -> Collector as first argument adn then Function as second argument + // collectingAndThen -> Collector as first argument adn then Function as second argument List employees = SampleData.getSimpleEmployees(); - //Find the names of the employees and the corrosponding count + // Find the names of the employees and the corrosponding count findNameCount(employees); /*employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(Collectors.groupingBy(emp -> emp.getName(), emp.);*/ + .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) + .collect(Collectors.groupingBy(emp -> emp.getName(), emp.);*/ } private static void findNameCount(List employeeSimples) { Map byName = employeeSimples.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(groupingBy( - EmployeeSimple::getName, //First Argument of Grouping By - collectingAndThen(//Collector as Second Argument of Grouping By - Collectors.counting(),//Collector as First argument of CAT (collectingNThen) - Long::intValue // finisher function as second Argument - )//CollectingAndThen returns a Collector, so it can be further continued - //Function.identity() can be used if there is no mapper/transformer/convertor/enricher needed - ) - ); - - System.out.println(byName);//{Wayne=2, Don=1, John=3, Jane=1, Dow=1} - + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .collect( + groupingBy( + EmployeeSimple::getName, // First Argument of Grouping By + collectingAndThen( // Collector as Second Argument of + // Grouping By + Collectors + .counting(), // Collector as First argument + // of CAT (collectingNThen) + Long::intValue // finisher function as second + // Argument + ) // CollectingAndThen returns a Collector, so it + // can be further continued + // Function.identity() can be used if there is no + // mapper/transformer/convertor/enricher needed + )); + + System.out.println(byName); // {Wayne=2, Don=1, John=3, Jane=1, Dow=1} } } diff --git a/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M1maxMin.java b/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M1maxMin.java index 035759cc..960a00dc 100644 --- a/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M1maxMin.java +++ b/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M1maxMin.java @@ -2,7 +2,6 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.Comparator; import java.util.List; import java.util.Objects; @@ -14,74 +13,96 @@ public static void main(String[] args) { List employees = SampleData.getSimpleEmployees(); - //Find employee with Max Age using Streams + // Find employee with Max Age using Streams minMaxIntro(employees); - //Find maxBy minBy via Collectors + // Find maxBy minBy via Collectors minByMaxByIntro(employees); minAndMax(employees); minByAndMaxBy(employees); - } private static void minByMaxByIntro(List employees) { - EmployeeSimple collect = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(Collectors.maxBy( - Comparator.comparing(EmployeeSimple::getAge))) - .orElse(new EmployeeSimple()); + EmployeeSimple collect = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .collect(Collectors.maxBy(Comparator.comparing(EmployeeSimple::getAge))) + .orElse(new EmployeeSimple()); System.out.println(collect.getAge()); - int minAge;//TODO: find way to utilize optional - Integer minSalary = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(Collectors.collectingAndThen( - Collectors.maxBy(Comparator.comparing(EmployeeSimple::getAge)), - emp -> emp.map(EmployeeSimple::getAge).orElseThrow() - ) - ); + int minAge; // TODO: find way to utilize optional + Integer minSalary = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .collect( + Collectors.collectingAndThen( + Collectors.maxBy( + Comparator.comparing(EmployeeSimple::getAge)), + emp -> emp.map(EmployeeSimple::getAge).orElseThrow())); } private static void minMaxIntro(List employees) { - int maxAge = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .mapToInt(EmployeeSimple::getAge) - .max().orElse(-1); + int maxAge = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .mapToInt(EmployeeSimple::getAge) + .max() + .orElse(-1); System.out.println(maxAge); - int minAge = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .map(EmployeeSimple::getAge) - .min(Comparator.comparing(Integer::intValue))//Obvious comparing - .orElse(-1); + int minAge = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .map(EmployeeSimple::getAge) + .min(Comparator.comparing(Integer::intValue)) // Obvious comparing + .orElse(-1); System.out.println(minAge); } private static void minAndMax(List employees) { // Max and Min return Optional Integer - OptionalInt max = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - .mapToInt(EmployeeSimple::getAge) - .max(); + OptionalInt max = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + .mapToInt(EmployeeSimple::getAge) + .max(); System.out.println(max.getAsInt()); } private static void minByAndMaxBy(List employees) { // MaxBy and MinBy return Optional of the Object - EmployeeSimple maxBy = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - .collect(Collectors.maxBy( - Comparator.comparing( - EmployeeSimple::getAge))).orElse(new EmployeeSimple()); - System.out.println(maxBy);//EmployeeSimple(name=Jane, age=35, salary=76546.0, level=B, experience=5) - - EmployeeSimple minBy = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getName()).filter(emp -> null != emp.getAge()) - .collect(Collectors.minBy(Comparator.comparing(EmployeeSimple::getAge))).orElse(new EmployeeSimple()); - System.out.println(minBy);//EmployeeSimple(name=John, age=20, salary=65000.0, level=C, experience=5) + EmployeeSimple maxBy = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + .collect(Collectors.maxBy(Comparator.comparing(EmployeeSimple::getAge))) + .orElse(new EmployeeSimple()); + System.out.println( + maxBy); // EmployeeSimple(name=Jane, age=35, salary=76546.0, level=B, experience=5) + + EmployeeSimple minBy = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getName()) + .filter(emp -> null != emp.getAge()) + .collect(Collectors.minBy(Comparator.comparing(EmployeeSimple::getAge))) + .orElse(new EmployeeSimple()); + System.out.println( + minBy); // EmployeeSimple(name=John, age=20, salary=65000.0, level=C, experience=5) } } diff --git a/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M2CollectingMaxMin.java b/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M2CollectingMaxMin.java index 0a19e2db..2b1a49c8 100644 --- a/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M2CollectingMaxMin.java +++ b/src/main/java/nitin/streams/collectors/c8minMaxAvgCount/M2CollectingMaxMin.java @@ -2,7 +2,6 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.Comparator; import java.util.List; import java.util.Objects; @@ -12,18 +11,34 @@ public class M2CollectingMaxMin { public static void main(String[] args) { List employees = SampleData.getSimpleEmployees(); - //find the name of the employee with max Salary - String maxSalEmp = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .collect(Collectors.collectingAndThen( - Collectors.maxBy(Comparator.comparing(EmployeeSimple::getSalary)),//Collector as the first argument//First argument to find the max - emp -> emp.map(EmployeeSimple::getName)//Mapping Function as the second argument - .orElse("No Name")//maxBy returns an optional so use orElse for - ) - ); + // find the name of the employee with max Salary + String maxSalEmp = + employees.stream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .collect( + Collectors.collectingAndThen( + Collectors.maxBy( + Comparator.comparing( + EmployeeSimple + ::getSalary)), // Collector as the + // first + // argument//First + // argument to find + // the max + emp -> + emp.map(EmployeeSimple::getName) // Mapping + // Function as + // the second + // argument + .orElse("No Name") // maxBy returns an + // optional so use orElse + // for + )); employees.stream().forEach(System.out::println); System.out.println(maxSalEmp); - //TODO: Find the map of names with max Salary + // TODO: Find the map of names with max Salary } } diff --git a/src/main/java/nitin/streams/collectors/c9reducing/R1reduceIntro.java b/src/main/java/nitin/streams/collectors/c9reducing/R1reduceIntro.java index 090e7dae..01670fde 100644 --- a/src/main/java/nitin/streams/collectors/c9reducing/R1reduceIntro.java +++ b/src/main/java/nitin/streams/collectors/c9reducing/R1reduceIntro.java @@ -2,7 +2,6 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.List; import java.util.Objects; @@ -10,34 +9,38 @@ public class R1reduceIntro { public static void main(String[] args) { List employees = SampleData.getSimpleEmployees(); - //Find total sum of salaries of each employee + // Find total sum of salaries of each employee sumWithReduce(employees); sumWithOutReduce(employees); } - private static void sumWithOutReduce(List employees) { Double totalSalary = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) .mapToDouble(EmployeeSimple::getSalary) - .average().orElseThrow(); + .average() + .orElseThrow(); System.out.println(totalSalary); } - //Reduce takes the form of - reduce, collect, sum + // Reduce takes the form of - reduce, collect, sum private static void sumWithReduce(List employees) { Double totalSalary = employees.stream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) .map(EmployeeSimple::getSalary) - //.reduce(0, (total, age) -> total + age)); + // .reduce(0, (total, age) -> total + age)); .reduce(0.0, Double::sum); - //.orElse(-1D); + // .orElse(-1D); - //Reduce with identity returbs a , reduce without identity returns a Optional + // Reduce with identity returbs a , reduce without identity returns a Optional System.out.println(totalSalary); } diff --git a/src/main/java/nitin/streams/collectors/model/AdditionalLab.java b/src/main/java/nitin/streams/collectors/model/AdditionalLab.java index 53bfcd86..5c0549ad 100644 --- a/src/main/java/nitin/streams/collectors/model/AdditionalLab.java +++ b/src/main/java/nitin/streams/collectors/model/AdditionalLab.java @@ -5,6 +5,4 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class AdditionalLab extends LabBase { - -} +public class AdditionalLab extends LabBase {} diff --git a/src/main/java/nitin/streams/collectors/model/AdditionalLabsDto.java b/src/main/java/nitin/streams/collectors/model/AdditionalLabsDto.java index dd9a7695..c9ed48ac 100644 --- a/src/main/java/nitin/streams/collectors/model/AdditionalLabsDto.java +++ b/src/main/java/nitin/streams/collectors/model/AdditionalLabsDto.java @@ -3,13 +3,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data diff --git a/src/main/java/nitin/streams/collectors/model/CrossTable.java b/src/main/java/nitin/streams/collectors/model/CrossTable.java index bbe3350a..25918a1e 100644 --- a/src/main/java/nitin/streams/collectors/model/CrossTable.java +++ b/src/main/java/nitin/streams/collectors/model/CrossTable.java @@ -2,13 +2,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data @@ -19,5 +18,4 @@ public class CrossTable { private List
header; private List labDetails; - } diff --git a/src/main/java/nitin/streams/collectors/model/Header.java b/src/main/java/nitin/streams/collectors/model/Header.java index aa112710..a2dce3ef 100644 --- a/src/main/java/nitin/streams/collectors/model/Header.java +++ b/src/main/java/nitin/streams/collectors/model/Header.java @@ -18,5 +18,4 @@ public class Header { @JsonProperty("value") private String value; - } diff --git a/src/main/java/nitin/streams/collectors/model/Lab.java b/src/main/java/nitin/streams/collectors/model/Lab.java index 79f11e38..2c96358b 100644 --- a/src/main/java/nitin/streams/collectors/model/Lab.java +++ b/src/main/java/nitin/streams/collectors/model/Lab.java @@ -3,13 +3,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data @@ -20,7 +19,7 @@ public class Lab { @JsonProperty("month") private String month; - @JsonProperty("labsData")//Can have maximum of 3 labs each column - private List labsData;//Can have maximum of 3 labs each column + @JsonProperty("labsData") // Can have maximum of 3 labs each column + private List labsData; // Can have maximum of 3 labs each column } diff --git a/src/main/java/nitin/streams/collectors/model/LabBase.java b/src/main/java/nitin/streams/collectors/model/LabBase.java index 4b87d2c6..7af55799 100644 --- a/src/main/java/nitin/streams/collectors/model/LabBase.java +++ b/src/main/java/nitin/streams/collectors/model/LabBase.java @@ -5,13 +5,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import java.time.LocalDateTime; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.time.LocalDateTime; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data @@ -22,10 +21,13 @@ public class LabBase { @JsonProperty("categoryName") public String categoryName; + @JsonProperty("testCodeId") public String testCodeId; + @JsonProperty("name") public String name; + @JsonProperty("uom") public String uom; @@ -35,6 +37,7 @@ public class LabBase { @JsonProperty("value") public String value; + @JsonProperty("sortOrder") public int sortOrder; } diff --git a/src/main/java/nitin/streams/collectors/model/LabDetail.java b/src/main/java/nitin/streams/collectors/model/LabDetail.java index c92efd83..af37596e 100644 --- a/src/main/java/nitin/streams/collectors/model/LabDetail.java +++ b/src/main/java/nitin/streams/collectors/model/LabDetail.java @@ -3,13 +3,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data @@ -20,10 +19,12 @@ public class LabDetail { @JsonProperty("name") private String name; + @JsonProperty("uom") private String uom; + private int sortOrder; - @JsonProperty("labs") - private List labs;//Keeps 13 months of similar labs + @JsonProperty("labs") + private List labs; // Keeps 13 months of similar labs } diff --git a/src/main/java/nitin/streams/collectors/model/PdAdequacyLab.java b/src/main/java/nitin/streams/collectors/model/PdAdequacyLab.java index 18f60c79..eade6c8d 100644 --- a/src/main/java/nitin/streams/collectors/model/PdAdequacyLab.java +++ b/src/main/java/nitin/streams/collectors/model/PdAdequacyLab.java @@ -5,6 +5,4 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class PdAdequacyLab extends LabBase { - -} +public class PdAdequacyLab extends LabBase {} diff --git a/src/main/java/nitin/streams/collectors/model/PdAdequacyLabsDto.java b/src/main/java/nitin/streams/collectors/model/PdAdequacyLabsDto.java index 2050cf3f..27cdf1a5 100644 --- a/src/main/java/nitin/streams/collectors/model/PdAdequacyLabsDto.java +++ b/src/main/java/nitin/streams/collectors/model/PdAdequacyLabsDto.java @@ -3,13 +3,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data diff --git a/src/main/java/nitin/streams/collectors/model/TestBaseData.java b/src/main/java/nitin/streams/collectors/model/TestBaseData.java index 172a4903..53b9f426 100644 --- a/src/main/java/nitin/streams/collectors/model/TestBaseData.java +++ b/src/main/java/nitin/streams/collectors/model/TestBaseData.java @@ -10,15 +10,19 @@ public class TestBaseData { @JsonProperty("groupName") public String groupName; + @JsonProperty("code") public String code; + @JsonProperty("name") public String name; + @JsonProperty("dateTime") public String dateTime; + @JsonProperty("value") public String value; + @JsonProperty("categoryName") private String careCategoryName; - -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/example/CareCategory.java b/src/main/java/nitin/streams/collectors/whyItsWorking/example/CareCategory.java index 46939c51..8ea8ab85 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/example/CareCategory.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/example/CareCategory.java @@ -1,12 +1,11 @@ package nitin.streams.collectors.whyItsWorking.example; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @Data @Builder @AllArgsConstructor diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/example/CurrentMonth.java b/src/main/java/nitin/streams/collectors/whyItsWorking/example/CurrentMonth.java index 48b77659..20cd0f3f 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/example/CurrentMonth.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/example/CurrentMonth.java @@ -5,10 +5,9 @@ @RequiredArgsConstructor @Data - public class CurrentMonth { public String result0130; public String outside0130; public String date0130; public String outOfRangeInd0130; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/example/Example.java b/src/main/java/nitin/streams/collectors/whyItsWorking/example/Example.java index 445da02c..c2158b89 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/example/Example.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/example/Example.java @@ -7,4 +7,4 @@ @Data public class Example { public Report report; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/example/Labs.java b/src/main/java/nitin/streams/collectors/whyItsWorking/example/Labs.java index 6d4f3eb2..f35ffef8 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/example/Labs.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/example/Labs.java @@ -1,13 +1,11 @@ package nitin.streams.collectors.whyItsWorking.example; +import java.util.List; import lombok.Data; import lombok.RequiredArgsConstructor; -import java.util.List; - @RequiredArgsConstructor @Data - public class Labs { public String careCategoryName; public String currentMonthName; diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/example/Report.java b/src/main/java/nitin/streams/collectors/whyItsWorking/example/Report.java index e7e368ed..2454d0a7 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/example/Report.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/example/Report.java @@ -1,14 +1,12 @@ package nitin.streams.collectors.whyItsWorking.example; +import java.util.List; import lombok.Data; import lombok.RequiredArgsConstructor; -import java.util.List; - @RequiredArgsConstructor @Data - public class Report { public Boolean labsData; public List labs; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/example/SecondPreviousMonth.java b/src/main/java/nitin/streams/collectors/whyItsWorking/example/SecondPreviousMonth.java index 73dba155..d4bcbc5a 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/example/SecondPreviousMonth.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/example/SecondPreviousMonth.java @@ -5,10 +5,9 @@ @RequiredArgsConstructor @Data - public class SecondPreviousMonth { public String result6190; public String outside6190; public String date6190; public String outOfRangeInd6190; -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/collectors/whyItsWorking/test/Test.java b/src/main/java/nitin/streams/collectors/whyItsWorking/test/Test.java index fb2e88d8..0b67a8ec 100644 --- a/src/main/java/nitin/streams/collectors/whyItsWorking/test/Test.java +++ b/src/main/java/nitin/streams/collectors/whyItsWorking/test/Test.java @@ -1,11 +1,6 @@ package nitin.streams.collectors.whyItsWorking.test; import com.fasterxml.jackson.databind.ObjectMapper; -import nitin.streams.collectors.whyItsWorking.example.CareCategory; -import nitin.streams.collectors.whyItsWorking.example.Example; -import nitin.streams.collectors.whyItsWorking.example.Labs; -import org.apache.commons.io.FileUtils; - import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -14,16 +9,22 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import nitin.streams.collectors.whyItsWorking.example.CareCategory; +import nitin.streams.collectors.whyItsWorking.example.Example; +import nitin.streams.collectors.whyItsWorking.example.Labs; +import org.apache.commons.io.FileUtils; public class Test { - static final List ANEMIA_LABS = Arrays.asList("HEMOGLOBIN (g/dL)", - "IRON SATURATION (%)", - "FERRITIN (ng/mL)", - "IRON (ug/dL)", - "MCV (fL)", - "RETIC COUNT (%)", - "ABSOLUTE RETIC COUNT (x 10'6 cells/uL)", - "WBC (x 10'3 cells/uL)"); + static final List ANEMIA_LABS = + Arrays.asList( + "HEMOGLOBIN (g/dL)", + "IRON SATURATION (%)", + "FERRITIN (ng/mL)", + "IRON (ug/dL)", + "MCV (fL)", + "RETIC COUNT (%)", + "ABSOLUTE RETIC COUNT (x 10'6 cells/uL)", + "WBC (x 10'3 cells/uL)"); public static void main(String[] args) { Example example = getData(); @@ -33,35 +34,39 @@ public static void main(String[] args) { anemiaLabsMap.put(lab, false); } - List labsAnemiaAndOther = example.getReport().getLabs(); - List anemiaLabs = labsAnemiaAndOther - .stream() - .filter(allLabs -> allLabs.getCareCategoryName().equalsIgnoreCase("Anemia")) - .toList(); - - List anemiaCareCategory = anemiaLabs.get(0).getCareCategory();//Add the empty labs in this - - if (anemiaCareCategory.size() != ANEMIA_LABS.size()) {//8 Anemia labs hardcoded if all 8 are present, send as is, else fill with empty + List anemiaLabs = + labsAnemiaAndOther.stream() + .filter(allLabs -> allLabs.getCareCategoryName().equalsIgnoreCase("Anemia")) + .toList(); + + List anemiaCareCategory = + anemiaLabs.get(0).getCareCategory(); // Add the empty labs in this + + if (anemiaCareCategory.size() + != ANEMIA_LABS + .size()) { // 8 Anemia labs hardcoded if all 8 are present, send as is, else + // fill with empty for (CareCategory singleCareCategory : anemiaCareCategory) { - //Fill the Anemia Labs map to find the delta + // Fill the Anemia Labs map to find the delta anemiaLabsMap.put(singleCareCategory.getLabTestName(), Boolean.TRUE); } } - //Put care category for false value of key labs + // Put care category for false value of key labs // Iterate through the map entries for (Map.Entry entry : anemiaLabsMap.entrySet()) { String labTest = entry.getKey(); Boolean isAnemic = entry.getValue(); // Check if the value is false if (!isAnemic) { - CareCategory careCategoryDTO = CareCategory.builder() - .labTestName(labTest) - .currentMonth(List.of()) - .previousMonth(List.of()) - .secondPreviousMonth(List.of()) - .build(); + CareCategory careCategoryDTO = + CareCategory.builder() + .labTestName(labTest) + .currentMonth(List.of()) + .previousMonth(List.of()) + .secondPreviousMonth(List.of()) + .build(); anemiaCareCategory.add(careCategoryDTO); } } diff --git a/src/main/java/nitin/streams/fileStreams/FileStream.java b/src/main/java/nitin/streams/fileStreams/FileStream.java index eda51eeb..40af33a9 100644 --- a/src/main/java/nitin/streams/fileStreams/FileStream.java +++ b/src/main/java/nitin/streams/fileStreams/FileStream.java @@ -2,33 +2,31 @@ import com.entity.Cancer; import com.utilities.CsvReadUtility; - import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -/** - * Created by nichaurasia on Tuesday, January/28/2020 at 3:55 PM - */ - +/** Created by nichaurasia on Tuesday, January/28/2020 at 3:55 PM */ public class FileStream { public static void main(String[] args) throws URISyntaxException, IOException { List list = CsvReadUtility.getCancerData(); - Map> map = list.stream() - .collect(Collectors.groupingBy(Cancer::getYear)); + Map> map = + list.stream().collect(Collectors.groupingBy(Cancer::getYear)); for (Map.Entry> itr : map.entrySet()) { - System.out.println("Key: " + itr.getKey() + "== Value: " + itr.getValue().stream().count()); + System.out.println( + "Key: " + itr.getKey() + "== Value: " + itr.getValue().stream().count()); } - Map> map2 = list.stream() - .collect(Collectors.groupingBy(Cancer::getState)); + Map> map2 = + list.stream().collect(Collectors.groupingBy(Cancer::getState)); for (Map.Entry> itr : map2.entrySet()) { - System.out.println("Key: " + itr.getKey() + "== Value: " + itr.getValue().stream().count()); + System.out.println( + "Key: " + itr.getKey() + "== Value: " + itr.getValue().stream().count()); } } } diff --git a/src/main/java/nitin/streams/higherOrderFunctions/Example1.java b/src/main/java/nitin/streams/higherOrderFunctions/Example1.java index 982dadd4..0b0c0606 100644 --- a/src/main/java/nitin/streams/higherOrderFunctions/Example1.java +++ b/src/main/java/nitin/streams/higherOrderFunctions/Example1.java @@ -5,11 +5,10 @@ import java.util.function.Function; import java.util.function.Predicate; -/** - * Created by nitin on Tuesday, February/18/2020 at 9:44 PM - */ +/** Created by nitin on Tuesday, February/18/2020 at 9:44 PM */ public class Example1 { - public static final List namesList = Arrays.asList("Adrian", "Briana", "Chetan", "Neil", "Nitin", "Mukesh"); + public static final List namesList = + Arrays.asList("Adrian", "Briana", "Chetan", "Neil", "Nitin", "Mukesh"); public static void main(String[] args) { final Function> startsWithLetterFunction = @@ -22,12 +21,8 @@ public static void main(String[] args) { letter -> name -> name.startsWith(letter); System.out.println("Block 3"); - System.out.println(namesList.stream() - .filter(startsWithLetterFunction.apply("N")) - .count()); + System.out.println(namesList.stream().filter(startsWithLetterFunction.apply("N")).count()); - System.out.println(namesList.stream() - .filter(startsWithLetterFunction.apply("B")) - .count()); + System.out.println(namesList.stream().filter(startsWithLetterFunction.apply("B")).count()); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/parallel/MathUtils.java b/src/main/java/nitin/streams/parallel/MathUtils.java index b72a4a83..cdc5b92e 100755 --- a/src/main/java/nitin/streams/parallel/MathUtils.java +++ b/src/main/java/nitin/streams/parallel/MathUtils.java @@ -4,23 +4,14 @@ public class MathUtils { public static double fancySum1(double[] nums) { - return DoubleStream.of(nums) - .map(d -> Math.sqrt(2 * d)) - .sum(); + return DoubleStream.of(nums).map(d -> Math.sqrt(2 * d)).sum(); } public static double fancySum2(double[] nums) { - return DoubleStream.of(nums) - .parallel() - .map(d -> Math.sqrt(2 * d)) - .sum(); + return DoubleStream.of(nums).parallel().map(d -> Math.sqrt(2 * d)).sum(); } - - /** - * Make an n-length array of random numbers. - */ - + /** Make an n-length array of random numbers. */ public static double[] randomNums(int length) { double[] nums = new double[length]; for (int i = 0; i < length; i++) { diff --git a/src/main/java/nitin/streams/parallel/ParallelTests.java b/src/main/java/nitin/streams/parallel/ParallelTests.java index 6fd61ea2..7cb8b8f3 100755 --- a/src/main/java/nitin/streams/parallel/ParallelTests.java +++ b/src/main/java/nitin/streams/parallel/ParallelTests.java @@ -4,7 +4,7 @@ public class ParallelTests { public static void main(String[] args) { - //compareOutput(); + // compareOutput(); compareTiming(); } diff --git a/src/main/java/nitin/streams/parallelStreams/FJPCustomization.java b/src/main/java/nitin/streams/parallelStreams/FJPCustomization.java index e0e1ff5a..da4e5561 100644 --- a/src/main/java/nitin/streams/parallelStreams/FJPCustomization.java +++ b/src/main/java/nitin/streams/parallelStreams/FJPCustomization.java @@ -1,7 +1,6 @@ package nitin.streams.parallelStreams; import com.utilities.MultiThreadUtility; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.ForkJoinPool; @@ -19,16 +18,19 @@ public static void main(String[] args) { list.parallelStream() .filter(num -> num == num) .map(num -> incrementWith1SecDelay(num)) - //.forEach(num -> {}) + // .forEach(num -> {}) ; - customizingForkJoinPool(integerParallelStream);//Sending the stream + customizingForkJoinPool(integerParallelStream); // Sending the stream } private static void customizingForkJoinPool(Stream integerStream) { - ForkJoinPool forkJoinPool = new ForkJoinPool(100);//parallelism = 100 - forkJoinPool.submit(() -> integerStream.forEach(e -> { - }));//Running the reduction operation in another method withg another thread + ForkJoinPool forkJoinPool = new ForkJoinPool(100); // parallelism = 100 + forkJoinPool.submit( + () -> + integerStream.forEach( + e -> {})); // Running the reduction operation in another method + // withg another thread forkJoinPool.shutdown(); diff --git a/src/main/java/nitin/streams/parallelStreams/FaultyParallel_ProdCode_SharedMutability.java b/src/main/java/nitin/streams/parallelStreams/FaultyParallel_ProdCode_SharedMutability.java index 77723b81..858daef9 100644 --- a/src/main/java/nitin/streams/parallelStreams/FaultyParallel_ProdCode_SharedMutability.java +++ b/src/main/java/nitin/streams/parallelStreams/FaultyParallel_ProdCode_SharedMutability.java @@ -4,7 +4,6 @@ import com.google.common.collect.Lists; import com.utilities.CsvReadUtility; import com.utilities.MultiThreadUtility; - import java.util.ArrayList; import java.util.List; @@ -23,25 +22,32 @@ private static void updates() { System.out.println("total partitions " + partition.size()); try { partition.parallelStream() - .forEach(cancerPartitionList -> { - List objectList = new ArrayList<>(); - - //This was the impurity due to which the DB updates were not happening properly - cancerPartitionList.parallelStream().forEach(singleHhdOrder -> { //no fork join here - //cancerPartitionList.forEach(singleHhdOrder -> { - singleHhdOrder.setRace(null);//Changing int to double - singleHhdOrder.setCancer_sites("test"); - objectList.add(singleHhdOrder); - }); - - if (null != objectList) { - System.out.println("updating # of records " + objectList.size()); - //Simulating DB Write - MultiThreadUtility.delay(1000); - } - }); + .forEach( + cancerPartitionList -> { + List objectList = new ArrayList<>(); + + // This was the impurity due to which the DB updates were not + // happening properly + cancerPartitionList.parallelStream() + .forEach( + singleHhdOrder -> { // no fork join here + // cancerPartitionList.forEach(singleHhdOrder -> + // { + singleHhdOrder.setRace( + null); // Changing int to double + singleHhdOrder.setCancer_sites("test"); + objectList.add(singleHhdOrder); + }); + + if (null != objectList) { + System.out.println( + "updating # of records " + objectList.size()); + // Simulating DB Write + MultiThreadUtility.delay(1000); + } + }); } catch (Exception e) { System.out.println(e.getMessage()); } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/streams/parallelStreams/P1Intro.java b/src/main/java/nitin/streams/parallelStreams/P1Intro.java index bfd2cd96..33d1a7bf 100644 --- a/src/main/java/nitin/streams/parallelStreams/P1Intro.java +++ b/src/main/java/nitin/streams/parallelStreams/P1Intro.java @@ -3,7 +3,6 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; import com.utilities.MultiThreadUtility; - import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -13,20 +12,20 @@ public class P1Intro { public static void main(String[] args) { List list = List.of(0, 1, 2, 3, 4, 5, 6, 7, 9, 8); - //sequential(list); - //streamDotParallel(list.stream()); - //sequentialPitFalls(list); - //parallelStreamWithoutOrder(list); - //parallelStreamWithOrder(list); + // sequential(list); + // streamDotParallel(list.stream()); + // sequentialPitFalls(list); + // parallelStreamWithoutOrder(list); + // parallelStreamWithOrder(list); - //reducePitfalls(list); + // reducePitfalls(list); - //batchProcessing(); + // batchProcessing(); - //customFjp(); + // customFjp(); for (int i = 0; i < 10; i++) { - //findFirstParallel(); + // findFirstParallel(); } for (int i = 0; i < 10; i++) { @@ -37,29 +36,35 @@ public static void main(String[] args) { private static void findFirstParallel() { List employees = SampleData.getSimpleEmployees(); - //Find the name of the first employee greater than 40 years of age - - System.out.print(employees.parallelStream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .filter(emp -> emp.getAge() > 25) - .map(emp -> emp.getName()) - .findFirst()//Ordered and thus yields same result in both parallel and sequential - .orElse("No Emp Found")); - + // Find the name of the first employee greater than 40 years of age + + System.out.print( + employees.parallelStream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .filter(emp -> emp.getAge() > 25) + .map(emp -> emp.getName()) + .findFirst() // Ordered and thus yields same result in both parallel and + // sequential + .orElse("No Emp Found")); } private static void findAnyParallel() { List employees = SampleData.getSimpleEmployees(); - //Find the name of the any employee greater than 25 years of age - - System.out.println(employees.parallelStream() - .filter(Objects::nonNull).filter(emp -> null != emp.getAge()).filter(emp -> null != emp.getName()) - .filter(emp -> emp.getAge() > 25) - .map(emp -> emp.getName()) - .findAny()//behaves erratically with Parallel stream. Runs fine with sequential execution - .orElse("No Emp Found")); - + // Find the name of the any employee greater than 25 years of age + + System.out.println( + employees.parallelStream() + .filter(Objects::nonNull) + .filter(emp -> null != emp.getAge()) + .filter(emp -> null != emp.getName()) + .filter(emp -> emp.getAge() > 25) + .map(emp -> emp.getName()) + .findAny() // behaves erratically with Parallel stream. Runs fine with + // sequential execution + .orElse("No Emp Found")); } private static void batchProcessing() { @@ -71,22 +76,23 @@ private static void batchProcessing() { list.parallelStream() .filter(num -> num == num) .map(num -> incrementWith1SecDelay(num)) - .forEach(e -> { - }); + .forEach(e -> {}); } private static void reducePitfalls(List list) { - Integer result = list - .parallelStream()//Using Parallel Stream - .reduce(30, //First Parameter is not INITIAL value, it's an identity - (total, e) -> add(total, e)); + Integer result = + list.parallelStream() // Using Parallel Stream + .reduce( + 30, // First Parameter is not INITIAL value, it's an identity + (total, e) -> add(total, e)); System.out.println("Final Result : " + result); } private static Integer add(Integer a, Integer b) { int result = a + b; - System.out.println("a = " + a + " b = " + b + " r = " + result + " " + Thread.currentThread()); + System.out.println( + "a = " + a + " b = " + b + " r = " + result + " " + Thread.currentThread()); return result; } @@ -94,39 +100,44 @@ private static void sequentialPitFalls(List list) { System.out.println("\nstreamDotParallel"); list.parallelStream() .map(num -> incrementWith1SecDelay(num)) - .sequential()//This takes precedence due to its proximity with forEach (Reduce operation) + .sequential() // This takes precedence due to its proximity with forEach (Reduce + // operation) .forEach(num -> System.out.print(num + " ")); } private static void streamDotParallel(Stream listStream) { System.out.println("\nstreamDotParallel"); - listStream.parallel()//if Stream is already provided,or outside our control + listStream + .parallel() // if Stream is already provided,or outside our control .map(num -> incrementWith1SecDelay(num)) .forEachOrdered(num -> System.out.print(num + " ")); } private static void parallelStreamWithOrder(List list) { System.out.println("\nparallel Stream With Order"); - list.parallelStream()//Simple conversion to parallel stream - .map(num -> { - MultiThreadUtility.delay(1000); - num = num + 1; - System.out.println("map: " + num + "--" + Thread.currentThread()); - return num; - }) - .forEachOrdered(num -> System.out.println("feo: " + num + "--" + Thread.currentThread())); + list.parallelStream() // Simple conversion to parallel stream + .map( + num -> { + MultiThreadUtility.delay(1000); + num = num + 1; + System.out.println("map: " + num + "--" + Thread.currentThread()); + return num; + }) + .forEachOrdered( + num -> System.out.println("feo: " + num + "--" + Thread.currentThread())); } private static void parallelStreamWithoutOrder(List list) { System.out.println("\nparallel Stream Without Order"); - list.parallelStream()//Simple conversion to parallel stream - .map(num -> { - MultiThreadUtility.delay(1000); - num = num + 1; - System.out.println("map: " + num + "--" + Thread.currentThread()); - return num; - }) + list.parallelStream() // Simple conversion to parallel stream + .map( + num -> { + MultiThreadUtility.delay(1000); + num = num + 1; + System.out.println("map: " + num + "--" + Thread.currentThread()); + return num; + }) .forEach(num -> System.out.println("fe : " + num + "--" + Thread.currentThread())); } @@ -134,7 +145,7 @@ private static void sequential(List list) { System.out.println("Sequential"); list.stream() - .sequential()//Without this method also it will work similar + .sequential() // Without this method also it will work similar .map(num -> incrementWith1SecDelay(num)) .forEach(num -> System.out.print(num + " ")); } @@ -144,5 +155,4 @@ private static int incrementWith1SecDelay(int number) { MultiThreadUtility.delay(1000); return number + 1; } - } diff --git a/src/main/java/nitin/streams/parallelStreams/ParallelProcessing.java b/src/main/java/nitin/streams/parallelStreams/ParallelProcessing.java index 83ca5e16..3ce29f77 100644 --- a/src/main/java/nitin/streams/parallelStreams/ParallelProcessing.java +++ b/src/main/java/nitin/streams/parallelStreams/ParallelProcessing.java @@ -1,34 +1,32 @@ package nitin.streams.parallelStreams; -import com.utilities.InternetUtilities; +import static com.utilities.PerformanceUtility.*; +import com.utilities.InternetUtilities; import java.util.List; import java.util.stream.Collectors; -import static com.utilities.PerformanceUtility.*; - public class ParallelProcessing { public static void main(String[] args) { - List wordList = InternetUtilities.bringWordListFromNet(); - System.out.println("********************************** Sequential **********************************"); + System.out.println( + "********************************** Sequential **********************************"); startTimer(); - List capitalListSequential = wordList - .stream() - .map(str -> str.toUpperCase()) - .collect(Collectors.toList()); + List capitalListSequential = + wordList.stream().map(str -> str.toUpperCase()).collect(Collectors.toList()); stopTimer(); System.out.println(capitalListSequential.size()); resetTimer(); - System.out.println("********************************** Parallel **********************************"); + System.out.println( + "********************************** Parallel **********************************"); startTimer(); - List capitalListParallel = wordList - .parallelStream() - .map(str -> str.toUpperCase()) - .collect(Collectors.toList()); + List capitalListParallel = + wordList.parallelStream() + .map(str -> str.toUpperCase()) + .collect(Collectors.toList()); stopTimer(); System.out.println(capitalListParallel.size()); } diff --git a/src/main/java/nitin/streams/sortingNcomparators/AdvancedComparator.java b/src/main/java/nitin/streams/sortingNcomparators/AdvancedComparator.java index 70f15b33..a52ffda6 100644 --- a/src/main/java/nitin/streams/sortingNcomparators/AdvancedComparator.java +++ b/src/main/java/nitin/streams/sortingNcomparators/AdvancedComparator.java @@ -3,7 +3,6 @@ import com.entity.reports.EventComments; import com.entity.reports.IntraStatsLine; import com.entity.reports.SampleIntraStatLine; - import java.util.List; public class AdvancedComparator { @@ -11,36 +10,40 @@ public static void main(String[] args) { IntraStatsLine intraStatsLine = SampleIntraStatLine.getIntraStatsLine(); System.out.println("*************** BEFORE SORT ***************"); - intraStatsLine.getEventComments() - .forEach(System.out::println); + intraStatsLine.getEventComments().forEach(System.out::println); System.out.println("*************** AFTER SORT ***************"); List eventCommentsList = intraStatsLine.getEventComments(); -// eventCommentsList.sort((object1, object2) -> { -// return object2.getSomeStats().get(0).getTimeDtDisplay().compareTo(object1.getSomeStats().get(0).getTimeDtDisplay()); -// }); - - eventCommentsList.sort((object1, object2) -> { - return object1.getSomeClass().getIndex().compareTo(object2.getSomeClass().getIndex()); - }); - - eventCommentsList.sort((EventComments o1, EventComments o2) -> { - if (o1.getSomeClass().getIndex() > o2.getSomeClass().getIndex()) - return -1; - else if (o1.getSomeClass().getIndex() < o2.getSomeClass().getIndex()) - return 1; - else { - return (o2.getSomeStats().get(0).getTimeDtDisplay().compareTo(o1.getSomeStats().get(0).getTimeDtDisplay())); - } - }); - + // eventCommentsList.sort((object1, object2) -> { + // return + // object2.getSomeStats().get(0).getTimeDtDisplay().compareTo(object1.getSomeStats().get(0).getTimeDtDisplay()); + // }); + + eventCommentsList.sort( + (object1, object2) -> { + return object1.getSomeClass() + .getIndex() + .compareTo(object2.getSomeClass().getIndex()); + }); + + eventCommentsList.sort( + (EventComments o1, EventComments o2) -> { + if (o1.getSomeClass().getIndex() > o2.getSomeClass().getIndex()) return -1; + else if (o1.getSomeClass().getIndex() < o2.getSomeClass().getIndex()) return 1; + else { + return (o2.getSomeStats() + .get(0) + .getTimeDtDisplay() + .compareTo(o1.getSomeStats().get(0).getTimeDtDisplay())); + } + }); intraStatsLine.setEventComments(eventCommentsList); - intraStatsLine.getEventComments() -// .forEach(x -> System.out.println(x.getSomeStats().get(0).toString())); + intraStatsLine + .getEventComments() + // .forEach(x -> + // System.out.println(x.getSomeStats().get(0).toString())); .forEach(x -> System.out.println(x)); - - } } diff --git a/src/main/java/nitin/streams/sortingNcomparators/EmployeeServices.java b/src/main/java/nitin/streams/sortingNcomparators/EmployeeServices.java index 69758d26..e9572081 100644 --- a/src/main/java/nitin/streams/sortingNcomparators/EmployeeServices.java +++ b/src/main/java/nitin/streams/sortingNcomparators/EmployeeServices.java @@ -2,15 +2,12 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.List; import java.util.OptionalDouble; /** - * @author Created by nichaurasia - * Created on Monday, September/28/2020 at 12:07 AM + * @author Created by nichaurasia Created on Monday, September/28/2020 at 12:07 AM */ - public class EmployeeServices { public static void main(String[] args) { final List employees = SampleData.getSimpleEmployees(); @@ -28,11 +25,9 @@ public static void main(String[] args) { System.out.println("Average of salaries"); avgSalariesSum(employees); - //TODO : + // TODO : System.out.println("Average of salaries"); avgSalariesreduce(employees); - - } private static void incrementSalary(List list) { @@ -43,30 +38,25 @@ private static void incrementSalary(List list) { } private static void anyMatchageGT30Employee(List list) { - System.out.println(list.stream() - //.distinctBy() - .anyMatch(Lambdas.ageGT30Predicate)); + System.out.println( + list.stream() + // .distinctBy() + .anyMatch(Lambdas.ageGT30Predicate)); } private static void avgSalariesSum(List list) { - OptionalDouble avgSalOptional = list.stream() - .mapToDouble(EmployeeSimple::getSalary) - .average(); + OptionalDouble avgSalOptional = + list.stream().mapToDouble(EmployeeSimple::getSalary).average(); - avgSalOptional - .ifPresent(System.out::println); + avgSalOptional.ifPresent(System.out::println); } private static void avgSalariesreduce(List list) { - System.out.println(list.stream() - .map((e) -> e.getSalary()) - .reduce(0.0, (x, y) -> (x + y))); + System.out.println(list.stream().map((e) -> e.getSalary()).reduce(0.0, (x, y) -> (x + y))); } private static void howManyGT30Employee(List list) { - System.out.println(list.stream() - .filter(Lambdas.ageGT30Predicate) - .count()); + System.out.println(list.stream().filter(Lambdas.ageGT30Predicate).count()); } } diff --git a/src/main/java/nitin/streams/sortingNcomparators/EmployeeSorting.java b/src/main/java/nitin/streams/sortingNcomparators/EmployeeSorting.java index 4d1e5cbf..f0743c8f 100644 --- a/src/main/java/nitin/streams/sortingNcomparators/EmployeeSorting.java +++ b/src/main/java/nitin/streams/sortingNcomparators/EmployeeSorting.java @@ -2,20 +2,16 @@ import com.entity.EmployeeSimple; import com.entity.SampleData; - import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -/** - * Created by nichaurasia on Thursday, February/13/2020 at 11:50 AM - */ - +/** Created by nichaurasia on Thursday, February/13/2020 at 11:50 AM */ public class EmployeeSorting { public static void main(String[] args) { final List list = SampleData.getSimpleEmployees(); - /* System.out.println("Sorting with ageDifference method"); + /* System.out.println("Sorting with ageDifference method"); //sortAgeByAgeDiffMethod(list); System.out.println(); @@ -47,70 +43,62 @@ public static void main(String[] args) { } private static void distinctAgeEmployee(List list) { - list.stream() - .filter(x -> x.getAge() > 0) - .distinct() - .forEach(System.out::println); + list.stream().filter(x -> x.getAge() > 0).distinct().forEach(System.out::println); } private static void minSalaryEmployee(List list) { - System.out.println(list.stream() - .min(Lambdas.salaryLambda) - .get()); + System.out.println(list.stream().min(Lambdas.salaryLambda).get()); } private static void maxSalaryEmployee(List list) { - System.out.println(list.stream() - .max(Lambdas.salaryLambda) - .get()); + System.out.println(list.stream().max(Lambdas.salaryLambda).get()); } private static void reverseSortUsingAgeNSalaryLambda(List employees) { - - employees - .stream() - .sorted(Lambdas.revAgeLambda - .thenComparing(Lambdas.salaryLambda)) + employees.stream() + .sorted(Lambdas.revAgeLambda.thenComparing(Lambdas.salaryLambda)) .forEach(System.out::println); } private static void reverseSortUsingAgeLambda(List list) { - Comparator salaryComparator = (e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()); + Comparator salaryComparator = + (e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()); Comparator salaryComparatorMethodRef = EmployeeSimple::salaryDifference; - list.stream().sorted(EmployeeSimple::salaryDifference) - .forEach(System.out::println); + list.stream().sorted(EmployeeSimple::salaryDifference).forEach(System.out::println); } private static void maxAgeEmployee(List list) { - EmployeeSimple e = list.stream() - .max(Lambdas.ageLambda) - .get(); + EmployeeSimple e = list.stream().max(Lambdas.ageLambda).get(); System.out.println(e); } private static void sortUsingAgeLambda(List list) { - list.stream() - .sorted(Lambdas.ageLambda) - .forEach(System.out::println); + list.stream().sorted(Lambdas.ageLambda).forEach(System.out::println); } private static void sortAgeByAgeDiffMethod(List list) { - list.stream() - .sorted(Lambdas.ageLambda) - .forEach(System.out::println); + list.stream().sorted(Lambdas.ageLambda).forEach(System.out::println); } private static List test(List list) { - List empList = list.stream() - .sorted(Comparator.comparing(EmployeeSimple::getSalary, Comparator.nullsLast(Comparator.naturalOrder()))) - .map(employee -> { - String sb = employee.getName() + " has a salary of " + - employee.getSalary() + " at the age of " + - employee.getAge(); - return sb; - }) - .collect(Collectors.toList()); + List empList = + list.stream() + .sorted( + Comparator.comparing( + EmployeeSimple::getSalary, + Comparator.nullsLast(Comparator.naturalOrder()))) + .map( + employee -> { + String sb = + employee.getName() + + " has a salary of " + + employee.getSalary() + + " at the age of " + + employee.getAge(); + return sb; + }) + .collect(Collectors.toList()); return empList; } diff --git a/src/main/java/nitin/streams/sortingNcomparators/Lambdas.java b/src/main/java/nitin/streams/sortingNcomparators/Lambdas.java index bae5b20b..cdff80a8 100644 --- a/src/main/java/nitin/streams/sortingNcomparators/Lambdas.java +++ b/src/main/java/nitin/streams/sortingNcomparators/Lambdas.java @@ -1,33 +1,32 @@ package nitin.streams.sortingNcomparators; import com.entity.EmployeeSimple; - import java.util.Comparator; import java.util.function.Predicate; /** - * @author Created by nichaurasia - * Created on Sunday, September/27/2020 at 4:59 PM + * @author Created by nichaurasia Created on Sunday, September/27/2020 at 4:59 PM */ - public class Lambdas { - public static final Comparator ageLambda = (e1, e2) -> e1.getAge() - e2.getAge(); + public static final Comparator ageLambda = + (e1, e2) -> e1.getAge() - e2.getAge(); - public static final Comparator ageLambdaOld = new Comparator() { - @Override - public int compare(EmployeeSimple o1, EmployeeSimple o2) { - return o1.getAge() - o2.getAge(); - } - }; - public static final Comparator revAgeLambda = (e1, e2) -> e2.getAge() - e1.getAge(); + public static final Comparator ageLambdaOld = + new Comparator() { + @Override + public int compare(EmployeeSimple o1, EmployeeSimple o2) { + return o1.getAge() - o2.getAge(); + } + }; + public static final Comparator revAgeLambda = + (e1, e2) -> e2.getAge() - e1.getAge(); - public static final Comparator salaryLambda = (e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()); + public static final Comparator salaryLambda = + (e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()); - //Predicates + // Predicates public static final Predicate ageGT30Predicate = e -> e.getAge() > 30; - - private Lambdas() { - } + private Lambdas() {} } diff --git a/src/main/java/nitin/streams/specializedstreams/DoubleStreamTest.java b/src/main/java/nitin/streams/specializedstreams/DoubleStreamTest.java index b1431b14..68627757 100755 --- a/src/main/java/nitin/streams/specializedstreams/DoubleStreamTest.java +++ b/src/main/java/nitin/streams/specializedstreams/DoubleStreamTest.java @@ -9,14 +9,9 @@ public class DoubleStreamTest { public static void main(String[] args) { - List nums1 = - Stream.of(1.2, 2.3, 3.4) - .collect(Collectors.toList()); + List nums1 = Stream.of(1.2, 2.3, 3.4).collect(Collectors.toList()); System.out.println(nums1); - List nums2 = - DoubleStream.of(1.2, 2.3, 3.4) - .boxed() - .collect(Collectors.toList()); + List nums2 = DoubleStream.of(1.2, 2.3, 3.4).boxed().collect(Collectors.toList()); System.out.println(nums2); } } diff --git a/src/main/java/nitin/streams/specializedstreams/P1DoubleStream.java b/src/main/java/nitin/streams/specializedstreams/P1DoubleStream.java index 7863532d..df155cef 100644 --- a/src/main/java/nitin/streams/specializedstreams/P1DoubleStream.java +++ b/src/main/java/nitin/streams/specializedstreams/P1DoubleStream.java @@ -2,9 +2,7 @@ import java.util.stream.DoubleStream; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class P1DoubleStream { public static void main(String[] args) { DoubleStream oneValue = DoubleStream.of(3.14, 4.34, 6.50); diff --git a/src/main/java/nitin/streams/specializedstreams/UseArgs.java b/src/main/java/nitin/streams/specializedstreams/UseArgs.java index 5632c031..378ba524 100755 --- a/src/main/java/nitin/streams/specializedstreams/UseArgs.java +++ b/src/main/java/nitin/streams/specializedstreams/UseArgs.java @@ -1,8 +1,7 @@ package nitin.streams.specializedstreams; public class UseArgs { - private UseArgs() { - } + private UseArgs() {} public static int firstNumber(int... nums) { return (nums[0]); diff --git a/src/main/java/nitin/streams/timing/Op.java b/src/main/java/nitin/streams/timing/Op.java index b48955f1..beaf5e6a 100755 --- a/src/main/java/nitin/streams/timing/Op.java +++ b/src/main/java/nitin/streams/timing/Op.java @@ -1,6 +1,5 @@ package nitin.streams.timing; - @FunctionalInterface public interface Op { static void timeOp(Op operation) { diff --git a/src/main/java/nitin/streams/timing/TimingTests.java b/src/main/java/nitin/streams/timing/TimingTests.java index 1584ee73..944cc56c 100755 --- a/src/main/java/nitin/streams/timing/TimingTests.java +++ b/src/main/java/nitin/streams/timing/TimingTests.java @@ -18,10 +18,7 @@ public static void main(String[] args) { } } - /** - * Make an n-length array of random numbers. - */ - + /** Make an n-length array of random numbers. */ public static double[] randomNums(int length) { double[] nums = new double[length]; for (int i = 0; i < length; i++) { @@ -37,9 +34,7 @@ public static void sortArray(int length) { public static void wasteTime(int repeats) { for (int i = 0; i < repeats; i++) { - double d = Math.sqrt(Math.random()) + - Math.sin(Math.random()) + - Math.exp(Math.random()); + double d = Math.sqrt(Math.random()) + Math.sin(Math.random()) + Math.exp(Math.random()); doSomethingWith(d); } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S0forEach.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S0forEach.java index a087666d..1e723de4 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S0forEach.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S0forEach.java @@ -3,10 +3,7 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by Nitin Chaurasia on 1/31/18 at 12:53 AM. - * Applies the s2lambda to each element - */ +/** Created by Nitin Chaurasia on 1/31/18 at 12:53 AM. Applies the s2lambda to each element */ public class S0forEach { public static void main(String[] args) { @@ -18,14 +15,11 @@ public static void main(String[] args) { list.add("Nagarjuna"); System.out.println(list); - //For each method applies the s2lambda to each element of the collection - //Prints each element - list.stream() - .forEach(str -> System.out.println(str)); - - //Lambda can be replaced by method reference - list.stream() - .forEach(System.out::print); + // For each method applies the s2lambda to each element of the collection + // Prints each element + list.stream().forEach(str -> System.out.println(str)); + // Lambda can be replaced by method reference + list.stream().forEach(System.out::print); } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S10distinct.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S10distinct.java index 96899bfd..308bfb55 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S10distinct.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S10distinct.java @@ -4,16 +4,15 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class S10distinct { public static void main(String[] args) { List intList = Arrays.asList(1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9); - List collect = intList.stream() - .distinct()//What to do without bothering how to do - .collect(Collectors.toList()); + List collect = + intList.stream() + .distinct() // What to do without bothering how to do + .collect(Collectors.toList()); System.out.println(collect); } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S11limitSkip.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S11limitSkip.java index 24648612..7172fb85 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S11limitSkip.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S11limitSkip.java @@ -4,26 +4,18 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class S11limitSkip { public static void main(String[] args) { List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); - List integerList = intList.stream() - .limit(5) - .map(num -> num * num) - .collect(Collectors.toList()); + List integerList = + intList.stream().limit(5).map(num -> num * num).collect(Collectors.toList()); System.out.println(integerList); - List integerList2 = intList.stream() - .skip(5) - .map(num -> num * num) - .collect(Collectors.toList()); + List integerList2 = + intList.stream().skip(5).map(num -> num * num).collect(Collectors.toList()); System.out.println(integerList2); - - } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S12peek.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S12peek.java index 69680e3c..89b263de 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S12peek.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S12peek.java @@ -4,20 +4,19 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class S12peek { public static void main(String[] args) { - //Used extensively for debugging + // Used extensively for debugging List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); - List integerList = intList.stream() - .map(num -> num * num) - .peek(x -> System.out.print(x + "\t")) - .limit(5) - .peek(x -> System.out.print(x + "\t")) - .collect(Collectors.toList()); + List integerList = + intList.stream() + .map(num -> num * num) + .peek(x -> System.out.print(x + "\t")) + .limit(5) + .peek(x -> System.out.print(x + "\t")) + .collect(Collectors.toList()); // Lazy Evaluation in Streams. Streams will be calculated when a terminal operator // is encountered. diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S1filter.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S1filter.java index c059e010..df0b4b4f 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S1filter.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S1filter.java @@ -4,18 +4,17 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class S1filter { public static void main(String[] args) { List list = Arrays.asList(1, 4, 6, 8, 9, 7, 5, 3, 2); // Filter takes in a Predicate functional interface - List collect = list.stream() - .filter(num -> num % 2 != 0) - .filter(num -> num % 2 == 0) - .collect(Collectors.toList()); + List collect = + list.stream() + .filter(num -> num % 2 != 0) + .filter(num -> num % 2 == 0) + .collect(Collectors.toList()); System.out.println(collect); } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S2count.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S2count.java index 4cee26fe..e5d3a94d 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S2count.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S2count.java @@ -8,9 +8,8 @@ /** * Created by Nitin Chaurasia on 1/31/18 at 12:33 AM. - *

- * Count method Present in Stream Class - * public long count(); returns a long value + * + *

Count method Present in Stream Class public long count(); returns a long value */ public class S2count { public static void main(String[] args) { @@ -25,11 +24,11 @@ public static void main(String[] args) { Predicate strLong = str -> str.length() >= 9; // Count the number of strings greater than 9 characters - long count = list - .stream() - //.filter(strLong) - .filter(str -> str.length() >= 9) - .count(); + long count = + list.stream() + // .filter(strLong) + .filter(str -> str.length() >= 9) + .count(); System.out.println("# strings > 9 chars :: " + count); @@ -37,16 +36,16 @@ public static void main(String[] args) { System.out.println(stringStream.count()); List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); - //Creating a Stream from list + // Creating a Stream from list Stream fromList = intList.stream(); - System.out.println(fromList - .filter(num -> num % 2 == 0) - .count()//The stream ends with the reduction operation - ); - - - //Exception : java.lang.IllegalStateException: stream has already been operated upon or closed - //System.out.println(fromList.count()); + System.out.println( + fromList.filter(num -> num % 2 == 0) + .count() // The stream ends with the reduction operation + ); + + // Exception : java.lang.IllegalStateException: stream has already been operated upon or + // closed + // System.out.println(fromList.count()); System.out.println(intList.stream().count()); } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S3Iterate.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S3Iterate.java index e53148ac..daa6828d 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S3Iterate.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S3Iterate.java @@ -2,23 +2,16 @@ import java.util.stream.Stream; -/** - * Created by nitin on Sunday, January/26/2020 at 10:29 PM - */ +/** Created by nitin on Sunday, January/26/2020 at 10:29 PM */ public class S3Iterate { public static void main(String[] args) { // It takes an initial value and a function that provides next value, // Runs infinitely, Use limit() to put an upper cap - Stream - .iterate(1, x -> x + 3) - .limit(5) - .forEach(System.out::print); + Stream.iterate(1, x -> x + 3).limit(5).forEach(System.out::print); System.out.println(); // Iterate with 3 Arguments - Stream - .iterate(2, x -> x < 10, x -> x + 2) - .forEach(x -> System.out.print(x + "\t")); + Stream.iterate(2, x -> x < 10, x -> x + 2).forEach(x -> System.out.print(x + "\t")); } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S3sorted.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S3sorted.java index 6e9cf2d7..d932d117 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S3sorted.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S3sorted.java @@ -5,9 +5,7 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by Nitin Chaurasia on 1/31/18 at 12:40 AM. - */ +/** Created by Nitin Chaurasia on 1/31/18 at 12:40 AM. */ public class S3sorted { public static void main(String[] args) { List list = new ArrayList<>(); @@ -20,32 +18,28 @@ public static void main(String[] args) { System.out.println("SORTED LIST"); // Sort elements of the Stream, using DNSO - List l = list.stream() - .sorted() - .collect(Collectors.toList()); + List l = list.stream().sorted().collect(Collectors.toList()); System.out.println(l); // Reverse Sorted, customised sorted order - List l2 = list.stream() - .sorted((str1, str2) -> str2.compareTo(str1)) - .collect(Collectors.toList()); -// List l3 = list.stream().sorted(new Comparator() { -// @Override -// public int compare(String o1, String o2) { -// o2.compareTo(o1); -// } -// }).collect(Collectors.toList()); + List l2 = + list.stream() + .sorted((str1, str2) -> str2.compareTo(str1)) + .collect(Collectors.toList()); + // List l3 = list.stream().sorted(new Comparator() { + // @Override + // public int compare(String o1, String o2) { + // o2.compareTo(o1); + // } + // }).collect(Collectors.toList()); System.out.println(l2); - System.out.println("COMPARATOR USE CASE"); list.stream() - .sorted(Comparator - .comparing(String::length) - //.thenComparing((str1, str2) -> str2.compareTo(str1)) - .thenComparing(Comparator.reverseOrder()) - ) + .sorted( + Comparator.comparing(String::length) + // .thenComparing((str1, str2) -> str2.compareTo(str1)) + .thenComparing(Comparator.reverseOrder())) .forEach(System.out::print); - } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S4OfNullable.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S4OfNullable.java index 11d6cabb..9ecce51e 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S4OfNullable.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S4OfNullable.java @@ -1,32 +1,31 @@ package nitin.streams.variousMethodsOfStreams; - import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; -/** - * Created by nitin on Sunday, January/26/2020 at 10:42 PM - */ +/** Created by nitin on Sunday, January/26/2020 at 10:42 PM */ public class S4OfNullable { public static void main(String[] args) { List list = Arrays.asList("Andy", "B", null, "D", null, "F"); // First way of avoiding NullPointerException - List collect = list.stream() - .filter(object -> object != null) - .filter(Objects::nonNull) - .map(str -> str.toLowerCase()) - .collect(Collectors.toList()); + List collect = + list.stream() + .filter(object -> object != null) + .filter(Objects::nonNull) + .map(str -> str.toLowerCase()) + .collect(Collectors.toList()); System.out.println(collect); // Use of FlatMap with ofNullable to avoid null pointer exception - List strings = list.stream() - .flatMap(object -> Stream.ofNullable(object)) - .map(str -> str.toLowerCase()) - .collect(Collectors.toList()); + List strings = + list.stream() + .flatMap(object -> Stream.ofNullable(object)) + .map(str -> str.toLowerCase()) + .collect(Collectors.toList()); System.out.println(strings); } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S4minNmax.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S4minNmax.java index 7e62705a..69f7bea4 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S4minNmax.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S4minNmax.java @@ -5,10 +5,7 @@ import java.util.List; import java.util.Optional; -/** - * Created by Nitin Chaurasia on 1/31/18 at 12:49 AM. - * Returns an optional - */ +/** Created by Nitin Chaurasia on 1/31/18 at 12:49 AM. Returns an optional */ public class S4minNmax { public static void main(String[] args) { List list = new ArrayList<>(); @@ -19,7 +16,7 @@ public static void main(String[] args) { list.add("Nagarjuna"); System.out.println(list); - //min accepts comparator to sort + // min accepts comparator to sort String min = list.stream().min((str1, str2) -> str1.compareTo(str2)).get(); System.out.println(min); @@ -27,29 +24,30 @@ public static void main(String[] args) { System.out.println(max); List stringList = List.of("Cat", "Dog", "Elephant", "Frog", "Goat"); - //min needs a comparator + // min needs a comparator Optional min2 = stringList.stream().min((s1, s2) -> s1.compareToIgnoreCase(s2)); min2.ifPresent(System.out::println); - //get also return the same thing - //System.out.println(min2.get()); + // get also return the same thing + // System.out.println(min2.get()); System.out.println("MIN 3"); - Optional min3 = stringList.stream().min((s1, s2) -> { - if (s1.length() > s2.length()) - return 1; - else if (s1.length() < s2.length()) - return -1; - else - return s2.compareTo(s1); - }); + Optional min3 = + stringList.stream() + .min( + (s1, s2) -> { + if (s1.length() > s2.length()) return 1; + else if (s1.length() < s2.length()) return -1; + else return s2.compareTo(s1); + }); min3.ifPresent(System.out::println); System.out.println("Min 4"); - Optional min4 = stringList.stream() - .min(Comparator.comparing(String::length)//TODO : Learn to write in Lambda - .thenComparing(Comparator.reverseOrder()) - ); + Optional min4 = + stringList.stream() + .min( + Comparator.comparing( + String::length) // TODO : Learn to write in Lambda + .thenComparing(Comparator.reverseOrder())); min4.ifPresent(System.out::println); - } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S6toArray.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S6toArray.java index 6cd15b73..e71493c5 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S6toArray.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S6toArray.java @@ -3,9 +3,7 @@ import java.util.ArrayList; import java.util.List; -/** - * Created by Nitin Chaurasia on 1/31/18 at 12:59 AM. - */ +/** Created by Nitin Chaurasia on 1/31/18 at 12:59 AM. */ public class S6toArray { public static void main(String[] args) { List list = new ArrayList<>(); @@ -21,7 +19,6 @@ public static void main(String[] args) { Object[] objectArray = list.toArray(); String[] listArray = list.toArray(new String[0]); - for (String a : arr) { System.out.println(a); } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S7streamOf.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S7streamOf.java index 15ad78c5..e3de5f5a 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S7streamOf.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S7streamOf.java @@ -7,8 +7,8 @@ /** * Created by Nitin Chaurasia on 1/31/18 at 11:48 AM. - *

- * Applying Stream for group of values & for arrays + * + *

Applying Stream for group of values & for arrays */ public class S7streamOf { public static void main(String[] args) { diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S8map.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S8map.java index ace85a00..5bea22b2 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S8map.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S8map.java @@ -3,22 +3,17 @@ import java.util.List; import java.util.stream.Collectors; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class S8map { public static void main(String[] args) { List stringList = List.of("Nitin", "Nidhi", "Niti"); // Lambda Expression - stringList.stream() - .map(a -> a.toLowerCase()) - .forEach(b -> System.out.println(b)); + stringList.stream().map(a -> a.toLowerCase()).forEach(b -> System.out.println(b)); - //The same is written in method reference - List strings = stringList.stream() - .map(String::toLowerCase) - .collect(Collectors.toList()); + // The same is written in method reference + List strings = + stringList.stream().map(String::toLowerCase).collect(Collectors.toList()); System.out.println(strings); } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap.java index fd3939ad..1ae37c03 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap.java @@ -7,9 +7,9 @@ /** * Created by Nitin C on 3/3/2016. - *

- * The difference - map operation produces one output value for each input value, whereas the flatMap - * operation produces an arbitrary number (zero or more) values for each input value. + * + *

The difference - map operation produces one output value for each input value, whereas the + * flatMap operation produces an arbitrary number (zero or more) values for each input value. */ public class S9flatMap { public static void main(String[] args) { @@ -22,16 +22,23 @@ public static void main(String[] args) { System.out.println(list); // for each values, generate uppercase and find length - List l = list.stream() - .flatMap(x -> Stream.of(x, x.toUpperCase(), String.valueOf(x.length()), x.toLowerCase())) - .collect(Collectors.toList()); + List l = + list.stream() + .flatMap( + x -> + Stream.of( + x, + x.toUpperCase(), + String.valueOf(x.length()), + x.toLowerCase())) + .collect(Collectors.toList()); System.out.println(l); System.out.println(); l.stream() - //.map(str -> str.toLowerCase()) + // .map(str -> str.toLowerCase()) .flatMap(x -> Stream.of(x.toLowerCase(), x.toUpperCase(), x.length())) .forEach(x -> System.out.print(x + ", ")); } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap2.java b/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap2.java index a95802b8..9cc441dd 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap2.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/S9flatMap2.java @@ -7,9 +7,9 @@ /** * Created by Nitin C on 3/3/2016. - *

- * The difference - map operation produces one output value for each input value, whereas the flatMap - * operation produces an arbitrary number (zero or more) values for each input value. + * + *

The difference - map operation produces one output value for each input value, whereas the + * flatMap operation produces an arbitrary number (zero or more) values for each input value. */ public class S9flatMap2 { public static void main(String[] args) { @@ -19,13 +19,14 @@ public static void main(String[] args) { } // for each even value, do nothing, for odd, take random as well and square - List l = list.stream() - .flatMap(x -> { - if (x % 2 == 0) - return Stream.of(x * x * x); - else - return Stream.of(x, x * x); - }).collect(Collectors.toList()); + List l = + list.stream() + .flatMap( + x -> { + if (x % 2 == 0) return Stream.of(x * x * x); + else return Stream.of(x, x * x); + }) + .collect(Collectors.toList()); System.out.println(l); } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/StreamDoNotDo.java b/src/main/java/nitin/streams/variousMethodsOfStreams/StreamDoNotDo.java index b270e3ab..901726b8 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/StreamDoNotDo.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/StreamDoNotDo.java @@ -19,26 +19,27 @@ public static void main(String[] args) { } private static List transformation(List integerList) { - List integers = integerList.stream() - .filter(num -> num % 2 == 0) - .map(num -> num * 2) - .collect(Collectors.toList()); + List integers = + integerList.stream() + .filter(num -> num % 2 == 0) + .map(num -> num * 2) + .collect(Collectors.toList()); return integers; } private static List transformationOdd(List integerList) { List list = new ArrayList<>(); - //Works until now, but stopped all of a sudden + // Works until now, but stopped all of a sudden // Code behaves - erratically with parallel Stream integerList.parallelStream() .filter(num -> num % 2 != 0) .map(num -> num * 2) - .forEach(num -> list.add(num));//shared Mutability - //BAD IDEA with ParallelStream - due to shared mutability - this is impure + .forEach(num -> list.add(num)); // shared Mutability + // BAD IDEA with ParallelStream - due to shared mutability - this is impure return list; - //[14, 18, 2, 10, 6] - //[14, 2, 6, 18, 10] + // [14, 18, 2, 10, 6] + // [14, 2, 6, 18, 10] } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/T6reduce.java b/src/main/java/nitin/streams/variousMethodsOfStreams/T6reduce.java index 66e181fe..2ed0be67 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/T6reduce.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/T6reduce.java @@ -2,9 +2,7 @@ import java.util.List; -/** - * Created by Nitin C on 3/3/2016. - */ +/** Created by Nitin C on 3/3/2016. */ public class T6reduce { public static void main(String[] args) { m1(); @@ -14,8 +12,7 @@ public static void main(String[] args) { public static void m1() { List arr = List.of("n", "i", "t", "i", "n"); - String name = arr.stream(). - reduce("", String::concat); + String name = arr.stream().reduce("", String::concat); System.out.println(name); } @@ -23,8 +20,7 @@ public static void m1() { public static void m2() { List intStream = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - Integer reduced = intStream.stream() - .reduce(0, (a, b) -> a + b); + Integer reduced = intStream.stream().reduce(0, (a, b) -> a + b); System.out.println(reduced); } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/TakeWhileTest.java b/src/main/java/nitin/streams/variousMethodsOfStreams/TakeWhileTest.java index 1b6c4683..ce4cf060 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/TakeWhileTest.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/TakeWhileTest.java @@ -1,7 +1,5 @@ package nitin.streams.variousMethodsOfStreams; public class TakeWhileTest { - public static void main(String[] args) { - - } + public static void main(String[] args) {} } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S1takeWhileVSdropWhile.java b/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S1takeWhileVSdropWhile.java index 789cc8b6..c6f35697 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S1takeWhileVSdropWhile.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S1takeWhileVSdropWhile.java @@ -6,10 +6,10 @@ /** * Created by Nitin Chaurasia on 2/1/18 at 1:41 AM. - *

- * takeWhile() like filter() method will take elements from the Stream as long as predicate returns true. - * If predicate returns false, at that point onwards remaining elements won't be processed, - * i.e rest of the Stream is discarded. + * + *

takeWhile() like filter() method will take elements from the Stream as long as predicate + * returns true. If predicate returns false, at that point onwards remaining elements won't be + * processed, i.e rest of the Stream is discarded. */ public class S1takeWhileVSdropWhile { public static void main(String[] args) { @@ -19,30 +19,23 @@ public static void main(String[] args) { list.add(i); } - //list = Cargo.intCargo(6); + // list = Cargo.intCargo(6); System.out.println(list); - //filtering the even elements out - List l = list - .stream() - .filter(x -> x % 2 == 0) - .collect(Collectors.toList()); + // filtering the even elements out + List l = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); System.out.println(l); - //filtering the even elements out using takeWhile (Fails after fulfilling first condition) - List l2 = list - .stream() - //.filter(x -> x%3==0) - .takeWhile(x -> x % 3 != 0) - .collect(Collectors.toList()); + // filtering the even elements out using takeWhile (Fails after fulfilling first condition) + List l2 = + list.stream() + // .filter(x -> x%3==0) + .takeWhile(x -> x % 3 != 0) + .collect(Collectors.toList()); System.out.println(l2); // drop while is opposite to take while - List l3 = list - .stream() - .dropWhile(x -> x % 3 != 0) - .collect(Collectors.toList()); + List l3 = list.stream().dropWhile(x -> x % 3 != 0).collect(Collectors.toList()); System.out.println(l3); - } } diff --git a/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S2DropWhile.java b/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S2DropWhile.java index 27b239e9..6b8410be 100644 --- a/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S2DropWhile.java +++ b/src/main/java/nitin/streams/variousMethodsOfStreams/takeWhileVSdropWhile/S2DropWhile.java @@ -1,58 +1,81 @@ package nitin.streams.variousMethodsOfStreams.takeWhileVSdropWhile; -import org.apache.commons.lang3.StringUtils; - import java.util.*; import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; /** - * Created by nitin on Sunday, January/26/2020 at 8:21 PM - * TakeWhile runs until the first false/negative condition is met - * DropWhile runs from the first negative condition is met. + * Created by nitin on Sunday, January/26/2020 at 8:21 PM TakeWhile runs until the first + * false/negative condition is met DropWhile runs from the first negative condition is met. */ public class S2DropWhile { public static void main(String[] args) { - List list = Arrays.asList("one", null, "two", "three", "four", null, "circuit breaker", "five", - "six", "seven", "", "", null, null); - //list = Arrays.asList(null,null,null,null); - //list = Arrays.asList("","","",""); + List list = + Arrays.asList( + "one", + null, + "two", + "three", + "four", + null, + "circuit breaker", + "five", + "six", + "seven", + "", + "", + null, + null); + // list = Arrays.asList(null,null,null,null); + // list = Arrays.asList("","","",""); takeWhileUntilLen7Comes(list); - //DropWhile runs from the first negative condition is met. + // DropWhile runs from the first negative condition is met. dropStringsuntilLen7Comes(list); pickFirstNonNullSortedString(list); } private static void dropStringsuntilLen7Comes(List list) { - List dropWhileList = list - .stream() - //.filter(str -> null != str) - .filter(Objects::nonNull) - .dropWhile(str -> str.length() < 7) - .collect(Collectors.toList()); + List dropWhileList = + list.stream() + // .filter(str -> null != str) + .filter(Objects::nonNull) + .dropWhile(str -> str.length() < 7) + .collect(Collectors.toList()); System.out.println(dropWhileList); } private static void takeWhileUntilLen7Comes(List list) { - List takeWhileList = list - .stream() - //.filter(str -> null != str) - .filter(Objects::nonNull) - .takeWhile(str -> str.length() < 7)//take the strings until a string of lenght 7 comes - .collect(Collectors.toList()); + List takeWhileList = + list.stream() + // .filter(str -> null != str) + .filter(Objects::nonNull) + .takeWhile( + str -> + str.length() + < 7) // take the strings until a string of lenght 7 + // comes + .collect(Collectors.toList()); System.out.println(takeWhileList); } private static void pickFirstNonNullSortedString(List list) { - List singleElementList = Collections.singletonList(Optional.of(list - .stream() - .filter(singleStr -> null != singleStr)//Removing nulls - .sorted(Comparator.naturalOrder()) - .dropWhile(str -> str.isBlank())//Removing Empty Strings - //.peek(x-> System.out.println(x)) - .findFirst()).get().orElse(StringUtils.EMPTY)); + List singleElementList = + Collections.singletonList( + Optional.of( + list.stream() + .filter( + singleStr -> + null != singleStr) // Removing nulls + .sorted(Comparator.naturalOrder()) + .dropWhile(str -> str.isBlank()) // Removing + // Empty Strings + // .peek(x-> System.out.println(x)) + .findFirst()) + .get() + .orElse(StringUtils.EMPTY)); System.out.println(singleElementList); } diff --git a/src/main/java/nitin/strings/S1StringInterning.java b/src/main/java/nitin/strings/S1StringInterning.java index 35c2dd52..c2cf1811 100644 --- a/src/main/java/nitin/strings/S1StringInterning.java +++ b/src/main/java/nitin/strings/S1StringInterning.java @@ -1,9 +1,6 @@ package nitin.strings; - -/** - * Created by nitin.chaurasia on 2/16/2017. - */ +/** Created by nitin.chaurasia on 2/16/2017. */ public class S1StringInterning { public static void main(String[] args) { @@ -14,11 +11,11 @@ public static void main(String[] args) { testIntern(one, two); String test1 = "Nitin"; - String test2 = "Nitin";//// Forcing to create a new String + String test2 = "Nitin"; // // Forcing to create a new String testIntern(test1, test2); - String three = "Nitin";// Forcing to create a new String - //String three = "Nitin".intern();//intern used + String three = "Nitin"; // Forcing to create a new String + // String three = "Nitin".intern();//intern used String four = "Nitin"; testIntern(three, four); } diff --git a/src/main/java/nitin/strings/S1StringPool.java b/src/main/java/nitin/strings/S1StringPool.java index adde6305..19e13751 100644 --- a/src/main/java/nitin/strings/S1StringPool.java +++ b/src/main/java/nitin/strings/S1StringPool.java @@ -1,12 +1,10 @@ package nitin.strings; -/** - * Created by nitin on Thu, 12/29/16 at 2:46 AM. - */ +/** Created by nitin on Thu, 12/29/16 at 2:46 AM. */ public class S1StringPool { public static void main(String[] args) { String a = "In String Pool"; // JVM uses the String Pool - String b = "Don't use String Pool";// + String b = "Don't use String Pool"; // } } diff --git a/src/main/java/nitin/strings/S1StringPoolingConcept.java b/src/main/java/nitin/strings/S1StringPoolingConcept.java index 99d69367..ebe0db95 100644 --- a/src/main/java/nitin/strings/S1StringPoolingConcept.java +++ b/src/main/java/nitin/strings/S1StringPoolingConcept.java @@ -1,8 +1,6 @@ package nitin.strings; -/** - * Created by Nitin C on 11/26/2015. - */ +/** Created by Nitin C on 11/26/2015. */ public class S1StringPoolingConcept { public static void main(String[] args) { // Two ways of Creating a String (new and "~~~") @@ -13,7 +11,7 @@ public static void main(String[] args) { String s1 = ""; String s2 = ""; String s3 = ""; - /* + /* When we use double quotes to create a string, it first looks for the string with the same value in the String Pool. If found it just returns the reference @@ -32,8 +30,6 @@ public static void main(String[] args) { if (x == y) { System.out.println("x and y are referring to a same String"); } - /** In Sting .equals() method checks for string equality - * = compared the references - */ + /** In Sting .equals() method checks for string equality = compared the references */ } } diff --git a/src/main/java/nitin/strings/S2StringImmutable.java b/src/main/java/nitin/strings/S2StringImmutable.java index 99fa585d..a558179b 100644 --- a/src/main/java/nitin/strings/S2StringImmutable.java +++ b/src/main/java/nitin/strings/S2StringImmutable.java @@ -1,8 +1,6 @@ package nitin.strings; -/** - * Created by Nitin C on 11/26/2015. - */ +/** Created by Nitin C on 11/26/2015. */ public class S2StringImmutable { /* String are made to be immutable as a consequence from Memory Pool concept. diff --git a/src/main/java/nitin/strings/S2StringMethods.java b/src/main/java/nitin/strings/S2StringMethods.java index 2b35b977..a482b562 100644 --- a/src/main/java/nitin/strings/S2StringMethods.java +++ b/src/main/java/nitin/strings/S2StringMethods.java @@ -1,13 +1,11 @@ package nitin.strings; -/** - * Created by nitin on Thu, 12/29/16 at 2:49 AM. - */ +/** Created by nitin on Thu, 12/29/16 at 2:49 AM. */ public class S2StringMethods { public static void main(String[] args) { String x = "Malgudi Days by R.K Narayan Features malgudi"; - System.out.println(x.length());// length method + System.out.println(x.length()); // length method System.out.println(x.charAt(9)); // Index Of @@ -18,18 +16,17 @@ public static void main(String[] args) { // Sub string - //toLowerCase() , toUpperCase() + // toLowerCase() , toUpperCase() // equals() , equalsIgnoreCase() // startesWith, endsWith - //contains + // contains - //replace + // replace // trim - } } diff --git a/src/main/java/nitin/strings/S3StringBuilder.java b/src/main/java/nitin/strings/S3StringBuilder.java index 2c5d634a..30f7a896 100644 --- a/src/main/java/nitin/strings/S3StringBuilder.java +++ b/src/main/java/nitin/strings/S3StringBuilder.java @@ -2,10 +2,9 @@ /** * Created by nitin.chaurasia on 11/21/2016. - *

- * StringBuilder is NON-SYNCHRONIZED thus more efficient - * StringBuffer is SYNCHRONIZED (THREAD SAFE) means two threads - * can call the methods of the a5object simultaneously. Thus comparatively + * + *

StringBuilder is NON-SYNCHRONIZED thus more efficient StringBuffer is SYNCHRONIZED (THREAD + * SAFE) means two threads can call the methods of the a5object simultaneously. Thus comparatively * less efficient */ public class S3StringBuilder { @@ -14,7 +13,7 @@ public static void main(String[] args) { String a = "test1" + " next1"; String b = "test2" + " next2"; - c = c.concat(" next3");//Not working + c = c.concat(" next3"); // Not working String s = "Nitin" + " Kumar" + " Chaurasia"; @@ -22,6 +21,5 @@ public static void main(String[] args) { System.out.println(b); System.out.println(c); System.out.println(s); - } } diff --git a/src/main/java/nitin/strings/S4StringBuffer.java b/src/main/java/nitin/strings/S4StringBuffer.java index b61501f0..4169b10f 100644 --- a/src/main/java/nitin/strings/S4StringBuffer.java +++ b/src/main/java/nitin/strings/S4StringBuffer.java @@ -4,9 +4,7 @@ import java.util.Arrays; import java.util.List; -/** - * Created by nitin on Thu, 12/29/16 at 3:04 AM. - */ +/** Created by nitin on Thu, 12/29/16 at 3:04 AM. */ public class S4StringBuffer { public static void main(String[] args) { // Declaring a Rectangular Matrix @@ -18,7 +16,7 @@ public static void main(String[] args) { list.add(3, List.of(41)); list.add(4, Arrays.asList(51, 52, 53)); - //Printing the Matrix using FOR Loop + // Printing the Matrix using FOR Loop for (int i = 0; i < list.size(); i = i + 1) { for (int j = 0; j < list.get(i).size(); j = j + 1) { System.out.print(list.get(i).get(j) + "\t"); diff --git a/src/main/java/nitin/strings/S4StringBufferVsStringBuilder.java b/src/main/java/nitin/strings/S4StringBufferVsStringBuilder.java index 5868a19a..c250f4a6 100644 --- a/src/main/java/nitin/strings/S4StringBufferVsStringBuilder.java +++ b/src/main/java/nitin/strings/S4StringBufferVsStringBuilder.java @@ -1,8 +1,6 @@ package nitin.strings; -/** - * Created by Nitin C on 11/26/2015. - */ +/** Created by Nitin C on 11/26/2015. */ public class S4StringBufferVsStringBuilder { public static void main(String[] args) { StringBuilder sbuild = new StringBuilder(); // Empty String with initial capacity 16 @@ -14,6 +12,5 @@ StringBuffer is SYNCHRONIZED (THREAD SAFE) means two threads less efficient */ - } } diff --git a/src/main/java/nitin/strings/S5SplitString.java b/src/main/java/nitin/strings/S5SplitString.java index b45fb079..271f20a1 100644 --- a/src/main/java/nitin/strings/S5SplitString.java +++ b/src/main/java/nitin/strings/S5SplitString.java @@ -2,9 +2,7 @@ import java.util.Arrays; -/** - * Created by Nitin Chaurasia on 3/23/18 at 11:22 PM. - */ +/** Created by Nitin Chaurasia on 3/23/18 at 11:22 PM. */ public class S5SplitString { public static void main(String[] args) { String myString = "Nitin x Kirti x Nidhi x Niti"; diff --git a/src/main/java/nitin/strings/stringMethods/IsBlank.java b/src/main/java/nitin/strings/stringMethods/IsBlank.java index bc8963f0..374e5dba 100644 --- a/src/main/java/nitin/strings/stringMethods/IsBlank.java +++ b/src/main/java/nitin/strings/stringMethods/IsBlank.java @@ -1,16 +1,13 @@ package nitin.strings.stringMethods; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 5:52 PM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 5:52 PM */ - public class IsBlank { public static void main(String[] args) { - System.out.println(" ".isBlank()); //true - System.out.println("".isBlank()); //true - System.out.println("Test".isBlank()); //false - + System.out.println(" ".isBlank()); // true + System.out.println("".isBlank()); // true + System.out.println("Test".isBlank()); // false } } diff --git a/src/main/java/nitin/strings/stringMethods/Lines.java b/src/main/java/nitin/strings/stringMethods/Lines.java index f262a173..ddca98a9 100644 --- a/src/main/java/nitin/strings/stringMethods/Lines.java +++ b/src/main/java/nitin/strings/stringMethods/Lines.java @@ -3,18 +3,13 @@ import java.util.stream.Collectors; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 7:14 PM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 7:14 PM */ - public class Lines { public static void main(String[] args) throws Exception { String str = "line1\nline2\nline3\tline4\rline5"; - System.out.println( - str.lines() - .collect(Collectors.toList()) - ); + System.out.println(str.lines().collect(Collectors.toList())); } } diff --git a/src/main/java/nitin/strings/stringMethods/Repeat.java b/src/main/java/nitin/strings/stringMethods/Repeat.java index 5af98227..0884acce 100644 --- a/src/main/java/nitin/strings/stringMethods/Repeat.java +++ b/src/main/java/nitin/strings/stringMethods/Repeat.java @@ -1,10 +1,8 @@ package nitin.strings.stringMethods; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 7:29 PM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 7:29 PM */ - public class Repeat { public static void main(String[] args) { String str = "Nitin".repeat(2); diff --git a/src/main/java/nitin/strings/stringMethods/Strip.java b/src/main/java/nitin/strings/stringMethods/Strip.java index 216755cd..2e4d9891 100644 --- a/src/main/java/nitin/strings/stringMethods/Strip.java +++ b/src/main/java/nitin/strings/stringMethods/Strip.java @@ -1,21 +1,19 @@ package nitin.strings.stringMethods; /** - * @author Created by nichaurasia - * Create on Sunday, December/20/2020 at 7:19 PM + * @author Created by nichaurasia Create on Sunday, December/20/2020 at 7:19 PM */ - public class Strip { public static void main(String[] args) { - System.out.println(" nitin ".trim() + "#####");//spaces at both ends - System.out.println(" nitin".trim() + "#####");//leading space - System.out.println("nitin ".trim() + "#####");//trailing space + System.out.println(" nitin ".trim() + "#####"); // spaces at both ends + System.out.println(" nitin".trim() + "#####"); // leading space + System.out.println("nitin ".trim() + "#####"); // trailing space - //strip() is “Unicode-aware” + // strip() is Unicode-aware System.out.println("*************** STRIP ***************"); - System.out.println(" nitin ".strip() + "#####");//spaces at both ends - System.out.println(" nitin ".stripLeading() + "#####");//leading space - System.out.println(" nitin ".stripTrailing() + "#####");//trailing space + System.out.println(" nitin ".strip() + "#####"); // spaces at both ends + System.out.println(" nitin ".stripLeading() + "#####"); // leading space + System.out.println(" nitin ".stripTrailing() + "#####"); // trailing space } } diff --git a/src/main/java/nitin/strings/stringMethods/TextBlock.java b/src/main/java/nitin/strings/stringMethods/TextBlock.java index bf49bb21..ce83516e 100644 --- a/src/main/java/nitin/strings/stringMethods/TextBlock.java +++ b/src/main/java/nitin/strings/stringMethods/TextBlock.java @@ -2,7 +2,8 @@ public class TextBlock { public static void main(String[] args) { - String text = """ + String text = + """ word1 \ word2 \ word3 \ diff --git a/src/main/java/nitin/strings/stringMethods/Trim.java b/src/main/java/nitin/strings/stringMethods/Trim.java index e09a316d..63e39a5d 100644 --- a/src/main/java/nitin/strings/stringMethods/Trim.java +++ b/src/main/java/nitin/strings/stringMethods/Trim.java @@ -1,9 +1,6 @@ package nitin.strings.stringMethods; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 7:14 PM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 7:14 PM */ - -public class Trim { -} +public class Trim {} diff --git a/src/main/java/nitin/zKnowYourJava/E1.java b/src/main/java/nitin/zKnowYourJava/E1.java index 91d6badd..1e739d6f 100644 --- a/src/main/java/nitin/zKnowYourJava/E1.java +++ b/src/main/java/nitin/zKnowYourJava/E1.java @@ -7,4 +7,4 @@ public class E1 { public static void main(String[] args) { List numbers = new ArrayList<>(List.of(1, 23)); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zKnowYourJava/T10DefaultInSwitch.java b/src/main/java/nitin/zKnowYourJava/T10DefaultInSwitch.java index d8a61198..6c62ca49 100644 --- a/src/main/java/nitin/zKnowYourJava/T10DefaultInSwitch.java +++ b/src/main/java/nitin/zKnowYourJava/T10DefaultInSwitch.java @@ -1,6 +1,9 @@ package nitin.zKnowYourJava; -enum When {DAY, NIGHT}//, DAWN} +enum When { + DAY, + NIGHT +} // , DAWN} public class T10DefaultInSwitch { public static void main(String[] args) { diff --git a/src/main/java/nitin/zKnowYourJava/T11Records.java b/src/main/java/nitin/zKnowYourJava/T11Records.java index e81aa1f6..cc397b6f 100644 --- a/src/main/java/nitin/zKnowYourJava/T11Records.java +++ b/src/main/java/nitin/zKnowYourJava/T11Records.java @@ -3,23 +3,22 @@ public class T11Records { public static void main(String[] args) { System.out.println(new Year(23)); - } } record Year(int year) { - //Avoid Canonical constructors as much as possible. + // Avoid Canonical constructors as much as possible. // Use the compact constructor instead - //Compact constructor is a filter or a pre-processor before the constructor is called. + // Compact constructor is a filter or a pre-processor before the constructor is called. - //code --> Compact constructor --> constructor. + // code --> Compact constructor --> constructor. Year { if (year < 0) { throw new RuntimeException("Negative Year"); } if (year < 100) { - //this.year = 2000 + year; + // this.year = 2000 + year; year = 2000 + year; } } diff --git a/src/main/java/nitin/zKnowYourJava/T13Collectors.java b/src/main/java/nitin/zKnowYourJava/T13Collectors.java index 93cd1e64..a4783e77 100644 --- a/src/main/java/nitin/zKnowYourJava/T13Collectors.java +++ b/src/main/java/nitin/zKnowYourJava/T13Collectors.java @@ -14,24 +14,28 @@ public static void main(String[] args) { System.out.println(min + " " + max); - var result = numbers.stream().collect(Collectors.teeing( - Collectors.maxBy(Comparator.comparing(num -> num)), - Collectors.minBy(Comparator.comparing(num -> num)), - List::of) - ); + var result = + numbers.stream() + .collect( + Collectors.teeing( + Collectors.maxBy(Comparator.comparing(num -> num)), + Collectors.minBy(Comparator.comparing(num -> num)), + List::of)); System.out.println(result); - //Get into a record - var result2 = numbers.stream().collect(Collectors.teeing( - Collectors.maxBy(Comparator.comparing(num -> num)), - Collectors.minBy(Comparator.comparing(num -> num)), - (val1, val2) -> new MinMax(val1.orElse(0), val2.orElse(0))) - ); + // Get into a record + var result2 = + numbers.stream() + .collect( + Collectors.teeing( + Collectors.maxBy(Comparator.comparing(num -> num)), + Collectors.minBy(Comparator.comparing(num -> num)), + (val1, val2) -> + new MinMax(val1.orElse(0), val2.orElse(0)))); System.out.println(result2); } } -record MinMax(int min, int max) { -} +record MinMax(int min, int max) {} diff --git a/src/main/java/nitin/zKnowYourJava/T14Functional.java b/src/main/java/nitin/zKnowYourJava/T14Functional.java index 741efac8..3bec5e98 100644 --- a/src/main/java/nitin/zKnowYourJava/T14Functional.java +++ b/src/main/java/nitin/zKnowYourJava/T14Functional.java @@ -1,4 +1,3 @@ package nitin.zKnowYourJava; -public class T14Functional { -} +public class T14Functional {} diff --git a/src/main/java/nitin/zKnowYourJava/T15Switch.java b/src/main/java/nitin/zKnowYourJava/T15Switch.java index 8b811be9..9861e18b 100644 --- a/src/main/java/nitin/zKnowYourJava/T15Switch.java +++ b/src/main/java/nitin/zKnowYourJava/T15Switch.java @@ -5,16 +5,11 @@ public class T15Switch { public static void main(String[] args) { - Stream.of(90, 80, 70, 60) - .map(T15Switch::grade) - .forEach(System.out::println); + Stream.of(90, 80, 70, 60).map(T15Switch::grade).forEach(System.out::println); - Stream.of(90, 80, 70, 60) - .map(T15Switch::grade2) - .forEach(System.out::println); + Stream.of(90, 80, 70, 60).map(T15Switch::grade2).forEach(System.out::println); } - private static String grade(int score) { String grade = ""; @@ -34,13 +29,14 @@ private static String grade(int score) { } private static String grade2(int score) { - String grade = switch (Math.min(score / 10, 10)) { - case 9, 10 -> "A"; - case 8 -> "B"; - case 7 -> "C"; - case 6 -> "D"; - default -> "F"; - }; + String grade = + switch (Math.min(score / 10, 10)) { + case 9, 10 -> "A"; + case 8 -> "B"; + case 7 -> "C"; + case 6 -> "D"; + default -> "F"; + }; return grade; } diff --git a/src/main/java/nitin/zKnowYourJava/T1ListVsCollectionsRemove.java b/src/main/java/nitin/zKnowYourJava/T1ListVsCollectionsRemove.java index 9c350942..acf40667 100644 --- a/src/main/java/nitin/zKnowYourJava/T1ListVsCollectionsRemove.java +++ b/src/main/java/nitin/zKnowYourJava/T1ListVsCollectionsRemove.java @@ -6,15 +6,15 @@ public class T1ListVsCollectionsRemove { public static void main(String[] args) { - List list = new ArrayList<>(getIntegers());//Polymnorphism + List list = new ArrayList<>(getIntegers()); // Polymnorphism list.remove(1); System.out.println(list); - Collection list2 = new ArrayList<>(getIntegers());//Polymnorphism - list2.remove(1);//Remove the element/object + Collection list2 = new ArrayList<>(getIntegers()); // Polymnorphism + list2.remove(1); // Remove the element/object System.out.println(list2); - var list3 = new ArrayList<>(getIntegers());//Polymnorphism + var list3 = new ArrayList<>(getIntegers()); // Polymnorphism list3.remove(1); System.out.println(list3); } @@ -22,4 +22,4 @@ public static void main(String[] args) { private static List getIntegers() { return List.of(1, 2, 3); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zKnowYourJava/T2TypeInference.java b/src/main/java/nitin/zKnowYourJava/T2TypeInference.java index 3b77edd0..71be4393 100644 --- a/src/main/java/nitin/zKnowYourJava/T2TypeInference.java +++ b/src/main/java/nitin/zKnowYourJava/T2TypeInference.java @@ -7,24 +7,24 @@ public class T2TypeInference { public static void main(String[] args) { var test = "test"; - //test.foo(); + // test.foo(); removeIndexFromVar(); removeObjectFromCollection(); } private static void removeObjectFromCollection() { Collection numbers = new ArrayList(getIntegers()); - numbers.remove(1);//Removes the Object - System.out.println(numbers);//[2, 3] + numbers.remove(1); // Removes the Object + System.out.println(numbers); // [2, 3] } private static void removeIndexFromVar() { var numbers = new ArrayList(getIntegers()); - numbers.remove(1);//overloaded Remove method that takes Integer instead of Object - System.out.println(numbers);//[1, 3] + numbers.remove(1); // overloaded Remove method that takes Integer instead of Object + System.out.println(numbers); // [1, 3] } private static List getIntegers() { return List.of(1, 2, 3); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zKnowYourJava/T3ArraysAsList.java b/src/main/java/nitin/zKnowYourJava/T3ArraysAsList.java index 36aa46f1..169ad31f 100644 --- a/src/main/java/nitin/zKnowYourJava/T3ArraysAsList.java +++ b/src/main/java/nitin/zKnowYourJava/T3ArraysAsList.java @@ -5,16 +5,15 @@ public class T3ArraysAsList { public static void main(String[] args) { - //arraysAsList(); - List numbers = List.of(1, 2, 3,null);//Immutable, add(), set() unsupported - System.out.println(numbers.getClass());//class java.util.ImmutableCollections$ListN - + // arraysAsList(); + List numbers = List.of(1, 2, 3, null); // Immutable, add(), set() unsupported + System.out.println(numbers.getClass()); // class java.util.ImmutableCollections$ListN } private static void arraysAsList() { List numbers = Arrays.asList(1, 2, 3); - System.out.println(numbers.getClass());//class java.util.Arrays$ArrayList - //it is far from immutable. does not support add method + System.out.println(numbers.getClass()); // class java.util.Arrays$ArrayList + // it is far from immutable. does not support add method try { numbers.add(4); diff --git a/src/main/java/nitin/zKnowYourJava/T4SharedMutability.java b/src/main/java/nitin/zKnowYourJava/T4SharedMutability.java index e21f083c..e9d778d0 100644 --- a/src/main/java/nitin/zKnowYourJava/T4SharedMutability.java +++ b/src/main/java/nitin/zKnowYourJava/T4SharedMutability.java @@ -10,7 +10,7 @@ public class T4SharedMutability { public static void main(String[] args) { String url = "https://www.mit.edu/~ecprice/wordlist.100000"; - List words = getData(url);//Add more data + List words = getData(url); // Add more data sharedMutabilityParallelism(words); useCollectorOrToList(words); @@ -20,11 +20,9 @@ private static void useCollectorOrToList(List words) { System.out.println("======== useCollectorOrToList ========"); System.out.println("initial size = " + words.size()); - //Use collectors instead - List result = words.parallelStream() - .map(String::toUpperCase) - .toList(); - //.collect(Collectors.toList()); + // Use collectors instead + List result = words.parallelStream().map(String::toUpperCase).toList(); + // .collect(Collectors.toList()); System.out.println("initial size = " + result.size()); } @@ -32,11 +30,11 @@ private static void useCollectorOrToList(List words) { private static void sharedMutabilityParallelism(List words) { System.out.println("======== sharedMutabilityParallelism ========"); System.out.println("initial size = " + words.size()); - List result = new ArrayList<>();//Shared Mutable Variable + List result = new ArrayList<>(); // Shared Mutable Variable - words.parallelStream()//.stream + words.parallelStream() // .stream .map(String::toUpperCase) - .forEach(name -> result.add(name));//Shared Mutability is BAD + .forEach(name -> result.add(name)); // Shared Mutability is BAD System.out.println("initial size = " + result.size()); } @@ -47,7 +45,8 @@ private static ArrayList getData(String url) { // Create a URL a5object URL urlObject = new URL(url); // Open a connection to the URL - BufferedReader reader = new BufferedReader(new InputStreamReader(urlObject.openStream())); + BufferedReader reader = + new BufferedReader(new InputStreamReader(urlObject.openStream())); String line; while ((line = reader.readLine()) != null) { words.add(line); diff --git a/src/main/java/nitin/zKnowYourJava/T5StreamLazyEvaluation.java b/src/main/java/nitin/zKnowYourJava/T5StreamLazyEvaluation.java index c85e3d45..5960b7f7 100644 --- a/src/main/java/nitin/zKnowYourJava/T5StreamLazyEvaluation.java +++ b/src/main/java/nitin/zKnowYourJava/T5StreamLazyEvaluation.java @@ -4,20 +4,24 @@ public class T5StreamLazyEvaluation { public static void main(String[] args) { - Integer multiplier = 2;//error: local variables referenced from a lambda expression must be final or effectively final - final int finalMultiplier = multiplier;//Either use the final variable so that no mutation can happen - int[] factor = new int[]{2}; + Integer multiplier = + 2; // error: local variables referenced from a lambda expression must be final or + // effectively final + final int finalMultiplier = + multiplier; // Either use the final variable so that no mutation can happen + int[] factor = new int[] {2}; var numbers = List.of(1, 2, 3); - var stream = numbers.stream() - //.map(number -> number * finalMultiplier) - .map(number -> factor[0]);//Does not evaluate yet, as there is no terminal operator + var stream = + numbers.stream() + // .map(number -> number * finalMultiplier) + .map(number -> factor[0]); // Does not evaluate yet, as there is no + // terminal operator // multiplier = 0;//Mutating the multiplier // finalMultiplier = 0;//Can't happen factor[0] = 0; - stream.forEach(System.out::println);//Evaluates here - + stream.forEach(System.out::println); // Evaluates here } } diff --git a/src/main/java/nitin/zKnowYourJava/T6ParallelStreams.java b/src/main/java/nitin/zKnowYourJava/T6ParallelStreams.java index 35de93ed..38575d25 100644 --- a/src/main/java/nitin/zKnowYourJava/T6ParallelStreams.java +++ b/src/main/java/nitin/zKnowYourJava/T6ParallelStreams.java @@ -4,11 +4,10 @@ public class T6ParallelStreams { public static void main(String[] args) { - //Which Thread will transform method run - List.of(1, 2, 3) - .parallelStream() + // Which Thread will transform method run + List.of(1, 2, 3).parallelStream() .map(number -> transform(number)) - //.sequential()//The **last setting** overrides the entire pipeline. + // .sequential()//The **last setting** overrides the entire pipeline. .forEach(number -> print(number)); } diff --git a/src/main/java/nitin/zKnowYourJava/T7/Base.java b/src/main/java/nitin/zKnowYourJava/T7/Base.java index f58402c0..256d6f6b 100644 --- a/src/main/java/nitin/zKnowYourJava/T7/Base.java +++ b/src/main/java/nitin/zKnowYourJava/T7/Base.java @@ -1,12 +1,11 @@ package nitin.zKnowYourJava.T7; public class Base { - public Base() {//Constructor + public Base() { // Constructor System.out.println("In base"); - check();// The check of the Derived is called + check(); // The check of the Derived is called } - //No Definition - public void check() { - } + // No Definition + public void check() {} } diff --git a/src/main/java/nitin/zKnowYourJava/T7Inheritance.java b/src/main/java/nitin/zKnowYourJava/T7Inheritance.java index 958e60fa..81a27c69 100644 --- a/src/main/java/nitin/zKnowYourJava/T7Inheritance.java +++ b/src/main/java/nitin/zKnowYourJava/T7Inheritance.java @@ -11,4 +11,3 @@ public static void main(String[] args) { } } } - diff --git a/src/main/java/nitin/zKnowYourJava/T8TypeInference2.java b/src/main/java/nitin/zKnowYourJava/T8TypeInference2.java index 3242474b..ff801fbe 100644 --- a/src/main/java/nitin/zKnowYourJava/T8TypeInference2.java +++ b/src/main/java/nitin/zKnowYourJava/T8TypeInference2.java @@ -4,11 +4,18 @@ public class T8TypeInference2 { public static void main(String[] args) { - var list = List.of(2, 3.14, "text", new StringBuilder("edit"));//Objects, Serializable and Comparable + var list = + List.of( + 2, + 3.14, + "text", + new StringBuilder("edit")); // Objects, Serializable and Comparable - //Type witness or Type hint - //var list = List.of(2, 3.14, "text", new StringBuilder("edit"));// java.lang.UnsupportedOperationException - //List list = List.of(2, 3.14, "text", new StringBuilder("edit"));// java.lang.UnsupportedOperationException + // Type witness or Type hint + // var list = List.of(2, 3.14, "text", new StringBuilder("edit"));// + // java.lang.UnsupportedOperationException + // List list = List.of(2, 3.14, "text", new StringBuilder("edit"));// + // java.lang.UnsupportedOperationException try { list.add(new T8TypeInference2()); diff --git a/src/main/java/nitin/zKnowYourJava/T9toList.java b/src/main/java/nitin/zKnowYourJava/T9toList.java index 1f3cdd92..3a8bff38 100644 --- a/src/main/java/nitin/zKnowYourJava/T9toList.java +++ b/src/main/java/nitin/zKnowYourJava/T9toList.java @@ -5,14 +5,15 @@ public class T9toList { public static void main(String[] args) { - //Which is better : toList or .collect(Collectors.toList()) - var result = List.of(1, 2, 3).stream() - .map(num -> num * 2) - //.toList(); - //.collect(Collectors.toList());//Mutable - .collect(Collectors.toUnmodifiableList());//Immutable + // Which is better : toList or .collect(Collectors.toList()) + var result = + List.of(1, 2, 3).stream() + .map(num -> num * 2) + // .toList(); + // .collect(Collectors.toList());//Mutable + .collect(Collectors.toUnmodifiableList()); // Immutable - //result.add(800); + // result.add(800); System.out.println(result.getClass()); System.out.println(result); } diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/Averager.java b/src/main/java/nitin/zOReiley2020SimonRoberts/Averager.java index 35441b85..ff6cb942 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/Averager.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/Averager.java @@ -25,11 +25,13 @@ public double get() { public class Averager { public static void main(String[] args) { long start = System.nanoTime(); - Average av = DoubleStream.generate(() -> ThreadLocalRandom.current().nextDouble(-Math.PI, Math.PI)) - .parallel() - .limit(200_000_000) - .map(Math::sin) - .collect(Average::new, Average::include, Average::merge); + Average av = + DoubleStream.generate( + () -> ThreadLocalRandom.current().nextDouble(-Math.PI, Math.PI)) + .parallel() + .limit(200_000_000) + .map(Math::sin) + .collect(Average::new, Average::include, Average::merge); long end = System.nanoTime(); double mean = av.get(); diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/Car.java b/src/main/java/nitin/zOReiley2020SimonRoberts/Car.java index 94e8c8ef..3ac46b5c 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/Car.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/Car.java @@ -5,16 +5,16 @@ public class Car { - private static final Predicate RED_CAR_CRITERION - = c -> c.color.equals("Red"); + private static final Predicate RED_CAR_CRITERION = c -> c.color.equals("Red"); private static final Comparator fuelComparator = (o1, o2) -> o1.gasLevel - o2.gasLevel; - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -22,20 +22,24 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY // using a named static factory for this, able to convey the meaning of the arguments. - //It's interesting to note that with the release of Java 8, virtually all of the new APIs made exclusive use of static + // It's interesting to note that with the release of Java 8, virtually all of the new APIs made + // exclusive use of static // factories instead of having public constructors, with the exception of Exceptions. public static Car withGasColorPassengers(int gas, String color, String... passengers) { - // And one of the things that functional programming likes to do is to use immutable data whenever possible. - //t's generally considered to be preferable to create a new version of something rather than to change an existing something + // And one of the things that functional programming likes to do is to use immutable data + // whenever possible. + // t's generally considered to be preferable to create a new version of something rather + // than to change an existing something List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); return self; } - //Notice the list of arguments. This would not have been possible with public constructors as this would not + // Notice the list of arguments. This would not have been possible with public constructors as + // this would not // have been a valid overload public static Car withGasColorPassengersAndTrunk(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); @@ -91,7 +95,14 @@ public Optional> getTrunkContentsOpt() { @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } } diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/CarScratch.java b/src/main/java/nitin/zOReiley2020SimonRoberts/CarScratch.java index c165ac3c..18969bee 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/CarScratch.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/CarScratch.java @@ -36,13 +36,14 @@ public static List filter(Iterable lc, Predicate criterion) { } public static void main(String[] args) { - List cars = Arrays.asList( - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); + List cars = + Arrays.asList( + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); showAll(cars); showAll(filter(cars, Car.getRedCarCriterion())); @@ -56,14 +57,16 @@ public static void main(String[] args) { showAll(filter(cars, c -> c.getPassengers().size() < 3)); - List words = Arrays.asList("LightCoral", "pink", "Orange", "Gold", "plum", "Blue", "limegreen"); + List words = + Arrays.asList("LightCoral", "pink", "Orange", "Gold", "plum", "Blue", "limegreen"); System.out.println("Long color names:"); showAll(filter(words, w -> w.length() > 4)); System.out.println("Capitalized color names:"); showAll(filter(words, w -> Character.isUpperCase(w.charAt(0)))); LocalDate today = LocalDate.now(); - List appointments = Arrays.asList(today, today.plusDays(2), today.minusDays(4), today.plusMonths(1)); + List appointments = + Arrays.asList(today, today.plusDays(2), today.minusDays(4), today.plusMonths(1)); System.out.println("All appointments"); showAll(appointments); System.out.println("Future appointments after: " + today); diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/Concordance.java b/src/main/java/nitin/zOReiley2020SimonRoberts/Concordance.java index b01304e0..c76b15e1 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/Concordance.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/Concordance.java @@ -13,8 +13,8 @@ public class Concordance { private static final Pattern WORD_BREAK = Pattern.compile("\\W+"); - private static final Comparator> valueOrder - = Map.Entry.comparingByValue(); + private static final Comparator> valueOrder = + Map.Entry.comparingByValue(); public static Optional> lines(Path p) { try { @@ -25,14 +25,16 @@ public static Optional> lines(Path p) { } public static void main(String[] args) throws IOException { - List filenames = Arrays.asList("PrideAndPrejudice.txt", "Bad.txt", "Emma.txt", "SenseAndSensibility.txt"); + List filenames = + Arrays.asList( + "PrideAndPrejudice.txt", "Bad.txt", "Emma.txt", "SenseAndSensibility.txt"); filenames.stream() .map(Paths::get) -// .flatMap(Files::lines) -// .map(Concordance::lines) -// .peek(s -> {if (!s.isPresent()) System.err.println("Bad file");}) -// .filter(Optional::isPresent) -// .flatMap(Optional::get) + // .flatMap(Files::lines) + // .map(Concordance::lines) + // .peek(s -> {if (!s.isPresent()) System.err.println("Bad file");}) + // .filter(Optional::isPresent) + // .flatMap(Optional::get) .map(Either.wrap(Files::lines)) .peek(e -> e.handle(System.err::println)) .filter(Either::succeeded) @@ -41,11 +43,11 @@ public static void main(String[] args) throws IOException { .flatMap(WORD_BREAK::splitAsStream) .filter(s -> s.length() > 0) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) - .entrySet().stream() + .entrySet() + .stream() .sorted(valueOrder.reversed()) .limit(200) .map(e -> String.format("%20s : %5d", e.getKey(), e.getValue())) .forEach(System.out::println); } } - diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/Either.java b/src/main/java/nitin/zOReiley2020SimonRoberts/Either.java index 9e22d91c..21cb2738 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/Either.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/Either.java @@ -7,8 +7,7 @@ public class Either { private E value; private Throwable problem; - private Either() { - } + private Either() {} public static Either success(E v) { Either self = new Either<>(); diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/NullChecks.java b/src/main/java/nitin/zOReiley2020SimonRoberts/NullChecks.java index 636c6b44..a7f03e4b 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/NullChecks.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/NullChecks.java @@ -26,9 +26,7 @@ public static void main(String[] args) { Optional> ownersOpt = Optional.of(owners); ownersOpt .map(m -> m.get(owner)) - .map(x -> x.getTrunkContentsOpt() - .map(y -> y.toString()) - .orElse("nothing")) + .map(x -> x.getTrunkContentsOpt().map(y -> y.toString()).orElse("nothing")) .map(x -> owner + " has " + x + " in the car") .ifPresent(m -> System.out.println(m)); } diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/Car1.java index 44d381ec..0377b809 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/Car1.java @@ -5,13 +5,14 @@ import java.util.List; class Car1 { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -19,7 +20,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -53,15 +54,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } /********************************************************************************************************************* @@ -69,7 +77,8 @@ public String toString() { * ******************************************************************************************************************* ********************************************************************************************************************/ - //Static inner class shares the same behaviour with all the instances. Static members vs instance members -> + // Static inner class shares the same behaviour with all the instances. Static members vs + // instance members -> // the criteria is shared wil all the objects static class GasLevelCarCriterion implements CarCriteria1 { private final int threshold; diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarCriteria1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarCriteria1.java index a622b1d1..16cede0c 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarCriteria1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarCriteria1.java @@ -1,8 +1,7 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r0Ownership; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:04 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:04 AM */ interface CarCriteria1 { boolean test(Car1 car); diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarRunner1.java index 0998f40f..7783177a 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r0Ownership/CarRunner1.java @@ -7,36 +7,37 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - //The behaviour of decision making is passed as an argument. + // The behaviour of decision making is passed as an argument. showAll(getCarsByCriteria1(cars, new Car1.RedCarCriterion())); System.out.println("************ GasLevelCarCriterion ************"); showAll(getCarsByCriteria1(cars, new Car1.GasLevelCarCriterion(7))); - //Original List is not changed + // Original List is not changed showAll(cars); } private static List getCarsByCriteria1(Iterable iter, CarCriteria1 criteria) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car1 c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -46,9 +47,9 @@ private static List getCarsByCriteria1(Iterable iter, CarCriteria1 c public static void showAll(List lc) { for (Car1 c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/Car1.java index 1572e7d9..0279947e 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/Car1.java @@ -5,15 +5,16 @@ import java.util.List; class Car1 { - //Making private to force the use of factory or singleton + // Making private to force the use of factory or singleton private static final RedCarCriterion RED_CAR_CRITERION = new RedCarCriterion(); - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -21,7 +22,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -35,12 +36,13 @@ static Car1 withGasColorPassengersAndTrunk(int gas, String color, String... pass return self; } - //Factory method : Much better than the constructor approach - //Here getRedCarCriterion has a choice of implementing the new a5object or the single static a5object - //public static RedCarCriterion getRedCarCriterion(){ + // Factory method : Much better than the constructor approach + // Here getRedCarCriterion has a choice of implementing the new a5object or the single static + // a5object + // public static RedCarCriterion getRedCarCriterion(){ public static CarCriteria1 getRedCarCriterion() { - return RED_CAR_CRITERION; //This is Singleton design pattern. - //return new RedCarCriterion(); + return RED_CAR_CRITERION; // This is Singleton design pattern. + // return new RedCarCriterion(); } /* Not Singleton as there is an argument, threshold, that is unique to each a5object.*/ @@ -68,15 +70,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } /********************************************************************************************************************* @@ -84,7 +93,8 @@ public String toString() { * ******************************************************************************************************************* ********************************************************************************************************************/ - //Static inner class shares the same behaviour with all the instances. Static members vs instance members -> + // Static inner class shares the same behaviour with all the instances. Static members vs + // instance members -> // the criteria is shared wil all the objects private static class GasLevelCarCriterion implements CarCriteria1 { private final int threshold; diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarCriteria1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarCriteria1.java index 25d761a7..54b2b12a 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarCriteria1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarCriteria1.java @@ -1,9 +1,8 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r1Quantity; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:08 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:08 AM */ interface CarCriteria1 { boolean test(Car1 car); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarRunner1.java index 47c39535..c74b2ef8 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r1Quantity/CarRunner1.java @@ -7,44 +7,51 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - //Factory type of approach. Instead of calling a static field, call a static method. - //showAll(getCarsByCriteria1(cars, Car1.RED_CAR_CRITERION)); + // Factory type of approach. Instead of calling a static field, call a static method. + // showAll(getCarsByCriteria1(cars, Car1.RED_CAR_CRITERION)); - //Here getRedCarCriterion has a choice of implementing the new a5object or the single static a5object - // If the below line is to be used 5 10 times within the same code, the new approach will created multiple objects, + // Here getRedCarCriterion has a choice of implementing the new a5object or the single + // static a5object + // If the below line is to be used 5 10 times within the same code, the new approach will + // created multiple objects, // while the static field will only create it once - //showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion())); + // showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion())); - //Calling directly by the interface name instead of its implementation - //showAll(getCarsByCriteria1(cars, Car1.getCarCriterion())); - showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion()));//****** Singletom *********** + // Calling directly by the interface name instead of its implementation + // showAll(getCarsByCriteria1(cars, Car1.getCarCriterion())); + showAll( + getCarsByCriteria1( + cars, Car1.getRedCarCriterion())); // ****** Singletom *********** System.out.println("************ GasLevelCarCriterion ************"); - showAll(getCarsByCriteria1(cars, Car1.getGasLevelCarCriterion(7)));//****** Not a Singleton ****** + showAll( + getCarsByCriteria1( + cars, Car1.getGasLevelCarCriterion(7))); // ****** Not a Singleton ****** - //Original List is not changed + // Original List is not changed showAll(cars); } private static List getCarsByCriteria1(Iterable iter, CarCriteria1 criteria) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car1 c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -54,9 +61,9 @@ private static List getCarsByCriteria1(Iterable iter, CarCriteria1 c public static void showAll(List lc) { for (Car1 c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/Car1.java index bb5e1c10..5bd8009b 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/Car1.java @@ -10,31 +10,34 @@ class Car1 { * ******************************************************************************************************************* ********************************************************************************************************************/ - - //Using Anonymous Class - /* private static final RedCarCriterion RED_CAR_CRITERION = new *//*RedCarCriterion(); - - static class RedCarCriterion implements *//*CarRunner1.CarCriteria1 { - @Override - public boolean test(Car1 car) { - return car.getColor().equals("Red"); - } - }*/ - - - private static final CarCriteria1 RED_CAR_CRITERION = new CarCriteria1() { - @Override - public boolean test(Car1 car) { - return car.getColor().equals("Red"); - } - }; - //Fields of Class Car + // Using Anonymous Class + /* private static final RedCarCriterion RED_CAR_CRITERION = new */ + /*RedCarCriterion(); + + static class RedCarCriterion implements */ + /*CarRunner1.CarCriteria1 { + @Override + public boolean test(Car1 car) { + return car.getColor().equals("Red"); + } + }*/ + + private static final CarCriteria1 RED_CAR_CRITERION = + new CarCriteria1() { + @Override + public boolean test(Car1 car) { + return car.getColor().equals("Red"); + } + }; + + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -42,7 +45,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -56,12 +59,13 @@ static Car1 withGasColorPassengersAndTrunk(int gas, String color, String... pass return self; } - //Factory method : Much better than the constructor approach - //Here getRedCarCriterion has a choice of implementing the new a5object or the single static a5object - //public static RedCarCriterion getRedCarCriterion(){ + // Factory method : Much better than the constructor approach + // Here getRedCarCriterion has a choice of implementing the new a5object or the single static + // a5object + // public static RedCarCriterion getRedCarCriterion(){ public static CarCriteria1 getRedCarCriterion() { - return RED_CAR_CRITERION; //This is Singleton design pattern. - //return new RedCarCriterion(); + return RED_CAR_CRITERION; // This is Singleton design pattern. + // return new RedCarCriterion(); } /* Not Singleton as there is amn argument, threshold, that is unique to each a5object.*/ @@ -89,18 +93,26 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } - //Static inner class shares the same behaviour with all the instances. Static members vs instance members -> + // Static inner class shares the same behaviour with all the instances. Static members vs + // instance members -> // the criteria is shared wil all the objects private static class GasLevelCarCriterion implements CarCriteria1 { private final int threshold; diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarCriteria1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarCriteria1.java index a69f46da..ade92002 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarCriteria1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarCriteria1.java @@ -1,8 +1,7 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r2VisibilityNAnonymity; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:12 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:12 AM */ public interface CarCriteria1 { boolean test(Car1 car); diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarRunner1.java index c58891f5..b5c832e3 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r2VisibilityNAnonymity/CarRunner1.java @@ -7,44 +7,51 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - //Factory type of approach. Instead of calling a static field, call a static method. - //showAll(getCarsByCriteria1(cars, Car1.RED_CAR_CRITERION)); + // Factory type of approach. Instead of calling a static field, call a static method. + // showAll(getCarsByCriteria1(cars, Car1.RED_CAR_CRITERION)); - //Here getRedCarCriterion has a choice of implementing the new a5object or the single static a5object - // If the below line is to be used 5 10 times within the same code, the new approach will created multiple objects, + // Here getRedCarCriterion has a choice of implementing the new a5object or the single + // static a5object + // If the below line is to be used 5 10 times within the same code, the new approach will + // created multiple objects, // while the static field will only create it once - //showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion())); + // showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion())); - //Calling directly by the interface name instead of its implementation - //showAll(getCarsByCriteria1(cars, Car1.getCarCriterion())); - showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion()));//****** Singletom *********** + // Calling directly by the interface name instead of its implementation + // showAll(getCarsByCriteria1(cars, Car1.getCarCriterion())); + showAll( + getCarsByCriteria1( + cars, Car1.getRedCarCriterion())); // ****** Singletom *********** System.out.println("************ GasLevelCarCriterion ************"); - showAll(getCarsByCriteria1(cars, Car1.getGasLevelCarCriterion(7)));//****** Not a Singleton ****** + showAll( + getCarsByCriteria1( + cars, Car1.getGasLevelCarCriterion(7))); // ****** Not a Singleton ****** - //Original List is not changed + // Original List is not changed showAll(cars); } private static List getCarsByCriteria1(Iterable iter, CarCriteria1 criteria) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car1 c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -54,9 +61,9 @@ private static List getCarsByCriteria1(Iterable iter, CarCriteria1 c public static void showAll(List lc) { for (Car1 c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/Car1.java index e0570567..c146f3ac 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/Car1.java @@ -10,25 +10,28 @@ class Car1 { * ******************************************************************************************************************* ********************************************************************************************************************/ - //Anonymous Inner Class - /*private static final CarRunner1.CarCriteria1 RED_CAR_CRITERION = new CarRunner1.CarCriteria1() { - @Override - public boolean test(Car1 car) { - return car.getColor().equals("Red"); - } -};*/ - - //Replacing anony. class with Lambda - private static final CarCriteria1 RED_CAR_CRITERION = (Car1 car) -> { + // Anonymous Inner Class + /*private static final CarRunner1.CarCriteria1 RED_CAR_CRITERION = new CarRunner1.CarCriteria1() { + @Override + public boolean test(Car1 car) { return car.getColor().equals("Red"); - };// This colon is marking the end of the assignment of the LHS - //Fields of Class Car + } + };*/ + + // Replacing anony. class with Lambda + private static final CarCriteria1 RED_CAR_CRITERION = + (Car1 car) -> { + return car.getColor().equals("Red"); + }; // This colon is marking the end of the assignment of the LHS + + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -36,7 +39,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -51,8 +54,8 @@ static Car1 withGasColorPassengersAndTrunk(int gas, String color, String... pass } public static CarCriteria1 getRedCarCriterion() { - return RED_CAR_CRITERION; //This is Singleton design pattern. - //return new RedCarCriterion(); + return RED_CAR_CRITERION; // This is Singleton design pattern. + // return new RedCarCriterion(); } public static CarCriteria1 getGasLevelCarCriterion(int threshold) { @@ -79,18 +82,26 @@ public List getTrunkContents() { return trunkContents; } - //Simplified - //private static final CarRunner1.CarCriteria1 RED_CAR_CRITERION = c -> c.getColor().equals("Red"); + // Simplified + // private static final CarRunner1.CarCriteria1 RED_CAR_CRITERION = c -> + // c.getColor().equals("Red"); - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } private static class GasLevelCarCriterion implements CarCriteria1 { diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarCriteria1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarCriteria1.java index 8c38dc95..ef2df8f3 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarCriteria1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarCriteria1.java @@ -1,8 +1,7 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r3IntroducingLambda; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:16 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:16 AM */ public interface CarCriteria1 { boolean test(Car1 car); diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarRunner1.java index ad6faf56..cf465884 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r3IntroducingLambda/CarRunner1.java @@ -7,44 +7,51 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - //Factory type of approach. Instead of calling a static field, call a static method. - //showAll(getCarsByCriteria1(cars, Car1.RED_CAR_CRITERION)); + // Factory type of approach. Instead of calling a static field, call a static method. + // showAll(getCarsByCriteria1(cars, Car1.RED_CAR_CRITERION)); - //Here getRedCarCriterion has a choice of implementing the new a5object or the single static a5object - // If the below line is to be used 5 10 times within the same code, the new approach will created multiple objects, + // Here getRedCarCriterion has a choice of implementing the new a5object or the single + // static a5object + // If the below line is to be used 5 10 times within the same code, the new approach will + // created multiple objects, // while the static field will only create it once - //showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion())); + // showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion())); - //Calling directly by the interface name instead of its implementation - //showAll(getCarsByCriteria1(cars, Car1.getCarCriterion())); - showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion()));//****** Singletom *********** + // Calling directly by the interface name instead of its implementation + // showAll(getCarsByCriteria1(cars, Car1.getCarCriterion())); + showAll( + getCarsByCriteria1( + cars, Car1.getRedCarCriterion())); // ****** Singletom *********** System.out.println("************ GasLevelCarCriterion ************"); - showAll(getCarsByCriteria1(cars, Car1.getGasLevelCarCriterion(7)));//****** Not a Singleton ****** + showAll( + getCarsByCriteria1( + cars, Car1.getGasLevelCarCriterion(7))); // ****** Not a Singleton ****** - //Original List is not changed + // Original List is not changed showAll(cars); } private static List getCarsByCriteria1(Iterable iter, CarCriteria1 criteria) { - //Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST + // Return a new list: Functional style : DO NOT MODIFY THE ORIGINAL LIST List returnCars = new ArrayList<>(); for (Car1 c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -54,9 +61,9 @@ private static List getCarsByCriteria1(Iterable iter, CarCriteria1 c public static void showAll(List lc) { for (Car1 c : lc) { - //Printing each car using toString representation + // Printing each car using toString representation System.out.println(c); } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Car1.java index 47476b8b..6446831f 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Car1.java @@ -11,14 +11,16 @@ class Car1 { ********************************************************************************************************************/ // Expression Lambda private static final CarCriteria1 RED_CAR_CRITERION = c -> c.getColor().equals("Red"); - //Fields of Class Car + + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -26,7 +28,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -47,8 +49,8 @@ public static CarCriteria1 getFourPassengerCriterion() { } public static CarCriteria1 getRedCarCriterion() { - return RED_CAR_CRITERION; //This is Singleton design pattern. - //return new RedCarCriterion(); + return RED_CAR_CRITERION; // This is Singleton design pattern. + // return new RedCarCriterion(); } public static CarCriteria1 getGasLevelCarCriterion(int threshold) { @@ -75,15 +77,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } private static class GasLevelCarCriterion implements CarCriteria1 { @@ -98,4 +107,4 @@ public boolean test(Car1 car) { return car.getGasLevel() >= threshold; } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarCriteria1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarCriteria1.java index d8718b6f..c80c41c7 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarCriteria1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarCriteria1.java @@ -1,9 +1,8 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r4GivingTypeToALambda; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ public interface CarCriteria1 { boolean test(Car1 car); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarRunner1.java index 0deb1e34..34d9edfa 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/CarRunner1.java @@ -7,28 +7,32 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); - //Calling Utility Method + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - showAll(getCarsByCriteria1(cars, Car1.getRedCarCriterion()));//****** Singletom *********** + showAll( + getCarsByCriteria1( + cars, Car1.getRedCarCriterion())); // ****** Singletom *********** System.out.println("************ getFourPassengerCriterion ************"); showAll(getCarsByCriteria1(cars, Car1.getFourPassengerCriterion())); - System.out.println("************ Passing Lambda. The method argument decides the type of the Lambda expression ************"); + System.out.println( + "************ Passing Lambda. The method argument decides the type of the Lambda expression ************"); showAll(getCarsByCriteria1(cars, c -> c.getPassengers().size() == 2)); - //Original List is not changed + // Original List is not changed showAll(cars); // Lambda Assignment @@ -36,23 +40,29 @@ public static void main(String[] args) { // Giving context to an stand alone Lambda to help determine its type. // The Cast provides the necessasary context for the Lambda expression to be successful. - // ((CarCriteria1)(c -> c.getColor().equals("Red"))) is an a5object reference of type CarCriteria1 and thus the test + // ((CarCriteria1)(c -> c.getColor().equals("Red"))) is an a5object reference of type + // CarCriteria1 and thus the test // method can be invoked. - boolean b1 = ((CarCriteria1) (c -> c.getColor().equals("Red"))).test(Car1.withGasColorPassengers(0, "Red")); + boolean b1 = + ((CarCriteria1) (c -> c.getColor().equals("Red"))) + .test(Car1.withGasColorPassengers(0, "Red")); // a single lambda expression could potentially be compiled into multiple - //different interfaces depending on the context. Almost the same context. - boolean b2 = ((Strange) ((Car1 c) -> c.getColor().equals("Red"))).anotherTestStuff(Car1.withGasColorPassengers(0, "Red")); + // different interfaces depending on the context. Almost the same context. + boolean b2 = + ((Strange) ((Car1 c) -> c.getColor().equals("Red"))) + .anotherTestStuff(Car1.withGasColorPassengers(0, "Red")); - System.out.println("a single lambda expression could potentially be compiled into multiple " + - "different interfaces depending on the context"); + System.out.println( + "a single lambda expression could potentially be compiled into multiple " + + "different interfaces depending on the context"); System.out.println("B1 = " + b1 + " abd B2 = " + b2); } private static List getCarsByCriteria1(Iterable iter, CarCriteria1 criteria) { List returnCars = new ArrayList<>(); for (Car1 c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -66,4 +76,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Strange.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Strange.java index 3aaf191f..3c3e2d55 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Strange.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r4GivingTypeToALambda/Strange.java @@ -1,13 +1,12 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r4GivingTypeToALambda; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 12:11 PM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 12:11 PM */ - @FunctionalInterface public interface Strange { - //Just takes a car1 as an argument. This is the only similarity with the Car1 Interface, along with the return type + // Just takes a car1 as an argument. This is the only similarity with the Car1 Interface, along + // with the return type boolean anotherTestStuff(Car1 car); } diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Car1.java index 37faf543..15ebdc08 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Car1.java @@ -11,14 +11,16 @@ class Car1 { ********************************************************************************************************************/ // Expression Lambda private static final Criteria RED_CAR_CRITERION = c -> c.getColor().equals("Red"); - //Fields of Class Car + + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -26,7 +28,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -47,8 +49,8 @@ public static Criteria getFourPassengerCriterion() { } public static Criteria getRedCarCriterion() { - return RED_CAR_CRITERION; //This is Singleton design pattern. - //return new RedCarCriterion(); + return RED_CAR_CRITERION; // This is Singleton design pattern. + // return new RedCarCriterion(); } // Factory for creating GasLevelCarCriterion @@ -76,15 +78,22 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } private static class GasLevelCarCriterion implements Criteria { @@ -99,4 +108,4 @@ public boolean test(Car1 car) { return car.getGasLevel() >= threshold; } } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/CarRunner1.java index f7ed87db..3e65eb89 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/CarRunner1.java @@ -7,40 +7,41 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); showAll(cars); System.out.println("************ getCarsByCriteria ************"); - showAll(getByCriteria(cars, Car1.getRedCarCriterion()));//****** Singletom *********** + showAll(getByCriteria(cars, Car1.getRedCarCriterion())); // ****** Singletom *********** System.out.println("************ getFourPassengerCriterion ************"); showAll(getByCriteria(cars, Car1.getFourPassengerCriterion())); - System.out.println("************ Passing Lambda. The method argument decides the type of the Lambda expression ************"); + System.out.println( + "************ Passing Lambda. The method argument decides the type of the Lambda expression ************"); showAll(getByCriteria(cars, c -> c.getPassengers().size() == 2)); - //Original List is not changed + // Original List is not changed showAll(cars); // Lambda Assignment Criteria x = c -> c.getColor().equals("Red"); - } - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Criteria criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -54,4 +55,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Criteria.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Criteria.java index dd059cdb..e6c603c9 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Criteria.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r5genericsNgeneralization/Criteria.java @@ -1,11 +1,9 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r5genericsNgeneralization; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ - @FunctionalInterface public interface Criteria { boolean test(E e); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/Criteria.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/Criteria.java index f149adeb..0205df58 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/Criteria.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/Criteria.java @@ -1,11 +1,9 @@ package nitin.zOReiley2020SimonRoberts.f2functionalConcepts.r6generalizationDemo; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ - @FunctionalInterface public interface Criteria { boolean test(E e); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/CriteriaRunner.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/CriteriaRunner.java index e251fc55..9082dd40 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/CriteriaRunner.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f2functionalConcepts/r6generalizationDemo/CriteriaRunner.java @@ -7,11 +7,11 @@ class CriteriaRunner { - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Criteria criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -20,25 +20,29 @@ private static List getByCriteria(Iterable iter, Criteria criteria) } public static void main(String[] args) { - List names = Arrays.asList( - "Haradanahalli Doddegowda Deve Gowda", - "Avul Pakir Jainulabdeen Abdul Kalam", - "Venkata Narasimha Rajuvaripet", - "Sarvepalli Radhakrishnan", - "Kocheril Raman Narayanan", - "Puratchi Thalaivar Maruthur Gopalan Ramachandran" - ); + List names = + Arrays.asList( + "Haradanahalli Doddegowda Deve Gowda", + "Avul Pakir Jainulabdeen Abdul Kalam", + "Venkata Narasimha Rajuvaripet", + "Sarvepalli Radhakrishnan", + "Kocheril Raman Narayanan", + "Puratchi Thalaivar Maruthur Gopalan Ramachandran"); List namesGT30Chars = getByCriteria(names, st -> st.length() >= 30); showAll(namesGT30Chars); - System.out.println("*********************************************************************************************"); - List intList = Arrays.asList(2, 43, 564567, 678, 897, 9874, 456, 23, 3, 5, 3, 25324, 45, 6546, 56); + System.out.println( + "*********************************************************************************************"); + List intList = + Arrays.asList(2, 43, 564567, 678, 897, 9874, 456, 23, 3, 5, 3, 25324, 45, 6546, 56); List intListFiltered = getByCriteria(intList, ints -> ints > 999); showAll(intListFiltered); - System.out.println(" ********************************************************************************************"); + System.out.println( + " ********************************************************************************************"); LocalDate today = LocalDate.now(); - List appointments = Arrays.asList(today, today.plusDays(2), today.minusDays(4), today.plusMonths(1)); + List appointments = + Arrays.asList(today, today.plusDays(2), today.minusDays(4), today.plusMonths(1)); System.out.println("All appointments"); showAll(appointments); System.out.println("Future appointments after: " + today); @@ -51,4 +55,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Car1.java index f182b373..c15d0d43 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Car1.java @@ -5,14 +5,15 @@ import java.util.List; class Car1 { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -20,7 +21,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -39,11 +40,13 @@ static Car1 withGasColorPassengersAndTrunk(int gas, String color, String... pass * ******************************************************************************************************************* ********************************************************************************************************************/ - // Factory for creating GasLevelCarCriterion using anonymous inner class. Variable is shared between lambda. + // Factory for creating GasLevelCarCriterion using anonymous inner class. Variable is shared + // between lambda. // Its effectively final. Can be used, but cannot be modified public static Criteria getGasLevelCarCriterion(int threshold) { - //threshold = threshold + 1;//Variable 'threshold' is accessed from within inner class, needs to be final or effectively final + // threshold = threshold + 1;//Variable 'threshold' is accessed from within inner class, + // needs to be final or effectively final return new Criteria() { @Override public boolean test(Car1 car1) { @@ -76,26 +79,33 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } - /*private static class GasLevelCarCriterion implements Criteria { - private int threshold; - public GasLevelCarCriterion(int threshold) { - this.threshold = threshold; - } - - @Override - public boolean test(Car1 car) { - return car.getGasLevel() >= threshold; - } - }*/ -} \ No newline at end of file + /*private static class GasLevelCarCriterion implements Criteria { + private int threshold; + public GasLevelCarCriterion(int threshold) { + this.threshold = threshold; + } + + @Override + public boolean test(Car1 car) { + return car.getGasLevel() >= threshold; + } + }*/ +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/CarRunner1.java index 5c865ce8..eb2c7754 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/CarRunner1.java @@ -7,34 +7,36 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); - //showAll(cars); + // showAll(cars); - System.out.println("************ getGasLevelCarCriterion with value of threshold being passed from method to the Lambda ************"); + System.out.println( + "************ getGasLevelCarCriterion with value of threshold being passed from method to the Lambda ************"); showAll(getByCriteria(cars, Car1.getGasLevelCarCriterion(7))); showAll(getByCriteria(cars, Car1.getGasLevelCarCriterionLambda(5))); - //Original List is not changed - //showAll(cars); + // Original List is not changed + // showAll(cars); } - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Criteria criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -48,4 +50,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Criteria.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Criteria.java index 3b62bcd5..17d07f4d 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Criteria.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s1SingleArgument/Criteria.java @@ -1,11 +1,9 @@ package nitin.zOReiley2020SimonRoberts.f3closures.s1SingleArgument; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ - @FunctionalInterface public interface Criteria { boolean test(E e); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Car1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Car1.java index 08e9df28..404620e2 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Car1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Car1.java @@ -3,14 +3,15 @@ import java.util.*; class Car1 { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car1(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -18,7 +19,7 @@ private Car1(int gasLevel, String color, List passengers, List t this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car1 withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car1 self = new Car1(gas, color, p, null); @@ -37,11 +38,13 @@ static Car1 withGasColorPassengersAndTrunk(int gas, String color, String... pass * ******************************************************************************************************************* ********************************************************************************************************************/ - // Factory for creating GasLevelCarCriterion using anonymous inner class. Variable is shared between lambda. + // Factory for creating GasLevelCarCriterion using anonymous inner class. Variable is shared + // between lambda. // Its effectively final. Can be used, but cannot be modified public static Criteria getGasLevelCarCriterion(int threshold) { - //threshold = threshold + 1;//Variable 'threshold' is accessed from within inner class, needs to be final or effectively final + // threshold = threshold + 1;//Variable 'threshold' is accessed from within inner class, + // needs to be final or effectively final return new Criteria() { @Override public boolean test(Car1 car1) { @@ -81,14 +84,21 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/CarRunner1.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/CarRunner1.java index e2f6701d..3d3daaec 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/CarRunner1.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/CarRunner1.java @@ -7,20 +7,22 @@ class CarRunner1 { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car1.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car1.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car1.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car1.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car1.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car1.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); - //showAll(cars); + // showAll(cars); - System.out.println("************ getGasLevelCarCriterion with value of threshold being passed from method to the Lambda ************"); + System.out.println( + "************ getGasLevelCarCriterion with value of threshold being passed from method to the Lambda ************"); showAll(getByCriteria(cars, Car1.getGasLevelCarCriterion(7))); showAll(getByCriteria(cars, Car1.getGasLevelCarCriterionLambda(5))); @@ -28,16 +30,16 @@ public static void main(String[] args) { System.out.println("************ getColorCriteria with varArg ************"); showAll(getByCriteria(cars, Car1.getColorCriteria("Red", "Green"))); - //Original List is not changed - //showAll(cars); + // Original List is not changed + // showAll(cars); } - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Criteria criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -51,4 +53,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Criteria.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Criteria.java index b825d7e7..7f39f91d 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Criteria.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s2VarArgument/Criteria.java @@ -1,11 +1,9 @@ package nitin.zOReiley2020SimonRoberts.f3closures.s2VarArgument; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ - @FunctionalInterface public interface Criteria { boolean test(E e); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Car.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Car.java index 9836935f..38dc2ff9 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Car.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Car.java @@ -3,14 +3,15 @@ import java.util.*; class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -18,7 +19,7 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); @@ -84,14 +85,21 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; - } -} \ No newline at end of file + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; + } +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/CarRunner.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/CarRunner.java index 1690b480..ae0cd83f 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/CarRunner.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/CarRunner.java @@ -7,18 +7,19 @@ class CarRunner { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); - //showAll(cars); + // showAll(cars); System.out.println("************ getColorCriteria with varArg ************"); showAll(getByCriteria(cars, Car.getColorCriteria("Red", "Green"))); @@ -36,14 +37,13 @@ public static void main(String[] args) { System.out.println("************ red Or Level 7 ************"); Criteria redORlevel7 = Car.or(isRed, level7); showAll(getByCriteria(cars, redORlevel7)); - } - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Criteria criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -57,4 +57,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Criteria.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Criteria.java index d013f713..6dcb9e95 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Criteria.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s3combiningBehaviours/Criteria.java @@ -1,11 +1,9 @@ package nitin.zOReiley2020SimonRoberts.f3closures.s3combiningBehaviours; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ - @FunctionalInterface public interface Criteria { boolean test(E e); -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Car.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Car.java index c6abdd1a..36aba9d3 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Car.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Car.java @@ -3,14 +3,15 @@ import java.util.*; class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -18,7 +19,7 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); @@ -72,14 +73,21 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/CarRunner.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/CarRunner.java index 9b44f160..bfe53cd7 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/CarRunner.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/CarRunner.java @@ -7,18 +7,19 @@ class CarRunner { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); - //showAll(cars); + // showAll(cars); System.out.println("************ getColorCriteria with varArg ************"); showAll(getByCriteria(cars, Car.getColorCriteria("Red", "Green"))); @@ -37,14 +38,13 @@ public static void main(String[] args) { System.out.println("************ red Or Level 7 ************"); Criteria redORlevel7 = isRed.or(level7); showAll(getByCriteria(cars, redORlevel7)); - } - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Criteria criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -58,4 +58,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Criteria.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Criteria.java index 6644346c..d14ea2dd 100644 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Criteria.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s4designCleanup/Criteria.java @@ -1,10 +1,8 @@ package nitin.zOReiley2020SimonRoberts.f3closures.s4designCleanup; /** - * @author Created by nichaurasia - * Created on Friday, September/18/2020 at 10:18 AM + * @author Created by nichaurasia Created on Friday, September/18/2020 at 10:18 AM */ - @FunctionalInterface public interface Criteria { boolean test(E e); @@ -20,4 +18,4 @@ default Criteria or(Criteria crit2) { default Criteria negate() { return x -> !this.test(x); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/Car.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/Car.java index 8fea3722..997e88ec 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/Car.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/Car.java @@ -4,14 +4,15 @@ import java.util.function.Predicate; class Car { - //Fields of Class Car + // Fields of Class Car private final int gasLevel; private final String color; private final List passengers; private final List trunkContents; public String getColor; - // there is a functional programming style that we will be using which will lead us to using factory methods + // there is a functional programming style that we will be using which will lead us to using + // factory methods private Car(int gasLevel, String color, List passengers, List trunkContents) { this.gasLevel = gasLevel; this.color = color; @@ -19,7 +20,7 @@ private Car(int gasLevel, String color, List passengers, List tr this.trunkContents = trunkContents; } - //STATIC FACTORY + // STATIC FACTORY static Car withGasColorPassengers(int gas, String color, String... passengers) { List p = Collections.unmodifiableList(Arrays.asList(passengers)); Car self = new Car(gas, color, p, null); @@ -73,14 +74,21 @@ public List getTrunkContents() { return trunkContents; } - //This could return null; DELIBERATELY WRITTEN FOR DEMO + // This could return null; DELIBERATELY WRITTEN FOR DEMO public List getTrunkContentsOpt() { return (trunkContents); } @Override public String toString() { - return "Car{" + "gasLevel=" + gasLevel + ", color=" + color + ", passengers=" + passengers - + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + '}'; + return "Car{" + + "gasLevel=" + + gasLevel + + ", color=" + + color + + ", passengers=" + + passengers + + (trunkContents != null ? ", trunkContents=" + trunkContents : " no trunk") + + '}'; } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/CarRunner.java b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/CarRunner.java index d5b7ed4a..d06456c5 100755 --- a/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/CarRunner.java +++ b/src/main/java/nitin/zOReiley2020SimonRoberts/f3closures/s5replaceCriteria2Predicate/CarRunner.java @@ -8,18 +8,19 @@ class CarRunner { public static void main(String[] args) { - List cars = Arrays.asList( - //Calling static Factories - Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), - Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), - Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), - Car.withGasColorPassengers(7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), - Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo") - ); - - //Calling Utility Method + List cars = + Arrays.asList( + // Calling static Factories + Car.withGasColorPassengers(6, "Red", "Fred", "Jim", "Sheila"), + Car.withGasColorPassengers(3, "Octarine", "Rincewind", "Ridcully"), + Car.withGasColorPassengers(9, "Black", "Weatherwax", "Magrat"), + Car.withGasColorPassengers( + 7, "Green", "Valentine", "Gillian", "Anne", "Dr. Mahmoud"), + Car.withGasColorPassengers(6, "Red", "Ender", "Hyrum", "Locke", "Bonzo")); + + // Calling Utility Method System.out.println("************ ALL CARS ************"); - //showAll(cars); + // showAll(cars); System.out.println("************ getColorCriteria with varArg ************"); showAll(getByCriteria(cars, Car.getColorCriteria("Red", "Green"))); @@ -38,14 +39,13 @@ public static void main(String[] args) { System.out.println("************ red Or Level 7 ************"); Predicate redORlevel7 = isRed.or(level7); showAll(getByCriteria(cars, redORlevel7)); - } - //The Type declaration of the Generic Variable is placed immediately before the Return Type + // The Type declaration of the Generic Variable is placed immediately before the Return Type private static List getByCriteria(Iterable iter, Predicate criteria) { List returnCars = new ArrayList<>(); for (E c : iter) { - //Passing the criteria based on the users input + // Passing the criteria based on the users input if (criteria.test(c)) { returnCars.add(c); } @@ -59,4 +59,4 @@ public static void showAll(List lc) { } System.out.println("-------------------------------------"); } -} \ No newline at end of file +} diff --git a/src/main/java/nitin/zkcura/java8Solution/part1/Data.java b/src/main/java/nitin/zkcura/java8Solution/part1/Data.java index bd6872fd..3d9e1e3e 100644 --- a/src/main/java/nitin/zkcura/java8Solution/part1/Data.java +++ b/src/main/java/nitin/zkcura/java8Solution/part1/Data.java @@ -2,9 +2,7 @@ import java.util.List; -/** - * Created by nitin on Sunday, October/06/2019 at 10:51 PM - */ +/** Created by nitin on Sunday, October/06/2019 at 10:51 PM */ public class Data { private int population; @@ -51,8 +49,17 @@ public void setInterstates(List interstates) { * */ public String toString() { String value = ""; - value = value + population + "\n" + city + ", " + state + "\n" + "Interstates: " + - interstatesToString(getInterstates()) + "\n"; + value = + value + + population + + "\n" + + city + + ", " + + state + + "\n" + + "Interstates: " + + interstatesToString(getInterstates()) + + "\n"; return value; } @@ -61,12 +68,17 @@ public String toString() { * */ public String aggragateCities() { String value = ""; - value = city + ", " + state + "\n" + "Interstates: " + - interstatesToString(interstates) + "\n"; + value = + city + + ", " + + state + + "\n" + + "Interstates: " + + interstatesToString(interstates) + + "\n"; return value; } - /* Method to Print List of Interstates in the required format */ public String interstatesToString(List iStates) { diff --git a/src/main/java/nitin/zkcura/java8Solution/part1/Driver8.java b/src/main/java/nitin/zkcura/java8Solution/part1/Driver8.java index 31ad7f19..358acc18 100644 --- a/src/main/java/nitin/zkcura/java8Solution/part1/Driver8.java +++ b/src/main/java/nitin/zkcura/java8Solution/part1/Driver8.java @@ -4,21 +4,19 @@ import java.nio.file.Files; import java.util.*; -/** - * Created by nitin on Sunday, October/06/2019 at 10:50 PM - */ +/** Created by nitin on Sunday, October/06/2019 at 10:50 PM */ public class Driver8 { public static final String CITIES_FILE = "Cities_By_Population.txt"; public static final String CITIES_FILE_REVERSED = "Cities_By_Population.txt"; public static final String INTERSTATES_FILE = "Interstates_By_City.txt"; - //public static final String FILE_PATH = "src\\main\\java\\com\\nitin\\zkcura\\java8Solution\\"; + // public static final String FILE_PATH = + // "src\\main\\java\\com\\nitin\\zkcura\\java8Solution\\"; public static final String FILE_PATH = "src/main/java/com/nitin/zkcura/java8Solution/"; - public static void main(String[] args) { if (args.length == 0 || args.length > 1) { - System.err.println("Supply a commandline argument \n" + - "Usage: java DriverMain "); + System.err.println( + "Supply a commandline argument \n" + "Usage: java DriverMain "); return; } @@ -39,7 +37,7 @@ private static void writeInterstatesByCity(List list) { FileWriter fw = null; try { - //Overwrite the File + // Overwrite the File fw = new FileWriter(FILE_PATH + INTERSTATES_FILE, false); } catch (IOException e) { e.printStackTrace(); @@ -49,7 +47,7 @@ private static void writeInterstatesByCity(List list) { Iterator itr = list.listIterator(); - //Map to hold the names of the Interstates and its count + // Map to hold the names of the Interstates and its count Map interstateCountMap = new TreeMap(); while (itr.hasNext()) { @@ -58,24 +56,27 @@ private static void writeInterstatesByCity(List list) { for (int i = 0; i < temp.size(); i++) { String currInterstateName = temp.get(i); - //If the Interstate is not there in the Hashmap + // If the Interstate is not there in the Hashmap if (!interstateCountMap.containsKey(currInterstateName)) { interstateCountMap.put(currInterstateName, 1); } else { - //Increment the count by one - interstateCountMap.put(currInterstateName, interstateCountMap.get(currInterstateName) + 1); + // Increment the count by one + interstateCountMap.put( + currInterstateName, interstateCountMap.get(currInterstateName) + 1); } } } - //There is no direct support for sorting the sets in Java. + // There is no direct support for sorting the sets in Java. // To sort a set, follow these steps: // Convert set to list. // Sort list using Collections.sort() API. // Convert list back to set. List interstateCountList = new ArrayList<>(interstateCountMap.keySet()); - Collections.sort(interstateCountList, ((String a, String b) - -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); + Collections.sort( + interstateCountList, + ((String a, String b) -> + Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); Iterator itr2 = interstateCountList.iterator(); while (itr2.hasNext()) { @@ -91,15 +92,16 @@ private static void writeInterstatesByCity(List list) { private static void writeCitiesByPopulation(List list) { // Sort the List of Objects based on the Population - list.sort(Comparator - .comparing(Data::getPopulation).reversed() - .thenComparing(Data::getState) - .thenComparing(Data::getCity)); + list.sort( + Comparator.comparing(Data::getPopulation) + .reversed() + .thenComparing(Data::getState) + .thenComparing(Data::getCity)); - //list.forEach(System.out::println); + // list.forEach(System.out::println); FileWriter fw = null; try { - //Overwrite in the File + // Overwrite in the File fw = new FileWriter(FILE_PATH + CITIES_FILE, false); } catch (IOException e) { e.printStackTrace(); @@ -112,7 +114,8 @@ private static void writeCitiesByPopulation(List list) { int currentPopulation = -1; while (itr.hasNext()) { Data curr = itr.next(); - // Grouping the cities with same population, if the population is same, all cities are clubbed + // Grouping the cities with same population, if the population is same, all cities are + // clubbed if (currentPopulation == curr.getPopulation()) { printToFile.println(curr.aggragateCities()); } else { @@ -121,12 +124,12 @@ private static void writeCitiesByPopulation(List list) { } } - printToFile.close();//Should have flushed also + printToFile.close(); // Should have flushed also System.out.println("Successfully saved data to file: " + FILE_PATH + CITIES_FILE); } private static void readDataFromFile(List list, File dataFile) { - //Argument has file name.Read the contents of the file and store locally + // Argument has file name.Read the contents of the file and store locally Scanner input = null; try { input = new Scanner(dataFile); @@ -136,36 +139,38 @@ private static void readDataFromFile(List list, File dataFile) { } while (input.hasNext()) { - //Split the tokens based on the delimiter "\" + // Split the tokens based on the delimiter "\" String[] temp = input.nextLine().split("\\|"); - //Put the tokens into an Object of Data Class and continue making a List of Data Object + // Put the tokens into an Object of Data Class and continue making a List of Data Object Data tempData = new Data(); - //Population in 100 thousands + // Population in 100 thousands tempData.setPopulation(Integer.parseInt(temp[0])); tempData.setCity(temp[1]); tempData.setState(temp[2]); - //Sort the interstates and then put into the Object + // Sort the interstates and then put into the Object List interstateList = Arrays.asList(temp[3].split(";")); - //Sorting the List with interstate number - - interstateList.sort(new Comparator() { - @Override - public int compare(String o1, String o2) { - int interstateNumber1 = Integer.parseInt(o1.substring(2)); - int interstateNumber2 = Integer.parseInt(o2.substring(2)); - - if (interstateNumber1 > interstateNumber2) { - return 1; - } else if (interstateNumber1 < interstateNumber2) { - return -1; - } else { - throw new IllegalArgumentException("Two Interstates with same name in a Same City"); - } - } - }); + // Sorting the List with interstate number + + interstateList.sort( + new Comparator() { + @Override + public int compare(String o1, String o2) { + int interstateNumber1 = Integer.parseInt(o1.substring(2)); + int interstateNumber2 = Integer.parseInt(o2.substring(2)); + + if (interstateNumber1 > interstateNumber2) { + return 1; + } else if (interstateNumber1 < interstateNumber2) { + return -1; + } else { + throw new IllegalArgumentException( + "Two Interstates with same name in a Same City"); + } + } + }); tempData.setInterstates(interstateList); list.add(tempData); diff --git a/src/main/java/nitin/zkcura/java8Solution/part2/BredthFirstTraversal.java b/src/main/java/nitin/zkcura/java8Solution/part2/BredthFirstTraversal.java index 560c1be1..789347f6 100644 --- a/src/main/java/nitin/zkcura/java8Solution/part2/BredthFirstTraversal.java +++ b/src/main/java/nitin/zkcura/java8Solution/part2/BredthFirstTraversal.java @@ -1,18 +1,19 @@ package nitin.zkcura.java8Solution.part2; -import nitin.zkcura.oldSolution.part1.Data; - import java.util.*; +import nitin.zkcura.oldSolution.part1.Data; -/** - * Created by Nitin Chaurasia on 11/10/15 at 10:05 PM. - */ +/** Created by Nitin Chaurasia on 11/10/15 at 10:05 PM. */ public class BredthFirstTraversal { - private final Set visited = new HashSet(); + private final Set visited = + new HashSet(); private final Queue inline = new LinkedList(); private final List allCitiesWithDistance = new ArrayList(); - public void traverseGraph(Map> citiesAdjList, nitin.zkcura.oldSolution.part1.Data root) { + public void traverseGraph( + Map> + citiesAdjList, + nitin.zkcura.oldSolution.part1.Data root) { int currDistance = 0; inline.add(new CityDistance(currDistance, root)); visited.add(root); @@ -26,7 +27,8 @@ public void traverseGraph(Map> adjList = new HashMap>(); @@ -41,12 +39,20 @@ private boolean containsCommonInterstates(Set interstates1, Set return false; } - //Utility function + // Utility function public void printAdjList() { for (Map.Entry> entry : adjList.entrySet()) { - System.out.println("Key: " + entry.getKey().getCity().getCityname() + ", " + entry.getKey().getCity().getState()); + System.out.println( + "Key: " + + entry.getKey().getCity().getCityname() + + ", " + + entry.getKey().getCity().getState()); for (Data connection : entry.getValue()) { - System.out.println("\tValue: " + connection.getCity().getCityname() + ", " + connection.getCity().getState()); + System.out.println( + "\tValue: " + + connection.getCity().getCityname() + + ", " + + connection.getCity().getState()); } System.out.println("\n"); } diff --git a/src/main/java/nitin/zkcura/java8Solution/part2/City.java b/src/main/java/nitin/zkcura/java8Solution/part2/City.java index fa86b34b..60051be9 100644 --- a/src/main/java/nitin/zkcura/java8Solution/part2/City.java +++ b/src/main/java/nitin/zkcura/java8Solution/part2/City.java @@ -1,14 +1,12 @@ package nitin.zkcura.java8Solution.part2; -/** - * Created by Nitin Chaurasia on 11/10/15 at 11:20 PM. - */ +/** Created by Nitin Chaurasia on 11/10/15 at 11:20 PM. */ public class City { private String cityname; private String state; - //Constructor + // Constructor public City(String city, String state) { this.cityname = city; this.state = state; @@ -45,6 +43,7 @@ public boolean equals(Object obj) { // Checking the city names under all the conditions, cities can be in lower case. // If both city name and state name are equal return true } else - return ((City) obj).getCityname().equalsIgnoreCase(cityname) && ((City) obj).getState().equalsIgnoreCase(state); + return ((City) obj).getCityname().equalsIgnoreCase(cityname) + && ((City) obj).getState().equalsIgnoreCase(state); } } diff --git a/src/main/java/nitin/zkcura/java8Solution/part2/Data.java b/src/main/java/nitin/zkcura/java8Solution/part2/Data.java index 725d92d4..5ebd24b8 100644 --- a/src/main/java/nitin/zkcura/java8Solution/part2/Data.java +++ b/src/main/java/nitin/zkcura/java8Solution/part2/Data.java @@ -2,9 +2,7 @@ import java.util.Set; -/** - * Created by Nitin Chaurasia on 11/9/15 at 11:06 PM. - */ +/** Created by Nitin Chaurasia on 11/9/15 at 11:06 PM. */ public class Data { private int population; @@ -12,7 +10,8 @@ public class Data { // City class contains city name and its corresponding state private City city; - // Interstates are already sorted during the time of reading from the file using InterStateComparator order + // Interstates are already sorted during the time of reading from the file using + // InterStateComparator order // (increasing order sort of alphanumeric key). private Set interstates; @@ -33,7 +32,7 @@ public void setCity(City city) { this.city = city; } - //CHANGE : Putting interstates in a Set + // CHANGE : Putting interstates in a Set public Set getInterstates() { return interstates; } @@ -47,8 +46,15 @@ public void setInterstates(Set interstates) { * */ public String toString() { String value = ""; - value = value + population + "\n\n" + city.toString() + "\n" + "Interstates: " + - interstatesToString(getInterstates()) + "\n"; + value = + value + + population + + "\n\n" + + city.toString() + + "\n" + + "Interstates: " + + interstatesToString(getInterstates()) + + "\n"; return value; } @@ -56,8 +62,7 @@ public String toString() { * */ public String aggragateCities() { String value = ""; - value = city.toString() + "\n" + "Interstates: " + - interstatesToString(interstates) + "\n"; + value = city.toString() + "\n" + "Interstates: " + interstatesToString(interstates) + "\n"; return value; } @@ -71,7 +76,6 @@ public String interstatesToString(Set iStates) { return result; } - @Override public boolean equals(Object obj) { @@ -88,6 +92,4 @@ public boolean equals(Object obj) { public int hashCode() { return (city.getCityname() + city.getState()).hashCode(); } - - } diff --git a/src/main/java/nitin/zkcura/java8Solution/part2/Driver.java b/src/main/java/nitin/zkcura/java8Solution/part2/Driver.java index 5d9a18f7..d959e437 100644 --- a/src/main/java/nitin/zkcura/java8Solution/part2/Driver.java +++ b/src/main/java/nitin/zkcura/java8Solution/part2/Driver.java @@ -5,208 +5,206 @@ import java.nio.file.Files; import java.util.*; */ -/** - * Created by nitin on Sunday, October/06/2019 at 10:50 PM - *//* - -public class Driver { - public static final String CITIES_FILE = "Cities_By_Population.txt"; - public static final String CITIES_FILE_REVERSED = "Cities_By_Population.txt"; - public static final String INTERSTATES_FILE = "Interstates_By_City.txt"; - //public static final String FILE_PATH = "src\\main\\java\\com\\nitin\\zkcura\\java8Solution\\"; - public static final String FILE_PATH = "src/main/java/com/nitin/zkcura/java8Solution/"; - - - public static void main(String[] args) { - if (args.length == 0 || args.length > 1) { - System.err.println("Supply a commandline argument \n" + - "Usage: java DriverMain "); - return; - } - - deleteOutputFiles(); - File dataFile = new File(FILE_PATH+args[0]); - // To keep the data of the File into list of Objects of type Data - List list = new ArrayList<>(); - - readDataFromFile(list, dataFile); - writeCitiesByPopulation(list); - // Method to solve Exercise of Option 1, part 2 - writeInterstatesByCity(list); - - //Option2 - printCitiesWithDistanceFromChicago(list); - - System.out.println("Program Terminates Successfully"); - } - - private static void writeInterstatesByCity(List list) { - - FileWriter fw = null; - try { - //Overwrite the File - fw = new FileWriter(FILE_PATH + INTERSTATES_FILE, false); - } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); - } - PrintWriter printToFile = new PrintWriter(fw); - - Iterator itr = list.listIterator(); - - //Map to hold the names of the Interstates and its count - Map interstateCountMap = new TreeMap(); - - while (itr.hasNext()) { - Data curr = itr.next(); - Set temp = curr.getInterstates(); - - for (int i = 0; i < temp.size(); i++) { - String currInterstateName = temp.get(i); - //If the Interstate is not there in the Hashmap - if (!interstateCountMap.containsKey(currInterstateName)) { - interstateCountMap.put(currInterstateName, 1); - } else { - //Increment the count by one - interstateCountMap.put(currInterstateName, interstateCountMap.get(currInterstateName) + 1); - } - } - } - - //There is no direct support for sorting the sets in Java. - // To sort a set, follow these steps: - // Convert set to list. - // Sort list using Collections.sort() API. - // Convert list back to set. - List interstateCountList = new ArrayList<>(interstateCountMap.keySet()); - Collections.sort(interstateCountList, ((String a, String b) - -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); - Iterator itr2 = interstateCountList.iterator(); - - while(itr2.hasNext()){ - String key = itr2.next(); - int value = interstateCountMap.get(key); - printToFile.println(key + " " + value); - } - - printToFile.close(); - System.out.println("Successfully saved data to file: " + FILE_PATH + INTERSTATES_FILE); - } - - private static void writeCitiesByPopulation(List list) { - - // Sort the List of Objects based on the Population - list.sort(Comparator - .comparing(Data::getPopulation).reversed() - .thenComparing(Data::getState) - .thenComparing(Data::getCity)); - - //list.forEach(System.out::println); - FileWriter fw = null; - try { - //Overwrite in the File - fw = new FileWriter(FILE_PATH + CITIES_FILE, false); - } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); - } - PrintWriter printToFile = new PrintWriter(fw); - - // Write the formatted Data into file - Iterator itr = list.listIterator(); - int currentPopulation = -1; - while (itr.hasNext()){ - Data curr = itr.next(); - // Grouping the cities with same population, if the population is same, all cities are clubbed - if (currentPopulation == curr.getPopulation()) { - printToFile.println(curr.aggragateCities()); - } else { - currentPopulation = curr.getPopulation(); - printToFile.println(curr.toString()); - } - } - - printToFile.close();//Should have flushed also - System.out.println("Successfully saved data to file: " + FILE_PATH + CITIES_FILE); - } - - private static void readDataFromFile(List list, File dataFile) { - //Argument has file name.Read the contents of the file and store locally - Scanner input = null; - try { - input = new Scanner(dataFile); - } catch (FileNotFoundException e) { - e.printStackTrace(); - System.exit(-1); - } - - while (input.hasNext()) { - //Split the tokens based on the delimiter "\" - String temp[] = input.nextLine().split("\\|"); - - //Put the tokens into an Object of Data Class and continue making a List of Data Object - Data tempData = new Data(); - - //Population in 100 thousands - tempData.setPopulation(Integer.parseInt(temp[0])); - tempData.setCity(temp[1]); - tempData.setState(temp[2]); - - //Sort the interstates and then put into the Object - List interstateList = Arrays.asList(temp[3].split(";")); - //Sorting the List with interstate number - - interstateList.sort(new Comparator() { - @Override - public int compare(String o1, String o2) { - int interstateNumber1 = Integer.parseInt(o1.substring(2)); - int interstateNumber2 = Integer.parseInt(o2.substring(2)); - - if (interstateNumber1 > interstateNumber2) { - return 1; - } else if (interstateNumber1 < interstateNumber2){ - return -1; - } - else{ - throw new IllegalArgumentException("Two Interstates with same name in a Same City"); - } - } - }); - tempData.setInterstates(interstateList); - - list.add(tempData); - } - } - - */ +/** Created by nitin on Sunday, October/06/2019 at 10:50 PM *//* + + public class Driver { + public static final String CITIES_FILE = "Cities_By_Population.txt"; + public static final String CITIES_FILE_REVERSED = "Cities_By_Population.txt"; + public static final String INTERSTATES_FILE = "Interstates_By_City.txt"; + //public static final String FILE_PATH = "src\\main\\java\\com\\nitin\\zkcura\\java8Solution\\"; + public static final String FILE_PATH = "src/main/java/com/nitin/zkcura/java8Solution/"; + + + public static void main(String[] args) { + if (args.length == 0 || args.length > 1) { + System.err.println("Supply a commandline argument \n" + + "Usage: java DriverMain "); + return; + } + + deleteOutputFiles(); + File dataFile = new File(FILE_PATH+args[0]); + // To keep the data of the File into list of Objects of type Data + List list = new ArrayList<>(); + + readDataFromFile(list, dataFile); + writeCitiesByPopulation(list); + // Method to solve Exercise of Option 1, part 2 + writeInterstatesByCity(list); + + //Option2 + printCitiesWithDistanceFromChicago(list); + + System.out.println("Program Terminates Successfully"); + } + + private static void writeInterstatesByCity(List list) { + + FileWriter fw = null; + try { + //Overwrite the File + fw = new FileWriter(FILE_PATH + INTERSTATES_FILE, false); + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); + } + PrintWriter printToFile = new PrintWriter(fw); + + Iterator itr = list.listIterator(); + + //Map to hold the names of the Interstates and its count + Map interstateCountMap = new TreeMap(); + + while (itr.hasNext()) { + Data curr = itr.next(); + Set temp = curr.getInterstates(); + + for (int i = 0; i < temp.size(); i++) { + String currInterstateName = temp.get(i); + //If the Interstate is not there in the Hashmap + if (!interstateCountMap.containsKey(currInterstateName)) { + interstateCountMap.put(currInterstateName, 1); + } else { + //Increment the count by one + interstateCountMap.put(currInterstateName, interstateCountMap.get(currInterstateName) + 1); + } + } + } + + //There is no direct support for sorting the sets in Java. + // To sort a set, follow these steps: + // Convert set to list. + // Sort list using Collections.sort() API. + // Convert list back to set. + List interstateCountList = new ArrayList<>(interstateCountMap.keySet()); + Collections.sort(interstateCountList, ((String a, String b) + -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2)))); + Iterator itr2 = interstateCountList.iterator(); + + while(itr2.hasNext()){ + String key = itr2.next(); + int value = interstateCountMap.get(key); + printToFile.println(key + " " + value); + } + + printToFile.close(); + System.out.println("Successfully saved data to file: " + FILE_PATH + INTERSTATES_FILE); + } + + private static void writeCitiesByPopulation(List list) { + + // Sort the List of Objects based on the Population + list.sort(Comparator + .comparing(Data::getPopulation).reversed() + .thenComparing(Data::getState) + .thenComparing(Data::getCity)); + + //list.forEach(System.out::println); + FileWriter fw = null; + try { + //Overwrite in the File + fw = new FileWriter(FILE_PATH + CITIES_FILE, false); + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); + } + PrintWriter printToFile = new PrintWriter(fw); + + // Write the formatted Data into file + Iterator itr = list.listIterator(); + int currentPopulation = -1; + while (itr.hasNext()){ + Data curr = itr.next(); + // Grouping the cities with same population, if the population is same, all cities are clubbed + if (currentPopulation == curr.getPopulation()) { + printToFile.println(curr.aggragateCities()); + } else { + currentPopulation = curr.getPopulation(); + printToFile.println(curr.toString()); + } + } + + printToFile.close();//Should have flushed also + System.out.println("Successfully saved data to file: " + FILE_PATH + CITIES_FILE); + } + + private static void readDataFromFile(List list, File dataFile) { + //Argument has file name.Read the contents of the file and store locally + Scanner input = null; + try { + input = new Scanner(dataFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + System.exit(-1); + } + + while (input.hasNext()) { + //Split the tokens based on the delimiter "\" + String temp[] = input.nextLine().split("\\|"); + + //Put the tokens into an Object of Data Class and continue making a List of Data Object + Data tempData = new Data(); + + //Population in 100 thousands + tempData.setPopulation(Integer.parseInt(temp[0])); + tempData.setCity(temp[1]); + tempData.setState(temp[2]); + + //Sort the interstates and then put into the Object + List interstateList = Arrays.asList(temp[3].split(";")); + //Sorting the List with interstate number + + interstateList.sort(new Comparator() { + @Override + public int compare(String o1, String o2) { + int interstateNumber1 = Integer.parseInt(o1.substring(2)); + int interstateNumber2 = Integer.parseInt(o2.substring(2)); + + if (interstateNumber1 > interstateNumber2) { + return 1; + } else if (interstateNumber1 < interstateNumber2){ + return -1; + } + else{ + throw new IllegalArgumentException("Two Interstates with same name in a Same City"); + } + } + }); + tempData.setInterstates(interstateList); + + list.add(tempData); + } + } + + */ /* Utility method to delete the files. * in case of testing it is used *//* - private static void deleteOutputFiles() { - File citiesFile = new File(FILE_PATH + CITIES_FILE); - File interstatesFile = new File(FILE_PATH + INTERSTATES_FILE); - try { - Files.deleteIfExists(citiesFile.toPath()); - Files.deleteIfExists(interstatesFile.toPath()); - } catch (IOException e) { - e.printStackTrace(); - System.err.println("Unable to delete output files."); - } - } - - private static void printCitiesWithDistanceFromChicago(List list) { - CitiesConnection citiesConnection = new CitiesConnection(); - Data chicagoData = null; - for (Data data : list) { - citiesConnection.addNewCity(data); - if (data.getCity().equals(new City("Chicago", "Illinois"))) { - chicagoData = data; - } - } - //citiesConnection.printAdjList(); - BredthFirstTraversal traversal = new BredthFirstTraversal(); - traversal.traverseGraph(citiesConnection.getAdjList(), chicagoData); - traversal.printList(); - } -} -*/ + private static void deleteOutputFiles() { + File citiesFile = new File(FILE_PATH + CITIES_FILE); + File interstatesFile = new File(FILE_PATH + INTERSTATES_FILE); + try { + Files.deleteIfExists(citiesFile.toPath()); + Files.deleteIfExists(interstatesFile.toPath()); + } catch (IOException e) { + e.printStackTrace(); + System.err.println("Unable to delete output files."); + } + } + + private static void printCitiesWithDistanceFromChicago(List list) { + CitiesConnection citiesConnection = new CitiesConnection(); + Data chicagoData = null; + for (Data data : list) { + citiesConnection.addNewCity(data); + if (data.getCity().equals(new City("Chicago", "Illinois"))) { + chicagoData = data; + } + } + //citiesConnection.printAdjList(); + BredthFirstTraversal traversal = new BredthFirstTraversal(); + traversal.traverseGraph(citiesConnection.getAdjList(), chicagoData); + traversal.printList(); + } + } + */ diff --git a/src/main/java/nitin/zkcura/oldSolution/part1/Data.java b/src/main/java/nitin/zkcura/oldSolution/part1/Data.java index 317cedcf..bf2245c3 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part1/Data.java +++ b/src/main/java/nitin/zkcura/oldSolution/part1/Data.java @@ -2,15 +2,14 @@ import java.util.List; -/** - * Created by Nitin Chaurasia on 11/9/15 at 11:06 PM. - */ +/** Created by Nitin Chaurasia on 11/9/15 at 11:06 PM. */ public class Data { private int population; private String city; private String state; - // Interstates are already sorted during the time of reading from the file using Default Sorting order. + // Interstates are already sorted during the time of reading from the file using Default Sorting + // order. private List interstates; // Accessors and Mutators for the private data members @@ -53,8 +52,17 @@ public void setInterstates(List interstates) { * */ public String toString() { String value = ""; - value = value + population + "\n\n" + city + ", " + state + "\n" + "Interstates: " + - interstatesToString(getInterstates()) + "\n"; + value = + value + + population + + "\n\n" + + city + + ", " + + state + + "\n" + + "Interstates: " + + interstatesToString(getInterstates()) + + "\n"; return value; } @@ -63,12 +71,17 @@ public String toString() { * */ public String aggragateCities() { String value = ""; - value = city + ", " + state + "\n" + "Interstates: " + - interstatesToString(interstates) + "\n"; + value = + city + + ", " + + state + + "\n" + + "Interstates: " + + interstatesToString(interstates) + + "\n"; return value; } - /* Method to Print List of Interstates in the required format */ public String interstatesToString(List iStates) { @@ -82,5 +95,4 @@ public String interstatesToString(List iStates) { return result; } - } diff --git a/src/main/java/nitin/zkcura/oldSolution/part1/Driver.java b/src/main/java/nitin/zkcura/oldSolution/part1/Driver.java index cdc1b1f9..071ee7a3 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part1/Driver.java +++ b/src/main/java/nitin/zkcura/oldSolution/part1/Driver.java @@ -6,14 +6,12 @@ /** * Created by Nitin Chaurasia on 11/9/15 at 3:43 PM as a part of the kCura interview process. - *

- * The data is present in a file the name of which is expected as a command line argument. - * If the file name is not given, the program terminates giving an error - * NOTE: The Data is assumed to be in a predefined format, thus the check for the - * correctness and formatting of data is avoided here. + * + *

The data is present in a file the name of which is expected as a command line argument. If the + * file name is not given, the program terminates giving an error NOTE: The Data is assumed to be in + * a predefined format, thus the check for the correctness and formatting of data is avoided here. */ - /* * Main Class that runs the project * Arguments to the main function is a name of the file containing data in pipe delimited format @@ -34,7 +32,7 @@ public static void main(String[] args) { // fileName contains the name of the file containing initial Data. String fileName = args[0]; - //Read the contents of the file and store locally + // Read the contents of the file and store locally File dataFile = new File(fileName); Scanner input = null; try { @@ -48,24 +46,24 @@ public static void main(String[] args) { List list = new ArrayList(); /* Read from the File, assuming the file is properly sanitized - The contents are put in the form of objects of type Data into a - List. - */ + The contents are put in the form of objects of type Data into a + List. + */ while (input.hasNext()) { - //Split the tokens based on the delimiter "\" + // Split the tokens based on the delimiter "\" String[] temp = input.nextLine().split("\\|"); - //Put the tokens into an Object of Data Class and continue making a List of Data Object + // Put the tokens into an Object of Data Class and continue making a List of Data Object Data tempData = new Data(); - //Population in 100 thousands + // Population in 100 thousands tempData.setPopulation(Integer.parseInt(temp[0])); tempData.setCity(temp[1]); tempData.setState(temp[2]); // Make a list of Interstates and Sort them for the convinience. String[] interstates = temp[3].split(";"); - //Sort the interstates and then put into the Object + // Sort the interstates and then put into the Object tempData.setInterstates(driver.sortInterstates(interstates)); list.add(tempData); @@ -94,16 +92,15 @@ public void deleteOutputFiles() { } } - /** - * Solving First Part of Option 1 in which data is written in a file named Cities_By_Population.txt - * In a specified format with a customized sorting order. + * Solving First Part of Option 1 in which data is written in a file named + * Cities_By_Population.txt In a specified format with a customized sorting order. */ public void writeCitiesByPopulation(List list) { FileWriter fw = null; try { - //Overwrite in the File + // Overwrite in the File fw = new FileWriter(CITIES_FILE, false); } catch (IOException e) { e.printStackTrace(); @@ -119,7 +116,8 @@ public void writeCitiesByPopulation(List list) { int currentPopulation = -1; while (itr.hasNext()) { Data curr = itr.next(); - // Grouping the cities with same population, if the population is same, all cities are clubbed + // Grouping the cities with same population, if the population is same, all cities are + // clubbed if (currentPopulation == curr.getPopulation()) { printToFile.println(curr.aggragateCities()); } else { @@ -128,19 +126,19 @@ public void writeCitiesByPopulation(List list) { } } - printToFile.close();//Should have flushed also + printToFile.close(); // Should have flushed also System.out.println("Successfully saved data to file: " + CITIES_FILE); } /** - * Solving Second Part of Option 1 in which the count of Interstates is to be written in a - * file named Interstates_By_City.txt. The Interstates name will be in the Ascending order + * Solving Second Part of Option 1 in which the count of Interstates is to be written in a file + * named Interstates_By_City.txt. The Interstates name will be in the Ascending order */ private void writeInterstatesByCity(List list) { FileWriter fw = null; try { - //Overwrite the File + // Overwrite the File fw = new FileWriter(INTERSTATES_FILE, false); } catch (IOException e) { e.printStackTrace(); @@ -150,7 +148,7 @@ private void writeInterstatesByCity(List list) { Iterator itr = list.listIterator(); - //Map to hold the names of the Interstates and its count + // Map to hold the names of the Interstates and its count Map interstateCount = new TreeMap(); while (itr.hasNext()) { @@ -159,12 +157,13 @@ private void writeInterstatesByCity(List list) { for (int i = 0; i < temp.size(); i++) { String currInterstateName = temp.get(i); - //If the Interstate is not there in the Hashmap + // If the Interstate is not there in the Hashmap if (!interstateCount.containsKey(currInterstateName)) { interstateCount.put(currInterstateName, 1); } else { - //Increment the count by one - interstateCount.put(currInterstateName, interstateCount.get(currInterstateName) + 1); + // Increment the count by one + interstateCount.put( + currInterstateName, interstateCount.get(currInterstateName) + 1); } } } @@ -174,10 +173,9 @@ private void writeInterstatesByCity(List list) { AllInterstatesSorted.add(key); } - //Keep a sorted list of Interstates to get the matching values from the Map + // Keep a sorted list of Interstates to get the matching values from the Map Collections.sort(AllInterstatesSorted, new InterstateComparator()); - // Writing Interstates names and its count into the file for (int i = 0; i < AllInterstatesSorted.size(); i++) { String key = AllInterstatesSorted.get(i); @@ -189,13 +187,11 @@ private void writeInterstatesByCity(List list) { System.out.println("Successfully saved data to file: " + INTERSTATES_FILE); } - //Method to Sort the Interstates + // Method to Sort the Interstates private List sortInterstates(String[] interstates) { List temp = Arrays.asList(interstates); Collections.sort(temp, new InterstateComparator()); return temp; } - } - diff --git a/src/main/java/nitin/zkcura/oldSolution/part1/InterstateComparator.java b/src/main/java/nitin/zkcura/oldSolution/part1/InterstateComparator.java index 21a5b9b0..49e90b7d 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part1/InterstateComparator.java +++ b/src/main/java/nitin/zkcura/oldSolution/part1/InterstateComparator.java @@ -4,11 +4,10 @@ /** * Created by Nitin Chaurasia on 11/10/15. - *

- * Based on the Assumption given in the Exercise, The same city will not - * appear more than once in the input file and thus it can safely be deduced that - * The total number of times an interstate name appears in the input file is equal to - * the total number of different cities is passes through + * + *

Based on the Assumption given in the Exercise, The same city will not appear more than once in + * the input file and thus it can safely be deduced that The total number of times an interstate + * name appears in the input file is equal to the total number of different cities is passes through */ public class InterstateComparator implements Comparator { @@ -21,9 +20,9 @@ public class InterstateComparator implements Comparator { @Override public int compare(String obj1, String obj2) { - //Take the number out of the String for comparison + // Take the number out of the String for comparison - //Based on the exercise, all Interstates will begin with prefix I- + // Based on the exercise, all Interstates will begin with prefix I- // Taking out the integer from name e.g I-25 will give 25 int num1 = Integer.parseInt(obj1.substring("I-".length())); int num2 = Integer.parseInt(obj2.substring("I-".length())); diff --git a/src/main/java/nitin/zkcura/oldSolution/part1/PopulationComparator.java b/src/main/java/nitin/zkcura/oldSolution/part1/PopulationComparator.java index 8c8f082c..760b1545 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part1/PopulationComparator.java +++ b/src/main/java/nitin/zkcura/oldSolution/part1/PopulationComparator.java @@ -4,11 +4,10 @@ /** * Created by Nitin Chaurasia on 11/10/15 - *

- * Sort the List of Objects based on the Population - * If there is a tie in the Population, Sorting is performed - * first by the alphabetical order of the States and - * the by the alphabetical order of the Cities + * + *

Sort the List of Objects based on the Population If there is a tie in the Population, Sorting + * is performed first by the alphabetical order of the States and the by the alphabetical order of + * the Cities */ public class PopulationComparator implements Comparator { @@ -21,7 +20,7 @@ public int compare(Data obj1, Data obj2) { if (obj1 == obj2) { return EQUAL; } else if (obj1.getPopulation() < obj2.getPopulation()) { - //Reverse Sorting as per the requirement + // Reverse Sorting as per the requirement return BIGGER; } else if (obj1.getPopulation() == obj2.getPopulation()) { return compareStates(obj1, obj2); @@ -30,7 +29,6 @@ public int compare(Data obj1, Data obj2) { } } - // Sorting based on alphabetical order of States (iff population is Same) private int compareStates(Data obj1, Data obj2) { if (obj1.getState().compareTo(obj2.getState()) > 0) { @@ -49,8 +47,10 @@ private int compareCities(Data obj1, Data obj2) { } else if (obj1.getCity().compareTo(obj2.getCity()) < 0) { return SMALLER; } else { - // We will never meet this condition since as per assumptions, the input file will not contain same cities - throw new IllegalArgumentException("Both Cities are same: " + obj1.getCity() + ", " + obj2.getCity()); + // We will never meet this condition since as per assumptions, the input file will not + // contain same cities + throw new IllegalArgumentException( + "Both Cities are same: " + obj1.getCity() + ", " + obj2.getCity()); } } } diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/BredthFirstTraversal.java b/src/main/java/nitin/zkcura/oldSolution/part2/BredthFirstTraversal.java index b579e099..95d148b6 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/BredthFirstTraversal.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/BredthFirstTraversal.java @@ -1,11 +1,8 @@ package nitin.zkcura.oldSolution.part2; - import java.util.*; -/** - * Created by Nitin Chaurasia on 11/10/15 at 10:05 PM. - */ +/** Created by Nitin Chaurasia on 11/10/15 at 10:05 PM. */ public class BredthFirstTraversal { private final Set visited = new HashSet(); private final Queue inline = new LinkedList(); diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/CitiesConnection.java b/src/main/java/nitin/zkcura/oldSolution/part2/CitiesConnection.java index 6712ad66..314c7750 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/CitiesConnection.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/CitiesConnection.java @@ -5,9 +5,7 @@ import java.util.Map; import java.util.Set; -/** - * Created by Nitin Chaurasia on 11/10/15 at 9:53 PM. - */ +/** Created by Nitin Chaurasia on 11/10/15 at 9:53 PM. */ public class CitiesConnection { private final Map> adjList = new HashMap>(); @@ -41,12 +39,14 @@ private boolean containsCommonInterstates(Set interstates1, Set return false; } - //Utility function + // Utility function public void printAdjList() { for (Map.Entry> entry : adjList.entrySet()) { - //System.out.println("Key: " + entry.getKey().getCity().getCityname() + ", " + entry.getKey().getCity().getState()); + // System.out.println("Key: " + entry.getKey().getCity().getCityname() + ", " + + // entry.getKey().getCity().getState()); for (Data connection : entry.getValue()) { - //System.out.println("\tValue: " + connection.getCity().getCityname() + ", " + connection.getCity().getState()); + // System.out.println("\tValue: " + connection.getCity().getCityname() + ", " + + // connection.getCity().getState()); } System.out.println("\n"); } diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/City.java b/src/main/java/nitin/zkcura/oldSolution/part2/City.java index d0f19d1e..ae78fb3d 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/City.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/City.java @@ -1,14 +1,12 @@ package nitin.zkcura.oldSolution.part2; -/** - * Created by Nitin Chaurasia on 11/10/15 at 11:20 PM. - */ +/** Created by Nitin Chaurasia on 11/10/15 at 11:20 PM. */ public class City { private String cityname; private String state; - //Constructor + // Constructor public City(String city, String state) { this.cityname = city; this.state = state; @@ -45,6 +43,7 @@ public boolean equals(Object obj) { // Checking the city names under all the conditions, cities can be in lower case. // If both city name and state name are equal return true } else - return ((City) obj).getCityname().equalsIgnoreCase(cityname) && ((City) obj).getState().equalsIgnoreCase(state); + return ((City) obj).getCityname().equalsIgnoreCase(cityname) + && ((City) obj).getState().equalsIgnoreCase(state); } } diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/Data.java b/src/main/java/nitin/zkcura/oldSolution/part2/Data.java index fe5135c6..35f4c30c 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/Data.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/Data.java @@ -2,9 +2,7 @@ import java.util.Set; -/** - * Created by Nitin Chaurasia on 11/9/15 at 11:06 PM. - */ +/** Created by Nitin Chaurasia on 11/9/15 at 11:06 PM. */ public class Data { private int population; @@ -12,7 +10,8 @@ public class Data { // City class contains city name and its corresponding state private City city; - // Interstates are already sorted during the time of reading from the file using InterStateComparator order + // Interstates are already sorted during the time of reading from the file using + // InterStateComparator order // (increasing order sort of alphanumeric key). private Set interstates; @@ -33,7 +32,7 @@ public void setCity(City city) { this.city = city; } - //CHANGE : Putting interstates in a Set + // CHANGE : Putting interstates in a Set public Set getInterstates() { return interstates; } @@ -47,8 +46,15 @@ public void setInterstates(Set interstates) { * */ public String toString() { String value = ""; - value = value + population + "\n\n" + city.toString() + "\n" + "Interstates: " + - interstatesToString(getInterstates()) + "\n"; + value = + value + + population + + "\n\n" + + city.toString() + + "\n" + + "Interstates: " + + interstatesToString(getInterstates()) + + "\n"; return value; } @@ -56,8 +62,7 @@ public String toString() { * */ public String aggragateCities() { String value = ""; - value = city.toString() + "\n" + "Interstates: " + - interstatesToString(interstates) + "\n"; + value = city.toString() + "\n" + "Interstates: " + interstatesToString(interstates) + "\n"; return value; } @@ -71,7 +76,6 @@ public String interstatesToString(Set iStates) { return result; } - @Override public boolean equals(Object obj) { @@ -88,6 +92,4 @@ public boolean equals(Object obj) { public int hashCode() { return (city.getCityname() + city.getState()).hashCode(); } - - } diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/Driver.java b/src/main/java/nitin/zkcura/oldSolution/part2/Driver.java index 24c1250e..96583a2c 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/Driver.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/Driver.java @@ -10,7 +10,8 @@ public class Driver { public static final String CITIES_FILE = "Cities_By_Population.txt"; public static final String INTERSTATES_FILE = "Interstates_By_City.txt"; public static final String CITIES_FILE_REVERSED = "Cities_By_Population.txt"; - //public static final String FILE_PATH = "src\\main\\java\\com\\nitin\\zkcura\\java8Solution\\"; + // public static final String FILE_PATH = + // "src\\main\\java\\com\\nitin\\zkcura\\java8Solution\\"; public static final String FILE_PATH = "src/main/java/com/nitin/zkcura/oldSolution/part2/"; public static void main(String[] args) { @@ -23,10 +24,10 @@ public static void main(String[] args) { // fileName contains the name of the file containing initial Data. String fileName = args[0]; - //Read the contents of the file and store locally + // Read the contents of the file and store locally File dataFile = new File(FILE_PATH + fileName); - //Read the File + // Read the File Scanner input = null; try { input = new Scanner(dataFile); @@ -38,22 +39,22 @@ public static void main(String[] args) { // To keep the data of the File into list of Objects List list = new ArrayList(); - //Read from the File, assuming the file is properly sanitized + // Read from the File, assuming the file is properly sanitized while (input.hasNext()) { - //Split the tokens based on the delimiter "\" + // Split the tokens based on the delimiter "\" String[] temp = input.nextLine().split("\\|"); - //Put the tokens into an Object of Data Class and continue making a List of Data Object + // Put the tokens into an Object of Data Class and continue making a List of Data Object Data tempData = new Data(); - //Population in 100 thousands + // Population in 100 thousands tempData.setPopulation(Integer.parseInt(temp[0])); tempData.setCity(new City(temp[1], temp[2])); // Make a list of Interstates and Sort them for the convinience. String[] interstates = temp[3].split(";"); - //Sort the interstates and then put into the Object + // Sort the interstates and then put into the Object Set istates = new HashSet(); Collections.addAll(istates, interstates); tempData.setInterstates(istates); @@ -61,7 +62,7 @@ public static void main(String[] args) { list.add(tempData); } - //Option2 + // Option2 driver.printCitiesWithDistanceFromChicago(list); System.out.println("Program Terminates Successfully"); @@ -76,7 +77,7 @@ private void printCitiesWithDistanceFromChicago(List list) { chicagoData = data; } } - //citiesConnection.printAdjList(); + // citiesConnection.printAdjList(); BredthFirstTraversal traversal = new BredthFirstTraversal(); traversal.traverseGraph(citiesConnection.getAdjList(), chicagoData); traversal.printList(); @@ -97,7 +98,7 @@ public void deleteOutputFiles() { } } - //Method to Sort the Interstates + // Method to Sort the Interstates private List sortInterstates(String[] interstates) { List temp = Arrays.asList(interstates); Collections.sort(temp, new InterstateComparator()); @@ -105,4 +106,3 @@ private List sortInterstates(String[] interstates) { return temp; } } - diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/InterstateComparator.java b/src/main/java/nitin/zkcura/oldSolution/part2/InterstateComparator.java index e2d63220..77de65fe 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/InterstateComparator.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/InterstateComparator.java @@ -4,11 +4,10 @@ /** * Created by Nitin Chaurasia on 11/10/15. - *

- * Based on the Assumption given in the Exercise, The same city will not - * appear more than once in the input file and thus it can safely be deduced that - * The total nmver of times an interstate name appears in the input file is equal to - * the total number of different cities is passes through + * + *

Based on the Assumption given in the Exercise, The same city will not appear more than once in + * the input file and thus it can safely be deduced that The total nmver of times an interstate name + * appears in the input file is equal to the total number of different cities is passes through */ public class InterstateComparator implements Comparator { @@ -21,9 +20,9 @@ public class InterstateComparator implements Comparator { @Override public int compare(String obj1, String obj2) { - //Take the number out of the String for comparison + // Take the number out of the String for comparison - //Based on the exercise, all Interstates will begin with prefix I- + // Based on the exercise, all Interstates will begin with prefix I- // Taking out the integer from name e.g I-25 will give 25 int num1 = Integer.parseInt(obj1.substring("I-".length())); int num2 = Integer.parseInt(obj2.substring("I-".length())); diff --git a/src/main/java/nitin/zkcura/oldSolution/part2/PopulationComparator.java b/src/main/java/nitin/zkcura/oldSolution/part2/PopulationComparator.java index 44dc1251..f88d90b7 100644 --- a/src/main/java/nitin/zkcura/oldSolution/part2/PopulationComparator.java +++ b/src/main/java/nitin/zkcura/oldSolution/part2/PopulationComparator.java @@ -4,11 +4,10 @@ /** * Created by Nitin Chaurasia on 11/10/15 - *

- * Sort the List of Objects based on the Population - * If there is a tie in the Population, Sorting is performed - * first by the alphabetical order of the States and - * the by the alphabetical order of the Cities + * + *

Sort the List of Objects based on the Population If there is a tie in the Population, Sorting + * is performed first by the alphabetical order of the States and the by the alphabetical order of + * the Cities */ public class PopulationComparator implements Comparator { @@ -21,7 +20,7 @@ public int compare(Data obj1, Data obj2) { if (obj1 == obj2) { return EQUAL; } else if (obj1.getPopulation() < obj2.getPopulation()) { - //Reverse Sorting as per the requirement + // Reverse Sorting as per the requirement return BIGGER; } else if (obj1.getPopulation() == obj2.getPopulation()) { return compareStates(obj1.getCity(), obj2.getCity()); @@ -30,7 +29,6 @@ public int compare(Data obj1, Data obj2) { } } - // Sorting based on alphabetical order of States (iff population is Same) private int compareStates(City obj1, City obj2) { if (obj1.getState().compareTo(obj2.getState()) > 0) { @@ -49,8 +47,10 @@ private int compareCities(City obj1, City obj2) { } else if (obj1.getCityname().compareTo(obj2.getCityname()) < 0) { return SMALLER; } else { - // We will never meet this condition since as per assumptions, the input file will not contain same cities - throw new IllegalArgumentException("Both Cities are same: " + obj1.getCityname() + ", " + obj2.getCityname()); + // We will never meet this condition since as per assumptions, the input file will not + // contain same cities + throw new IllegalArgumentException( + "Both Cities are same: " + obj1.getCityname() + ", " + obj2.getCityname()); } } } diff --git a/src/main/java/sandbox/ApostrophyIssue.java b/src/main/java/sandbox/ApostrophyIssue.java index 80166a71..93362282 100644 --- a/src/main/java/sandbox/ApostrophyIssue.java +++ b/src/main/java/sandbox/ApostrophyIssue.java @@ -4,8 +4,10 @@ public class ApostrophyIssue { public static void main(String[] args) { - //String selectedRad = "onClick='setSelectedValue(\""+ returnPaymentId + delimiterS + vendorId + delimiterS + eaReturnSummaryCargo.getRequestedBy()+"\")'"; - //String selectedRad = "onClick='setSelectedValue(\""+ returnPaymentId + delimiterS + vendorId + delimiterS + "Eutsler's" +"\")'"; + // String selectedRad = "onClick='setSelectedValue(\""+ returnPaymentId + delimiterS + + // vendorId + delimiterS + eaReturnSummaryCargo.getRequestedBy()+"\")'"; + // String selectedRad = "onClick='setSelectedValue(\""+ returnPaymentId + delimiterS + + // vendorId + delimiterS + "Eutsler's" +"\")'"; int var1 = 123; String var2 = "Testing's"; @@ -14,10 +16,11 @@ public static void main(String[] args) { StringUtils.replace(var2, "'", "’"); String selectedRad = "onClick='setSelectedValue(\"" + var1 + delimiterS + var2 + "\")'"; - String selectedRadWithApostropy = "onClick='setSelectedValue(\"" + var1 + delimiterS + "Eutsler's" + "\")'"; + String selectedRadWithApostropy = + "onClick='setSelectedValue(\"" + var1 + delimiterS + "Eutsler's" + "\")'"; System.out.println(selectedRad); System.out.println(selectedRadWithApostropy); } -} \ No newline at end of file +} diff --git a/src/main/java/sandbox/AsyncFuture.java b/src/main/java/sandbox/AsyncFuture.java index 83ca873e..92bdeb99 100644 --- a/src/main/java/sandbox/AsyncFuture.java +++ b/src/main/java/sandbox/AsyncFuture.java @@ -5,14 +5,13 @@ public class AsyncFuture { public static void main(String[] args) { - int[] factor = new int[]{2}; + int[] factor = new int[] {2}; var numbers = List.of(1, 2, 3); - var stream = numbers.stream() - .map(number -> number*factor[0]); + var stream = numbers.stream().map(number -> number * factor[0]); factor[0] = 0; - stream.forEach(System.out::println);//Evaluates here + stream.forEach(System.out::println); // Evaluates here } } diff --git a/src/main/java/sandbox/LogDemo.java b/src/main/java/sandbox/LogDemo.java index 4ecb29ab..1344d2f9 100644 --- a/src/main/java/sandbox/LogDemo.java +++ b/src/main/java/sandbox/LogDemo.java @@ -1,14 +1,11 @@ package sandbox; /** - * @author Created by nichaurasia - * Created on Sunday, December/20/2020 at 8:38 AM + * @author Created by nichaurasia Created on Sunday, December/20/2020 at 8:38 AM */ - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - public class LogDemo { private static final Log logger = LogFactory.getLog(LogDemo.class); diff --git a/src/main/java/sandbox/ParseMentorBox.java b/src/main/java/sandbox/ParseMentorBox.java index 2e5f2feb..d69bc644 100644 --- a/src/main/java/sandbox/ParseMentorBox.java +++ b/src/main/java/sandbox/ParseMentorBox.java @@ -5,19 +5,18 @@ import java.io.PrintWriter; import java.util.Scanner; -/** - * Created by Nitin Chaurasia on 2/15/18 at 8:47 PM. - */ +/** Created by Nitin Chaurasia on 2/15/18 at 8:47 PM. */ public class ParseMentorBox { public static void main(String[] args) { System.out.println("Hello"); - final String O_FILENAME = "/Users/nitin/OneDrive/Programming/Java/IntelliJ/output_mentorBox.txt"; + final String O_FILENAME = + "/Users/nitin/OneDrive/Programming/Java/IntelliJ/output_mentorBox.txt"; final String IN_FILENAME = "/Users/nitin/OneDrive/Programming/Java/IntelliJ/mentorBox.html"; final String searchTitle = "

"; final String searchSubTitle = "
"; - //Open the File + // Open the File File myFile = new File(IN_FILENAME); Scanner in = null; try { @@ -25,10 +24,10 @@ public static void main(String[] args) { } catch (FileNotFoundException e) { e.printStackTrace(); } - //Instead of System.in, take the file to read + // Instead of System.in, take the file to read // Output File - //Surrounding with try catch!! + // Surrounding with try catch!! PrintWriter output = null; try { output = new PrintWriter(O_FILENAME); @@ -57,7 +56,7 @@ public static void main(String[] args) { System.out.println("Total Titles found : " + titleCount); System.out.println("Total Subtitles found : " + subTitleCount); - //Close the File + // Close the File in.close(); output.close(); } diff --git a/src/main/java/sandbox/ParseMentorBoxLecture.java b/src/main/java/sandbox/ParseMentorBoxLecture.java index 559c7f69..d266754b 100644 --- a/src/main/java/sandbox/ParseMentorBoxLecture.java +++ b/src/main/java/sandbox/ParseMentorBoxLecture.java @@ -7,21 +7,20 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Created by Nitin Chaurasia on 2/15/18 at 8:47 PM. - */ +/** Created by Nitin Chaurasia on 2/15/18 at 8:47 PM. */ public class ParseMentorBoxLecture { public static void main(String[] args) { System.out.println("Hello"); - final String O_FILENAME = "/Users/nitin/OneDrive/Programming/Java/IntelliJ/mentorBox_lecture.txt"; - final String IN_FILENAME = "/Users/nitin/OneDrive/Programming/Java/IntelliJ/mentorBox_lecture.html"; + final String O_FILENAME = + "/Users/nitin/OneDrive/Programming/Java/IntelliJ/mentorBox_lecture.txt"; + final String IN_FILENAME = + "/Users/nitin/OneDrive/Programming/Java/IntelliJ/mentorBox_lecture.html"; final String searchTitle = " idList = Arrays.asList("00693", "12345", "11016", null, "00693"); - //Removing duplicates as Map cannot have 2 identical keys - idList = idList - .stream() - .distinct() - .collect(Collectors.toList()); + // Removing duplicates as Map cannot have 2 identical keys + idList = idList.stream().distinct().collect(Collectors.toList()); - //Removing nulls + // Removing nulls idList.removeIf(element -> element == null); Map idToIdMap = UuidUtils.getIdToIdMap(idList); diff --git a/src/main/java/sandbox/ZPatternExampleDito.java b/src/main/java/sandbox/ZPatternExampleDito.java index c9bfd2b3..465e6c5f 100644 --- a/src/main/java/sandbox/ZPatternExampleDito.java +++ b/src/main/java/sandbox/ZPatternExampleDito.java @@ -26,4 +26,3 @@ public static void main(String[] args) throws Exception { DitoDocumentBuilder.buildDocument(documentNode, new FileOutputStream("z_pattern_output.pdf")); } }*/ - diff --git a/src/main/resources/json/array-object-mapper.json b/src/main/resources/json/array-object-mapper.json index 9cd8b5c0..1efacf6a 100644 --- a/src/main/resources/json/array-object-mapper.json +++ b/src/main/resources/json/array-object-mapper.json @@ -1,58 +1,58 @@ [ - { - "name": "John Doe", - "dateOfBirth": 1676878272857, - "phones": { - "Work": "(123) 456 7890", - "Cell": "987-654-3210", - "Home": "963-852-7410" + { + "addresses": [ + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": "37027", + "city": "Brentwood", + "addressLine1": "134 Plum Nelly Circle", + "addressLine2": null, + "state": "TN" + } + ], + "name": "John Doe", + "phones": { + "Work": "(123) 456 7890", + "Cell": "987-654-3210", + "Home": "963-852-7410" + }, + "dateOfBirth": 1676878272857 }, - "addresses": [ - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": "134 Plum Nelly Circle", - "addressLine2": null, - "city": "Brentwood", - "state": "TN", - "zip": "37027" - } - ] - }, - { - "name": "Jane Doe", - "dateOfBirth": 1676878272857, - "phones": { - "Cell": "987-654-3210", - "Home": "963 852 7410" - }, - "addresses": [ - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": "209 Club Pkwy", - "addressLine2": null, - "city": "Nashville", - "state": "TN", - "zip": "37221" - } - ] - } + { + "addresses": [ + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": "37221", + "city": "Nashville", + "addressLine1": "209 Club Pkwy", + "addressLine2": null, + "state": "TN" + } + ], + "name": "Jane Doe", + "phones": { + "Cell": "987-654-3210", + "Home": "963 852 7410" + }, + "dateOfBirth": 1676878272857 + } ] diff --git a/src/main/resources/json/groupingBy.json b/src/main/resources/json/groupingBy.json index e64161f9..1bfdc287 100644 --- a/src/main/resources/json/groupingBy.json +++ b/src/main/resources/json/groupingBy.json @@ -1,587 +1,587 @@ [ - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2024-03-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2024-02-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2024-01-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-12-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-11-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-10-20T09:49:08Z", - "value": "24.8", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-09-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-08-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-07-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-06-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-05-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-04-19T14:50:00Z", - "value": "21.9", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "8191", - "name": "VITAMIN D (25-OH)", - "uom": " (ng/mL)", - "dateTime": "2023-03-01T00:00:00Z", - "value": "", - "sortOrder": 37 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2024-03-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2024-02-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2024-01-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-12-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-11-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-10-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-09-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-08-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-07-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-06-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-05-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-04-19T14:50:00Z", - "value": "3.6", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "1162", - "name": "MAGNESIUM", - "uom": " (mg/dL)", - "dateTime": "2023-03-01T00:00:00Z", - "value": "", - "sortOrder": 38 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2024-03-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2024-02-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2024-01-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-12-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-11-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-10-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-09-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-08-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-07-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-06-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-05-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-04-19T14:50:00Z", - "value": "10", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "8488", - "name": "ALUMINUM - BLOOD", - "uom": " (ug/L)", - "dateTime": "2023-03-01T00:00:00Z", - "value": "", - "sortOrder": 39 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2024-03-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2024-02-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2024-01-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-12-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-11-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-10-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-09-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-08-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-07-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-06-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-05-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-04-19T14:50:00Z", - "value": "14", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6137", - "name": "FOLIC ACID", - "uom": " (ng/mL)", - "dateTime": "2023-03-01T00:00:00Z", - "value": "", - "sortOrder": 40 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2024-03-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2024-02-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2024-01-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-12-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-11-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-10-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-09-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-08-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-07-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-06-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-05-01T00:00:00Z", - "value": "", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-04-19T14:50:00Z", - "value": "686", - "sortOrder": 41 - }, - { - "categoryName": "Additional", - "testCodeId": "6188", - "name": "VITAMIN B-12", - "uom": " (pg/mL)", - "dateTime": "2023-03-01T00:00:00Z", - "value": "", - "sortOrder": 41 - } -] \ No newline at end of file + { + "dateTime": "2024-03-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-02-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-01-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-12-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-11-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-10-20T09:49:08Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "24.8" + }, + { + "dateTime": "2023-09-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-08-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-07-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-06-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-05-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-04-19T14:50:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "21.9" + }, + { + "dateTime": "2023-03-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 37, + "name": "VITAMIN D (25-OH)", + "testCodeId": "8191", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-03-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-02-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-01-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-12-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-11-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-10-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-09-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-08-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-07-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-06-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-05-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-04-19T14:50:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "3.6" + }, + { + "dateTime": "2023-03-01T00:00:00Z", + "uom": " (mg/dL)", + "sortOrder": 38, + "name": "MAGNESIUM", + "testCodeId": "1162", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-03-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-02-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-01-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-12-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-11-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-10-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-09-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-08-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-07-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-06-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-05-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-04-19T14:50:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "10" + }, + { + "dateTime": "2023-03-01T00:00:00Z", + "uom": " (ug/L)", + "sortOrder": 39, + "name": "ALUMINUM - BLOOD", + "testCodeId": "8488", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-03-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-02-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-01-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-12-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-11-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-10-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-09-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-08-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-07-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-06-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-05-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-04-19T14:50:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "14" + }, + { + "dateTime": "2023-03-01T00:00:00Z", + "uom": " (ng/mL)", + "sortOrder": 40, + "name": "FOLIC ACID", + "testCodeId": "6137", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-03-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-02-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2024-01-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-12-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-11-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-10-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-09-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-08-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-07-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-06-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-05-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + }, + { + "dateTime": "2023-04-19T14:50:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "686" + }, + { + "dateTime": "2023-03-01T00:00:00Z", + "uom": " (pg/mL)", + "sortOrder": 41, + "name": "VITAMIN B-12", + "testCodeId": "6188", + "categoryName": "Additional", + "value": "" + } +] diff --git a/src/main/resources/json/groups.json b/src/main/resources/json/groups.json index a9a679f6..e68bd13e 100644 --- a/src/main/resources/json/groups.json +++ b/src/main/resources/json/groups.json @@ -1,135 +1,135 @@ [ - { - "groupName": "Hematology", - "code": "1730", - "name": "Hemoglobin", - "dateTime": "2023-12-01T08:00:00", - "value": "5" - }, - { - "groupName": "Hematology", - "code": "2845", - "name": "Platelet Count", - "dateTime": "2023-12-05T10:30:00", - "value": "240000" - }, - { - "groupName": "Hematology", - "code": "2990", - "name": "White Blood Cell Count", - "dateTime": "2023-12-10T12:45:00", - "value": "8000" - }, - { - "groupName": "Hematology", - "code": "1850", - "name": "Red Blood Cell Count", - "dateTime": "2023-12-15T14:00:00", - "value": "4.5" - }, - { - "groupName": "Hematology", - "code": "1987", - "name": "Mean Corpuscular Volume", - "dateTime": "2023-12-20T16:15:00", - "value": "90" - }, - { - "groupName": "Cardiology", - "code": "1201", - "name": "Heart Rate", - "dateTime": "2023-12-25T18:30:00", - "value": "75" - }, - { - "groupName": "Cardiology", - "code": "1300", - "name": "Blood Pressure", - "dateTime": "2023-12-30T20:45:00", - "value": "120/80" - }, - { - "groupName": "Endocrinology", - "code": "3101", - "name": "Thyroid Stimulating Hormone", - "dateTime": "2024-01-01T10:00:00", - "value": "2.5" - }, - { - "groupName": "Endocrinology", - "code": "3125", - "name": "Fasting Blood Sugar", - "dateTime": "2024-01-05T12:15:00", - "value": "90" - }, - { - "groupName": "Endocrinology", - "code": "3147", - "name": "Insulin", - "dateTime": "2024-01-10T14:30:00", - "value": "15" - }, - { - "groupName": "Endocrinology", - "code": "3200", - "name": "HbA1c", - "dateTime": "2024-01-15T16:45:00", - "value": "5.8" - }, - { - "groupName": "Neurology", - "code": "4102", - "name": "Brain Natriuretic Peptide", - "dateTime": "2024-01-20T18:00:00", - "value": "100" - }, - { - "groupName": "Neurology", - "code": "3300", - "name": "Cerebrospinal Fluid", - "dateTime": "2024-01-25T20:15:00", - "value": "Clear" - }, - { - "groupName": "Neurology", - "code": "3401", - "name": "Electroencephalogram", - "dateTime": "2024-01-30T22:30:00", - "value": "Normal" - }, - { - "groupName": "Nephrology", - "code": "2240", - "name": "Serum Creatinine", - "dateTime": "2024-02-01T09:00:00", - "value": "0.9" - }, - { - "groupName": "Nephrology", - "code": "1213", - "name": "Blood Urea Nitrogen", - "dateTime": "2024-02-05T11:15:00", - "value": "20" - }, - { - "groupName": "Nephrology", - "code": "1250", - "name": "Glomerular Filtration Rate", - "dateTime": "2024-02-10T13:30:00", - "value": "90" - }, - { - "groupName": "Nephrology", - "code": "1265", - "name": "Urine Protein", - "dateTime": "2024-02-15T15:45:00", - "value": "Negative" - }, - { - "groupName": "Nephrology", - "code": "1275", - "name": "Urine Creatinine", - "dateTime": "2024-02-20T18:00:00", - "value": "0.8" - } + { + "dateTime": "2023-12-01T08:00:00", + "groupName": "Hematology", + "code": "1730", + "name": "Hemoglobin", + "value": "5" + }, + { + "dateTime": "2023-12-05T10:30:00", + "groupName": "Hematology", + "code": "2845", + "name": "Platelet Count", + "value": "240000" + }, + { + "dateTime": "2023-12-10T12:45:00", + "groupName": "Hematology", + "code": "2990", + "name": "White Blood Cell Count", + "value": "8000" + }, + { + "dateTime": "2023-12-15T14:00:00", + "groupName": "Hematology", + "code": "1850", + "name": "Red Blood Cell Count", + "value": "4.5" + }, + { + "dateTime": "2023-12-20T16:15:00", + "groupName": "Hematology", + "code": "1987", + "name": "Mean Corpuscular Volume", + "value": "90" + }, + { + "dateTime": "2023-12-25T18:30:00", + "groupName": "Cardiology", + "code": "1201", + "name": "Heart Rate", + "value": "75" + }, + { + "dateTime": "2023-12-30T20:45:00", + "groupName": "Cardiology", + "code": "1300", + "name": "Blood Pressure", + "value": "120/80" + }, + { + "dateTime": "2024-01-01T10:00:00", + "groupName": "Endocrinology", + "code": "3101", + "name": "Thyroid Stimulating Hormone", + "value": "2.5" + }, + { + "dateTime": "2024-01-05T12:15:00", + "groupName": "Endocrinology", + "code": "3125", + "name": "Fasting Blood Sugar", + "value": "90" + }, + { + "dateTime": "2024-01-10T14:30:00", + "groupName": "Endocrinology", + "code": "3147", + "name": "Insulin", + "value": "15" + }, + { + "dateTime": "2024-01-15T16:45:00", + "groupName": "Endocrinology", + "code": "3200", + "name": "HbA1c", + "value": "5.8" + }, + { + "dateTime": "2024-01-20T18:00:00", + "groupName": "Neurology", + "code": "4102", + "name": "Brain Natriuretic Peptide", + "value": "100" + }, + { + "dateTime": "2024-01-25T20:15:00", + "groupName": "Neurology", + "code": "3300", + "name": "Cerebrospinal Fluid", + "value": "Clear" + }, + { + "dateTime": "2024-01-30T22:30:00", + "groupName": "Neurology", + "code": "3401", + "name": "Electroencephalogram", + "value": "Normal" + }, + { + "dateTime": "2024-02-01T09:00:00", + "groupName": "Nephrology", + "code": "2240", + "name": "Serum Creatinine", + "value": "0.9" + }, + { + "dateTime": "2024-02-05T11:15:00", + "groupName": "Nephrology", + "code": "1213", + "name": "Blood Urea Nitrogen", + "value": "20" + }, + { + "dateTime": "2024-02-10T13:30:00", + "groupName": "Nephrology", + "code": "1250", + "name": "Glomerular Filtration Rate", + "value": "90" + }, + { + "dateTime": "2024-02-15T15:45:00", + "groupName": "Nephrology", + "code": "1265", + "name": "Urine Protein", + "value": "Negative" + }, + { + "dateTime": "2024-02-20T18:00:00", + "groupName": "Nephrology", + "code": "1275", + "name": "Urine Creatinine", + "value": "0.8" + } ] diff --git a/src/main/resources/json/labs.json b/src/main/resources/json/labs.json index 61bde507..d5669e01 100644 --- a/src/main/resources/json/labs.json +++ b/src/main/resources/json/labs.json @@ -1,42 +1,30 @@ -{ - "report": { - "labsData": true, - "labs": [ - { - "careCategoryName": "ANEMIA", - "currentMonthName": "NOV 2023", - "previousMonthName": "OCT 2023", +{"report": { + "labs": [{ "secondPreviousMonthName": "SEP 2023", - "careCategory": [ - { + "careCategory": [{ "labTestName": "HEMOGLOBIN (g/dL)", - "currentMonth": [ - { - "result0130": "343", - "outside0130": "Y", - "date0130": "(11/09)", - "outOfRangeInd0130": "1" - } - ], - "previousMonth": [ - { - "result3160": "", - "outside3160": "", - "date3160": "", - "outOfRangeInd3160": "0" - } - ], - "secondPreviousMonth": [ - { + "secondPreviousMonth": [{ "result6190": "", "outside6190": "", "date6190": "", "outOfRangeInd6190": "0" - } - ] - } - ] - } - ] - } -} \ No newline at end of file + }], + "previousMonth": [{ + "outside3160": "", + "outOfRangeInd3160": "0", + "date3160": "", + "result3160": "" + }], + "currentMonth": [{ + "outOfRangeInd0130": "1", + "result0130": "343", + "date0130": "(11/09)", + "outside0130": "Y" + }] + }], + "currentMonthName": "NOV 2023", + "careCategoryName": "ANEMIA", + "previousMonthName": "OCT 2023" + }], + "labsData": true +}} diff --git a/src/main/resources/json/object-mapper-tester.json b/src/main/resources/json/object-mapper-tester.json index 8387ce77..0fa3e3b3 100644 --- a/src/main/resources/json/object-mapper-tester.json +++ b/src/main/resources/json/object-mapper-tester.json @@ -1,9 +1,9 @@ { - "tester": 52.32, - "testerList": [ - 52.32, - 43.47, - 78.65, - 21.89 - ] -} \ No newline at end of file + "tester": 52.32, + "testerList": [ + 52.32, + 43.47, + 78.65, + 21.89 + ] +} diff --git a/src/main/resources/json/single-object-mapper.json b/src/main/resources/json/single-object-mapper.json index 9709bff2..666788e3 100644 --- a/src/main/resources/json/single-object-mapper.json +++ b/src/main/resources/json/single-object-mapper.json @@ -1,87 +1,87 @@ [ - { - "name": "John Doe", - "dateOfBirth": 1676878272857, - "datelocaltzdt": "2023-08-04T12:15:00", - "phones": { - "Work": "(123) 456 7890", - "Cell": "987-654-3210", - "Home": "963-852-7410" + { + "datelocaltzdt": "2023-08-04T12:15:00", + "addresses": [ + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": "37027", + "city": "Brentwood", + "addressLine1": "134 Plum Nelly Circle", + "addressLine2": null, + "state": "TN" + } + ], + "name": "John Doe", + "phones": { + "Work": "(123) 456 7890", + "Cell": "987-654-3210", + "Home": "963-852-7410" + }, + "dateOfBirth": 1676878272857 }, - "addresses": [ - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": "134 Plum Nelly Circle", - "addressLine2": null, - "city": "Brentwood", - "state": "TN", - "zip": "37027" - } - ] - }, - { - "name": "Alice Smith", - "dateOfBirth": 1648262272857, - "datelocaltzdt": "2023-09-12T08:30:00", - "phones": { - "Work": "(111) 222 3333", - "Cell": "444-555-6666", - "Home": "777-888-9999" + { + "datelocaltzdt": "2023-09-12T08:30:00", + "addresses": [ + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": "62701", + "city": "Springfield", + "addressLine1": "456 Elm Street", + "addressLine2": null, + "state": "IL" + } + ], + "name": "Alice Smith", + "phones": { + "Work": "(111) 222 3333", + "Cell": "444-555-6666", + "Home": "777-888-9999" + }, + "dateOfBirth": 1648262272857 }, - "addresses": [ - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": "456 Elm Street", - "addressLine2": null, - "city": "Springfield", - "state": "IL", - "zip": "62701" - } - ] - }, - { - "name": "Bob Johnson", - "dateOfBirth": 1625182272857, - "datelocaltzdt": "2023-07-18T16:45:00", - "phones": { - "Work": "(999) 888 7777", - "Cell": "666-555-4444", - "Home": "333-222-1111" - }, - "addresses": [ - { - "addressLine1": null, - "addressLine2": null, - "city": null, - "state": null, - "zip": null - }, - { - "addressLine1": "789 Oak Avenue", - "addressLine2": null, - "city": "Oakland", - "state": "CA", - "zip": "94601" - } - ] - } -] \ No newline at end of file + { + "datelocaltzdt": "2023-07-18T16:45:00", + "addresses": [ + { + "zip": null, + "city": null, + "addressLine1": null, + "addressLine2": null, + "state": null + }, + { + "zip": "94601", + "city": "Oakland", + "addressLine1": "789 Oak Avenue", + "addressLine2": null, + "state": "CA" + } + ], + "name": "Bob Johnson", + "phones": { + "Work": "(999) 888 7777", + "Cell": "666-555-4444", + "Home": "333-222-1111" + }, + "dateOfBirth": 1625182272857 + } +] diff --git a/src/main/resources/json/transactions.json b/src/main/resources/json/transactions.json index 7342388a..2ae85c2d 100644 --- a/src/main/resources/json/transactions.json +++ b/src/main/resources/json/transactions.json @@ -1,353 +1,351 @@ [ - { - "date": "2023-01-15", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item2", - "amount": 50 - } - ] - }, - { - "date": "2023-02-20", - "items": [ - { - "name": "item3", - "amount": 100 - } - ] - }, - { - "date": "2023-01-25", - "items": [ - { - "name": "item2", - "amount": 50 - }, - { - "name": "item3", - "amount": 100 - } - ] - }, - { - "date": "2023-03-10", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item2", - "amount": 50 - }, - { - "name": "item3", - "amount": 100 - } - ] - }, - { - "date": "2023-02-05", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item3", - "amount": 100 - } - ] - }, - { - "date": "2023-04-15", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item2", - "amount": 50 - } - ] - }, - { - "date": "2023-07-15", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item2", - "amount": 50 - } - ] - }, - { - "date": "2023-10-15", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item2", - "amount": 50 - } - ] - }, - { - "date": "2023-01-15", - "items": [ - { - "name": "item1", - "amount": 50 - }, - { - "name": "item2", - "amount": 50 - } - ] - }, - { - "date": "2023-01-30", - "items": [ - { - "name": "item2", - "amount": 40 - }, - { - "name": "item3", - "amount": 60 - } - ] - }, - { - "date": "2023-02-05", - "items": [ - { - "name": "item1", - "amount": 30 - }, - { - "name": "item3", - "amount": 70 - } - ] - }, - { - "date": "2023-02-20", - "items": [ - { - "name": "item3", - "amount": 80 - }, - { - "name": "item4", - "amount": 20 - } - ] - }, - { - "date": "2023-03-10", - "items": [ - { - "name": "item1", - "amount": 45 - }, - { - "name": "item2", - "amount": 55 - } - ] - }, - { - "date": "2023-03-25", - "items": [ - { - "name": "item1", - "amount": 20 - }, - { - "name": "item3", - "amount": 80 - } - ] - }, - { - "date": "2023-04-15", - "items": [ - { - "name": "item2", - "amount": 60 - }, - { - "name": "item3", - "amount": 40 - } - ] - }, - { - "date": "2023-04-30", - "items": [ - { - "name": "item1", - "amount": 70 - }, - { - "name": "item4", - "amount": 30 - } - ] - }, - { - "date": "2023-05-05", - "items": [ - { - "name": "item2", - "amount": 50 - }, - { - "name": "item4", - "amount": 50 - } - ] - }, - { - "date": "2023-05-20", - "items": [ - { - "name": "item1", - "amount": 40 - }, - { - "name": "item3", - "amount": 60 - } - ] - }, - { - "date": "2023-06-10", - "items": [ - { - "name": "item1", - "amount": 60 - }, - { - "name": "item2", - "amount": 40 - } - ] - }, - { - "date": "2023-06-25", - "items": [ - { - "name": "item3", - "amount": 70 - }, - { - "name": "item4", - "amount": 30 - } - ] - }, - { - "date": "2023-07-15", - "items": [ - { - "name": "item1", - "amount": 55 - }, - { - "name": "item2", - "amount": 45 - } - ] - }, - { - "date": "2023-07-30", - "items": [ - { - "name": "item2", - "amount": 35 - }, - { - "name": "item4", - "amount": 65 - } - ] - }, - { - "date": "2023-08-05", - "items": [ - { - "name": "item1", - "amount": 25 - }, - { - "name": "item3", - "amount": 75 - } - ] - }, - { - "date": "2023-08-20", - "items": [ - { - "name": "item3", - "amount": 60 - }, - { - "name": "item4", - "amount": 40 - } - ] - }, - { - "date": "2023-09-10", - "items": [ - { - "name": "item1", - "amount": 45 - }, - { - "name": "item2", - "amount": 55 - } - ] - }, - { - "date": "2023-09-25", - "items": [ - { - "name": "item1", - "amount": 30 - }, - { - "name": "item3", - "amount": 70 - } - ] - }, - { - "date": "2023-10-15", - "items": [ - { - "name": "item2", - "amount": 60 - }, - { - "name": "item3", - "amount": 40 - } - ] - } -] \ No newline at end of file + { + "date": "2023-01-15", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 50, + "name": "item2" + } + ] + }, + { + "date": "2023-02-20", + "items": [{ + "amount": 100, + "name": "item3" + }] + }, + { + "date": "2023-01-25", + "items": [ + { + "amount": 50, + "name": "item2" + }, + { + "amount": 100, + "name": "item3" + } + ] + }, + { + "date": "2023-03-10", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 50, + "name": "item2" + }, + { + "amount": 100, + "name": "item3" + } + ] + }, + { + "date": "2023-02-05", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 100, + "name": "item3" + } + ] + }, + { + "date": "2023-04-15", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 50, + "name": "item2" + } + ] + }, + { + "date": "2023-07-15", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 50, + "name": "item2" + } + ] + }, + { + "date": "2023-10-15", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 50, + "name": "item2" + } + ] + }, + { + "date": "2023-01-15", + "items": [ + { + "amount": 50, + "name": "item1" + }, + { + "amount": 50, + "name": "item2" + } + ] + }, + { + "date": "2023-01-30", + "items": [ + { + "amount": 40, + "name": "item2" + }, + { + "amount": 60, + "name": "item3" + } + ] + }, + { + "date": "2023-02-05", + "items": [ + { + "amount": 30, + "name": "item1" + }, + { + "amount": 70, + "name": "item3" + } + ] + }, + { + "date": "2023-02-20", + "items": [ + { + "amount": 80, + "name": "item3" + }, + { + "amount": 20, + "name": "item4" + } + ] + }, + { + "date": "2023-03-10", + "items": [ + { + "amount": 45, + "name": "item1" + }, + { + "amount": 55, + "name": "item2" + } + ] + }, + { + "date": "2023-03-25", + "items": [ + { + "amount": 20, + "name": "item1" + }, + { + "amount": 80, + "name": "item3" + } + ] + }, + { + "date": "2023-04-15", + "items": [ + { + "amount": 60, + "name": "item2" + }, + { + "amount": 40, + "name": "item3" + } + ] + }, + { + "date": "2023-04-30", + "items": [ + { + "amount": 70, + "name": "item1" + }, + { + "amount": 30, + "name": "item4" + } + ] + }, + { + "date": "2023-05-05", + "items": [ + { + "amount": 50, + "name": "item2" + }, + { + "amount": 50, + "name": "item4" + } + ] + }, + { + "date": "2023-05-20", + "items": [ + { + "amount": 40, + "name": "item1" + }, + { + "amount": 60, + "name": "item3" + } + ] + }, + { + "date": "2023-06-10", + "items": [ + { + "amount": 60, + "name": "item1" + }, + { + "amount": 40, + "name": "item2" + } + ] + }, + { + "date": "2023-06-25", + "items": [ + { + "amount": 70, + "name": "item3" + }, + { + "amount": 30, + "name": "item4" + } + ] + }, + { + "date": "2023-07-15", + "items": [ + { + "amount": 55, + "name": "item1" + }, + { + "amount": 45, + "name": "item2" + } + ] + }, + { + "date": "2023-07-30", + "items": [ + { + "amount": 35, + "name": "item2" + }, + { + "amount": 65, + "name": "item4" + } + ] + }, + { + "date": "2023-08-05", + "items": [ + { + "amount": 25, + "name": "item1" + }, + { + "amount": 75, + "name": "item3" + } + ] + }, + { + "date": "2023-08-20", + "items": [ + { + "amount": 60, + "name": "item3" + }, + { + "amount": 40, + "name": "item4" + } + ] + }, + { + "date": "2023-09-10", + "items": [ + { + "amount": 45, + "name": "item1" + }, + { + "amount": 55, + "name": "item2" + } + ] + }, + { + "date": "2023-09-25", + "items": [ + { + "amount": 30, + "name": "item1" + }, + { + "amount": 70, + "name": "item3" + } + ] + }, + { + "date": "2023-10-15", + "items": [ + { + "amount": 60, + "name": "item2" + }, + { + "amount": 40, + "name": "item3" + } + ] + } +] diff --git a/src/test/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversionTest.java b/src/test/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversionTest.java index 7c06aa20..ee6c83e0 100644 --- a/src/test/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversionTest.java +++ b/src/test/java/nitin/calandarDateTime/java8Calandar/GmtToEstFormattedConversionTest.java @@ -1,13 +1,12 @@ package nitin.calandarDateTime.java8Calandar; -import com.utilities.ZonedDateTimeUtility.Result; -import org.junit.jupiter.api.Test; - -import java.time.zone.ZoneRulesException; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.utilities.ZonedDateTimeUtility.Result; +import java.time.zone.ZoneRulesException; +import org.junit.jupiter.api.Test; + public class GmtToEstFormattedConversionTest { @Test @@ -66,26 +65,32 @@ public void testTimeZoneWithDaylightSavingTimeTransition() { Result result = GmtToEstFormattedConversion.run(startDateTime, endDateTime, timeZoneIso); - //Same Date - //In the Eastern Time Zone (America/New_York), the daylight saving time (DST) transition happens on March 11, 2024. - // Therefore, the local time will transition from Eastern Standard Time (EST) to Eastern Daylight Time (EDT). + // Same Date + // In the Eastern Time Zone (America/New_York), the daylight saving time (DST) transition + // happens on March 11, 2024. + // Therefore, the local time will transition from Eastern Standard Time (EST) to Eastern + // Daylight Time (EDT). assertEquals("21:30 EDT", result.startDate()); assertEquals("23:30 EDT", result.endDate()); } - @Test public void testInvalidTimeZone() { String startDateTime = "2024-03-22 03:04:44+00"; String endDateTime = "2024-03-22 04:44:44+00"; String timeZoneIso = "Invalid/Timezone"; - //GmtToEstFormattedConversion.Result result = GmtToEstFormattedConversion.run(startDateTime, endDateTime,timeZoneIso); + // GmtToEstFormattedConversion.Result result = + // GmtToEstFormattedConversion.run(startDateTime, endDateTime,timeZoneIso); // Use assertThrows with the expected exception type and a lambda expression - ZoneRulesException exception = assertThrows(ZoneRulesException.class, () -> { - GmtToEstFormattedConversion.run(startDateTime, endDateTime, timeZoneIso); - }); + ZoneRulesException exception = + assertThrows( + ZoneRulesException.class, + () -> { + GmtToEstFormattedConversion.run( + startDateTime, endDateTime, timeZoneIso); + }); // Verify the exception message assertEquals("Invalid Timezone :: Invalid/Timezone", exception.getMessage()); @@ -95,18 +100,20 @@ public void testInvalidTimeZone() { public void testTimeZoneWithDaylightSavingTimeTransitionMultiDay() { // Scenario 1: Start in EST, End in EDT String startDateTime1 = "2024-03-10 04:00:00+00"; // Start time in GMT - String endDateTime1 = "2024-03-10 07:00:00+00"; // End time in GMT + String endDateTime1 = "2024-03-10 07:00:00+00"; // End time in GMT String timeZoneIso1 = "America/New_York"; - Result result1 = GmtToEstFormattedConversion.run(startDateTime1, endDateTime1, timeZoneIso1); + Result result1 = + GmtToEstFormattedConversion.run(startDateTime1, endDateTime1, timeZoneIso1); assertEquals("03/09/2024 23:00 EST", result1.startDate()); assertEquals("03/10/2024 03:00 EDT", result1.endDate()); // Scenario 2: Start in EST, End in EDT String startDateTime2 = "2024-03-10 06:59:00+00"; // Start time in GMT - String endDateTime2 = "2024-03-10 07:00:00+00"; // End time in GMT + String endDateTime2 = "2024-03-10 07:00:00+00"; // End time in GMT String timeZoneIso2 = "America/New_York"; - Result result2 = GmtToEstFormattedConversion.run(startDateTime2, endDateTime2, timeZoneIso2); + Result result2 = + GmtToEstFormattedConversion.run(startDateTime2, endDateTime2, timeZoneIso2); assertEquals("01:59 EST", result2.startDate()); assertEquals("03:00 EDT", result2.endDate()); } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/mappers/JacksonMapperTypesTest.java b/src/test/java/nitin/mappers/JacksonMapperTypesTest.java index a1887e28..3bcb529e 100644 --- a/src/test/java/nitin/mappers/JacksonMapperTypesTest.java +++ b/src/test/java/nitin/mappers/JacksonMapperTypesTest.java @@ -1,32 +1,29 @@ package nitin.mappers; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import nitin.mappers.jackson.JacksonMapperTypes; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; import nitin.mappers.jackson.model.RandomVehicle; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - @ExtendWith(MockitoExtension.class) public class JacksonMapperTypesTest { - @Mock - private ObjectMapper objectMapper; + @Mock private ObjectMapper objectMapper; private static RandomVehicle getSingleJsonFromFile() throws IOException { URL resource = new URL("file:src/test/resources/json/single_random_vehicle.json"); @@ -39,81 +36,85 @@ private static RandomVehicle getSingleJsonFromFile() throws IOException { return vehicle; } + @Tag("slow") @Test - void getFewRandomVehicles() throws JsonProcessingException { - RandomVehicle randomVehicle = RandomVehicle.builder() - .id(6534) - .uid("742b4374-032e-49bb-9b5b-92ffb457d313") - .vin("NPWPCPYJP9H242398") - .makeAndModel("Chevy Silverado") - .transmission("CVT") - .color("Yellow") - .driveType("AWD") - .fuelType("Gasoline Hybrid") - .carType("Wagon") - .carOptions(List.of("AM/FM Stereo", - "Airbag: Side", - "Airbag: Driver", - "CD (Multi Disc)", - "Cassette Player", - "Alloy Wheels")) - .specs(List.of("Traveler/mini trip computer", - "Rear door child safety locks", - "20\" x 9.0\" front & 20\" x 10.0\" rear aluminum wheels", - "Electronic brakeforce distribution (EBD) w/brake assist (BA) -inc: Smart stop technology", - "Eco drive indicator", - "Leather-wrapped shift knob", - "Foldable front door storage pockets", - "Foldable front door storage pockets", - "Anti-lock brake system (ABS) -inc: electronic brake force distribution (EBD), brake assist")) - .doors(2) - .mileage(82508) - .kilometer_range(45776) - .licensePlate("SQT-5871") - .build(); - - List randomVehicles = List.of(randomVehicle); - //Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.eq(RandomVehicle.class))).thenReturn(randomVehicles); - assertEquals(1, JacksonMapperTypes.getFewRandomVehicles(1).size()); - // Mockito.verify(objectMapper, Mockito.times(1)).readValue(Mockito.anyString(), Mockito.eq(RandomVehicle.class)); - } + /* + void getFewRandomVehicles() throws JsonProcessingException { + RandomVehicle randomVehicle = RandomVehicle.builder() + .id(6534) + .uid("742b4374-032e-49bb-9b5b-92ffb457d313") + .vin("NPWPCPYJP9H242398") + .makeAndModel("Chevy Silverado") + .transmission("CVT") + .color("Yellow") + .driveType("AWD") + .fuelType("Gasoline Hybrid") + .carType("Wagon") + .carOptions(List.of("AM/FM Stereo", + "Airbag: Side", + "Airbag: Driver", + "CD (Multi Disc)", + "Cassette Player", + "Alloy Wheels")) + .specs(List.of("Traveler/mini trip computer", + "Rear door child safety locks", + "20\" x 9.0\" front & 20\" x 10.0\" rear aluminum wheels", + "Electronic brakeforce distribution (EBD) w/brake assist (BA) -inc: Smart stop technology", + "Eco drive indicator", + "Leather-wrapped shift knob", + "Foldable front door storage pockets", + "Foldable front door storage pockets", + "Anti-lock brake system (ABS) -inc: electronic brake force distribution (EBD), brake assist")) + .doors(2) + .mileage(82508) + .kilometer_range(45776) + .licensePlate("SQT-5871") + .build(); + + List randomVehicles = List.of(randomVehicle); + //Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.eq(RandomVehicle.class))).thenReturn(randomVehicles); + assertEquals(1, JacksonMapperTypes.getFewRandomVehicles(1).size()); + // Mockito.verify(objectMapper, Mockito.times(1)).readValue(Mockito.anyString(), Mockito.eq(RandomVehicle.class)); + } + */ - @Test + // @Test void test_single_json_object() throws MalformedURLException, JsonProcessingException { - String JSON_OBJECT = "{\n" + - "\"id\": 6534,\n" + - "\"uid\": \"742b4374-032e-49bb-9b5b-92ffb457d313\",\n" + - "\"vin\": \"NPWPCPYJP9H242398\",\n" + - "\"make_and_model\": \"Chevy Silverado\",\n" + - "\"color\": \"Yellow\",\n" + - "\"transmission\": \"CVT\",\n" + - "\"drive_type\": \"AWD\",\n" + - "\"fuel_type\": \"Gasoline Hybrid\",\n" + - "\"car_type\": \"Wagon\",\n" + - "\"car_options\": [\n" + - "\"AM/FM Stereo\",\n" + - "\"Airbag: Side\",\n" + - "\"Airbag: Driver\",\n" + - "\"CD (Multi Disc)\",\n" + - "\"Cassette Player\",\n" + - "\"Alloy Wheels\"\n" + - "],\n" + - "\"specs\": [\n" + - "\"Traveler/mini trip computer\",\n" + - "\"Rear door child safety locks\",\n" + - "\"20\\\" x 9.0\\\" front & 20\\\" x 10.0\\\" rear aluminum wheels\",\n" + - "\"Electronic brakeforce distribution (EBD) w/brake assist (BA) -inc: Smart stop technology\",\n" + - "\"Eco drive indicator\",\n" + - "\"Leather-wrapped shift knob\",\n" + - "\"Foldable front door storage pockets\",\n" + - "\"Foldable front door storage pockets\",\n" + - "\"Anti-lock brake system (ABS) -inc: electronic brake force distribution (EBD), brake assist\"\n" + - "],\n" + - "\"doors\": 2,\n" + - "\"mileage\": 82508,\n" + - "\"kilometrage\": 45776,\n" + - "\"license_plate\": \"SQT-5871\"\n" + - "}"; + String JSON_OBJECT = + "{\n" + + "\"id\": 6534,\n" + + "\"uid\": \"742b4374-032e-49bb-9b5b-92ffb457d313\",\n" + + "\"vin\": \"NPWPCPYJP9H242398\",\n" + + "\"make_and_model\": \"Chevy Silverado\",\n" + + "\"color\": \"Yellow\",\n" + + "\"transmission\": \"CVT\",\n" + + "\"drive_type\": \"AWD\",\n" + + "\"fuel_type\": \"Gasoline Hybrid\",\n" + + "\"car_type\": \"Wagon\",\n" + + "\"car_options\": [\n" + + "\"AM/FM Stereo\",\n" + + "\"Airbag: Side\",\n" + + "\"Airbag: Driver\",\n" + + "\"CD (Multi Disc)\",\n" + + "\"Cassette Player\",\n" + + "\"Alloy Wheels\"\n" + + "],\n" + + "\"specs\": [\n" + + "\"Traveler/mini trip computer\",\n" + + "\"Rear door child safety locks\",\n" + + "\"20\\\" x 9.0\\\" front & 20\\\" x 10.0\\\" rear aluminum wheels\",\n" + + "\"Electronic brakeforce distribution (EBD) w/brake assist (BA) -inc: Smart stop technology\",\n" + + "\"Eco drive indicator\",\n" + + "\"Leather-wrapped shift knob\",\n" + + "\"Foldable front door storage pockets\",\n" + + "\"Foldable front door storage pockets\",\n" + + "\"Anti-lock brake system (ABS) -inc: electronic brake force distribution (EBD), brake assist\"\n" + + "],\n" + + "\"doors\": 2,\n" + + "\"mileage\": 82508,\n" + + "\"kilometrage\": 45776,\n" + + "\"license_plate\": \"SQT-5871\"\n" + + "}"; ObjectMapper mapper = new ObjectMapper(); RandomVehicle vehicle = mapper.readValue(JSON_OBJECT, RandomVehicle.class); assertNotNull(vehicle); @@ -125,8 +126,8 @@ void test_json_array() throws IOException { URL resource = new URL("file:src/test/resources/json/random_vehicle_array_json.json"); ObjectMapper objectMapper = new ObjectMapper(); - List randomVehicles = objectMapper.readValue(resource, new TypeReference>() { - }); + List randomVehicles = + objectMapper.readValue(resource, new TypeReference>() {}); for (final RandomVehicle car : randomVehicles) { assertNotNull(car); @@ -139,7 +140,7 @@ void test_json_array() throws IOException { void test_json_single_file() throws IOException { RandomVehicle vehicle = getSingleJsonFromFile(); assertNotNull(vehicle); - //assertThat(vehicle.getColor(), null);//containsString("Red")); + // assertThat(vehicle.getColor(), null);//containsString("Red")); assertEquals(vehicle.getCarOptions().size(), 11); // assertNull(vehicle.getColor()); } diff --git a/src/test/java/nitin/metrix/ArchUnitTest.java b/src/test/java/nitin/metrix/ArchUnitTest.java index d03b67e0..1fe1c5ca 100644 --- a/src/test/java/nitin/metrix/ArchUnitTest.java +++ b/src/test/java/nitin/metrix/ArchUnitTest.java @@ -5,26 +5,23 @@ import com.tngtech.archunit.library.Architectures; import org.junit.jupiter.api.Test; -import static com.tngtech.archunit.library.Architectures.layeredArchitecture; - public class ArchUnitTest { @Test void testArch() { - JavaClasses jc = new ClassFileImporter() - .importPackages("com.nitin"); + JavaClasses jc = new ClassFileImporter().importPackages("com.nitin"); Architectures.LayeredArchitecture arch; - arch = layeredArchitecture() - // Define layers - .layer("Presentation").definedBy("..presentation..") - .layer("Service").definedBy("..service..") - .layer("Persistence").definedBy("..persistence..") - // Add constraints - .whereLayer("Presentation").mayNotBeAccessedByAnyLayer() - .whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation") - .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service"); + // arch = layeredArchitecture() + // // Define layers + // .layer("Presentation").definedBy("..presentation..") + // .layer("Service").definedBy("..service..") + // .layer("Persistence").definedBy("..persistence..") + // // Add constraints + // .whereLayer("Presentation").mayNotBeAccessedByAnyLayer() + // .whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation") + // .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service"); - arch.check(jc); + // arch.check(jc); } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/metrix/DistanceFromMainSequenceFitnessFunction.java b/src/test/java/nitin/metrix/DistanceFromMainSequenceFitnessFunction.java index ff760f0f..18b4f0c8 100644 --- a/src/test/java/nitin/metrix/DistanceFromMainSequenceFitnessFunction.java +++ b/src/test/java/nitin/metrix/DistanceFromMainSequenceFitnessFunction.java @@ -1,17 +1,8 @@ package nitin.metrix; - +import java.io.IOException; import jdepend.framework.JDepend; -import jdepend.framework.JavaPackage; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.Collection; -import java.util.Iterator; - -import static org.junit.Assert.assertEquals; public class DistanceFromMainSequenceFitnessFunction { @@ -22,13 +13,14 @@ void init() throws IOException { jdepend = new JDepend(); jdepend.addDirectory("build/classes/java/main"); } - @Test + /*@Test + @Ignore void testAllPackages() { Collection packages = jdepend.analyze(); assertEquals("Cycles exist", false, jdepend.containsCycles()); - } + }*/ - @Test + /*@Test void allPackages(){ double ideal = 0.0; double tolerance = 0.5; // project-dependent @@ -38,5 +30,5 @@ void allPackages(){ JavaPackage p = (JavaPackage)iter.next(); Assertions.assertEquals(ideal, p.distance(), tolerance, "Distance exceeded: " + p.getName()); } - } + }*/ } diff --git a/src/test/java/nitin/multithreading/completableFutureBasics/CThenCombineTest.java b/src/test/java/nitin/multithreading/completableFutureBasics/CThenCombineTest.java index 48b90b38..2b6cd66e 100644 --- a/src/test/java/nitin/multithreading/completableFutureBasics/CThenCombineTest.java +++ b/src/test/java/nitin/multithreading/completableFutureBasics/CThenCombineTest.java @@ -1,16 +1,15 @@ package nitin.multithreading.completableFutureBasics; +import static com.utilities.PerformanceUtility.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.concurrent.CompletableFuture; import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.A12ThenCombine; import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.concurrent.CompletableFuture; - -import static com.utilities.PerformanceUtility.*; -import static org.junit.jupiter.api.Assertions.assertEquals; - @ExtendWith(MockitoExtension.class) public class CThenCombineTest { @@ -19,57 +18,63 @@ public class CThenCombineTest { @Test public void thenCombineCF() { - //Sequential Time : Should take over 2000 milli seconds adn there has been artificial delay introduced + // Sequential Time : Should take over 2000 milli seconds adn there has been artificial delay + // introduced startTimer(); - System.out.println((dfs.firstNameService(3) + " " + dfs.lastNameService(1000)).toUpperCase()); + System.out.println( + (dfs.firstNameService(3) + " " + dfs.lastNameService(1000)).toUpperCase()); stopTimer(); resetTimer(); - //when + // when startTimer(); - //Async Task: Should take Max(task1, Task2), close to a little over 1000 milli seconds + // Async Task: Should take Max(task1, Task2), close to a little over 1000 milli seconds CompletableFuture completableFuture = A12ThenCombine.fullNameService(); - stopTimer();//results are not returned yet + stopTimer(); // results are not returned yet - //then + // then resetTimer(); startTimer(); completableFuture - .thenAccept(fullName -> { - assertEquals(fullName, "JOHN DOE"); - }) - .join();//so that results can be collected + .thenAccept( + fullName -> { + assertEquals(fullName, "JOHN DOE"); + }) + .join(); // so that results can be collected stopTimer(); } @Test public void fullNameWithGreetingServiceTest() { startTimer(); - //when + // when CompletableFuture completableFuture = A12ThenCombine.fullNameWithGreetingService(); - //then + // then completableFuture - .thenAccept(fullNameWithGreetings -> { - assertEquals(fullNameWithGreetings, "HELLO!! JOHN DOE"); - }) - .join();//so that results can be collected + .thenAccept( + fullNameWithGreetings -> { + assertEquals(fullNameWithGreetings, "HELLO!! JOHN DOE"); + }) + .join(); // so that results can be collected stopTimer(); } @Test public void fullNameWithGreetingAndGoodByesServiceTest() { startTimer(); - //when - CompletableFuture completableFuture = A12ThenCombine.fullNameWithGreetingAndGoodByesService(); + // when + CompletableFuture completableFuture = + A12ThenCombine.fullNameWithGreetingAndGoodByesService(); - //then + // then completableFuture - .thenAccept(fullNameWithGreetings -> { - assertEquals(fullNameWithGreetings, "Hello!! john doe, Thank You!!"); - }) - .join();//so that results can be collected + .thenAccept( + fullNameWithGreetings -> { + assertEquals(fullNameWithGreetings, "Hello!! john doe, Thank You!!"); + }) + .join(); // so that results can be collected stopTimer(); } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/multithreading/completableFutureBasics/CompletableFutureExceptionHandlingTest.java b/src/test/java/nitin/multithreading/completableFutureBasics/CompletableFutureExceptionHandlingTest.java index ba32ae72..2e6458f0 100644 --- a/src/test/java/nitin/multithreading/completableFutureBasics/CompletableFutureExceptionHandlingTest.java +++ b/src/test/java/nitin/multithreading/completableFutureBasics/CompletableFutureExceptionHandlingTest.java @@ -1,5 +1,8 @@ package nitin.multithreading.completableFutureBasics; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.A5CompletableFutureExceptionHandling; import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; import org.junit.jupiter.api.Test; @@ -8,106 +11,106 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - - @ExtendWith(MockitoExtension.class) public class CompletableFutureExceptionHandlingTest { - @Mock - DataFetchService dataFetchService = new DataFetchService(); + @Mock DataFetchService dataFetchService = new DataFetchService(); - @InjectMocks - A5CompletableFutureExceptionHandling completableFutureExceptionHandling; + @InjectMocks A5CompletableFutureExceptionHandling completableFutureExceptionHandling; @Test public void async_call_exception_handle_test_1exception() { - //Given - when(dataFetchService.greetingsService(1000)).thenThrow(new NullPointerException("Exception"));//One Exception + // Given + when(dataFetchService.greetingsService(1000)) + .thenThrow(new NullPointerException("Exception")); // One Exception when((dataFetchService.firstNameService(1000))).thenCallRealMethod(); when((dataFetchService.lastNameService(1000))).thenCallRealMethod(); - //When + // When String result = completableFutureExceptionHandling.async_call_exception_handle(); - //then + // then assertEquals(result, "ERROR HI!! JOHN DOE"); } @Test public void async_call_exception_handle_test_2Exception() { - //Given - when(dataFetchService.greetingsService(1000)).thenThrow(new NullPointerException("Exception")); - when((dataFetchService.firstNameService(1000))).thenThrow(new NullPointerException("Exception")); + // Given + when(dataFetchService.greetingsService(1000)) + .thenThrow(new NullPointerException("Exception")); + when((dataFetchService.firstNameService(1000))) + .thenThrow(new NullPointerException("Exception")); when((dataFetchService.lastNameService(1000))).thenCallRealMethod(); - //When + // When String result = completableFutureExceptionHandling.async_call_exception_handle(); - //then + // then assertEquals(result, "ERROR FN!! DOE"); } @Test public void async_call_exception_handle_test_no_exception() { - //Given + // Given when(dataFetchService.greetingsService(1000)).thenCallRealMethod(); when((dataFetchService.firstNameService(1000))).thenCallRealMethod(); when((dataFetchService.lastNameService(1000))).thenCallRealMethod(); - //When + // When String result = completableFutureExceptionHandling.async_call_exception_handle(); - //then + // then assertEquals(result, "HELLO! JOHN DOE"); } @Test public void async_call_exception_exceptionally_test_no_exception() { - //Given + // Given when(dataFetchService.greetingsService(1000)).thenCallRealMethod(); when((dataFetchService.firstNameService(1000))).thenCallRealMethod(); when((dataFetchService.lastNameService(1000))).thenCallRealMethod(); - //When + // When String result = completableFutureExceptionHandling.async_call_exception_exceptionally(); - //then + // then assertEquals(result, "HELLO! JOHN DOE"); } @Test public void async_call_exception_exceptionally_test_1_exception() { - //Given - when(dataFetchService.greetingsService(1000)).thenThrow(new NullPointerException("Exception")); + // Given + when(dataFetchService.greetingsService(1000)) + .thenThrow(new NullPointerException("Exception")); when((dataFetchService.firstNameService(1000))).thenCallRealMethod(); when((dataFetchService.lastNameService(1000))).thenCallRealMethod(); - //When + // When String result = completableFutureExceptionHandling.async_call_exception_handle(); - //then + // then assertEquals(result, "ERROR HI!! JOHN DOE"); } @Test public void async_call_exception_exceptionally_test_2_exception() { - //Given - when(dataFetchService.greetingsService(1000)).thenThrow(new NullPointerException("Exception")); - when((dataFetchService.firstNameService(1000))).thenThrow(new NullPointerException("Exception")); + // Given + when(dataFetchService.greetingsService(1000)) + .thenThrow(new NullPointerException("Exception")); + when((dataFetchService.firstNameService(1000))) + .thenThrow(new NullPointerException("Exception")); when((dataFetchService.lastNameService(1000))).thenCallRealMethod(); - //When + // When String result = completableFutureExceptionHandling.async_call_exception_exceptionally(); - //then + // then assertEquals(result, "ERROR FN!! DOE"); } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/multithreading/completableFutureBasics/DThenComposeTest.java b/src/test/java/nitin/multithreading/completableFutureBasics/DThenComposeTest.java index d53ad2f4..f2242022 100644 --- a/src/test/java/nitin/multithreading/completableFutureBasics/DThenComposeTest.java +++ b/src/test/java/nitin/multithreading/completableFutureBasics/DThenComposeTest.java @@ -1,8 +1,8 @@ package nitin.multithreading.completableFutureBasics; - import com.entity.dto.VehicleTransformed; import com.utilities.PerformanceUtility; +import java.util.concurrent.CompletableFuture; import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.A12ThenCompose; import nitin.multithreading.bFuturesAndCompletableFutures.completableFutureBasics.service.DataFetchService; import org.junit.Assert; @@ -10,8 +10,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.concurrent.CompletableFuture; - @ExtendWith(MockitoExtension.class) public class DThenComposeTest { @@ -22,28 +20,38 @@ public class DThenComposeTest { public void futureNameTest() { PerformanceUtility.startTimer(); - //when - CompletableFuture test = A12ThenCompose.getGreetings_compose();//Get name from one service and pass the name into another - - //then - test.thenAccept(result -> { - Assert.assertEquals(result, "Hello john"); - }).join(); - PerformanceUtility.stopTimer();//Takes time = task1 + task2 + // when + CompletableFuture test = + A12ThenCompose + .getGreetings_compose(); // Get name from one service and pass the name into + // another + + // then + test.thenAccept( + result -> { + Assert.assertEquals(result, "Hello john"); + }) + .join(); + PerformanceUtility.stopTimer(); // Takes time = task1 + task2 } @Test public void vehicleComposeTest() { PerformanceUtility.startTimer(); - //when - CompletableFuture test = A12ThenCompose.getHeighestMileageCar();//Get name from one service and pass the name into another - - //then - test.thenAccept(result -> { - //System.out.println(result); - Assert.assertNotNull(result); - }).join(); + // when + CompletableFuture test = + A12ThenCompose + .getHeighestMileageCar(); // Get name from one service and pass the name + // into another + + // then + test.thenAccept( + result -> { + // System.out.println(result); + Assert.assertNotNull(result); + }) + .join(); PerformanceUtility.stopTimer(); } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/multithreading/tests/IncrementLikesReentrantLocksTest.java b/src/test/java/nitin/multithreading/tests/IncrementLikesReentrantLocksTest.java index 035c3bbc..2eec2140 100644 --- a/src/test/java/nitin/multithreading/tests/IncrementLikesReentrantLocksTest.java +++ b/src/test/java/nitin/multithreading/tests/IncrementLikesReentrantLocksTest.java @@ -1,23 +1,19 @@ package nitin.multithreading.tests; -import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikesReentrantLocks; -import org.junit.Assert; -import org.junit.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.*; - +import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikesReentrantLocks; +import org.junit.Assert; +import org.junit.Test; public class IncrementLikesReentrantLocksTest { @Test - public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception { + public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() + throws Exception { int count = 1000; IncrementLikesReentrantLocks il = new IncrementLikesReentrantLocks(); @@ -25,7 +21,8 @@ public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavio Assert.assertEquals(count, uniqueSequences.size()); } - private Set getLikes(int count, IncrementLikesReentrantLocks il) throws InterruptedException, ExecutionException { + private Set getLikes(int count, IncrementLikesReentrantLocks il) + throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(10); Set uniqueSequences = new LinkedHashSet<>(); List> futures = new ArrayList<>(); @@ -38,7 +35,8 @@ private Set getLikes(int count, IncrementLikesReentrantLocks il) throws } for (Future future : futures) { - Integer result = future.get();//Future returns the datatype of the method thats been multithreaded + Integer result = future.get(); // Future returns the datatype of the method thats been + // multithreaded System.out.println("Result from Future " + result); uniqueSequences.add(result); } @@ -47,4 +45,4 @@ private Set getLikes(int count, IncrementLikesReentrantLocks il) throws executor.shutdown(); return uniqueSequences; } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/multithreading/tests/IncrementLikesSynchronizedTest.java b/src/test/java/nitin/multithreading/tests/IncrementLikesSynchronizedTest.java index cfaf1f91..9cbaabc0 100644 --- a/src/test/java/nitin/multithreading/tests/IncrementLikesSynchronizedTest.java +++ b/src/test/java/nitin/multithreading/tests/IncrementLikesSynchronizedTest.java @@ -1,15 +1,14 @@ package nitin.multithreading.tests; -import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikes; -import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikesSynchronized; -import org.junit.Assert; -import org.junit.Test; - import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.*; +import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikes; +import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikesSynchronized; +import org.junit.Assert; +import org.junit.Test; public class IncrementLikesSynchronizedTest { @@ -31,7 +30,8 @@ public void syncTest2() throws Exception { Assert.assertEquals(count.intValue(), uniqueSequences.size()); } - private Set getLikes2(Integer count, IncrementLikes il) throws InterruptedException, ExecutionException { + private Set getLikes2(Integer count, IncrementLikes il) + throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(10); Set uniqueSequences = new LinkedHashSet<>(); List> futures = new ArrayList<>(); @@ -41,7 +41,8 @@ private Set getLikes2(Integer count, IncrementLikes il) throws Interrup } for (Future future : futures) { - Integer result = future.get();//Future returns the datatype of the method thats been multithreaded + Integer result = future.get(); // Future returns the datatype of the method thats been + // multithreaded System.out.println("Result from Future " + result); uniqueSequences.add(result); } @@ -51,7 +52,8 @@ private Set getLikes2(Integer count, IncrementLikes il) throws Interrup return uniqueSequences; } - private Set getLikes(int count, IncrementLikes il) throws ExecutionException, InterruptedException { + private Set getLikes(int count, IncrementLikes il) + throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(10); Set uniqueSequences = new LinkedHashSet<>(); List> futures = new ArrayList<>(); @@ -61,7 +63,8 @@ private Set getLikes(int count, IncrementLikes il) throws ExecutionExce } for (Future future : futures) { - Integer result = future.get();//Future returns the datatype of the method thats been multithreaded + Integer result = future.get(); // Future returns the datatype of the method thats been + // multithreaded System.out.println("Result from Future " + result); uniqueSequences.add(result); } @@ -70,4 +73,4 @@ private Set getLikes(int count, IncrementLikes il) throws ExecutionExce executor.shutdown(); return uniqueSequences; } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/multithreading/tests/IncrementLikesTest.java b/src/test/java/nitin/multithreading/tests/IncrementLikesTest.java index f793d6a9..dbbc20ce 100644 --- a/src/test/java/nitin/multithreading/tests/IncrementLikesTest.java +++ b/src/test/java/nitin/multithreading/tests/IncrementLikesTest.java @@ -1,20 +1,19 @@ package nitin.multithreading.tests; -import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikes; -import org.junit.Assert; -import org.junit.Test; -import org.junit.jupiter.api.Assertions; - import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.*; +import nitin.multithreading.raceCondition.dSynchronization.tests.IncrementLikes; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class IncrementLikesTest { @Test - public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception { + public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() + throws Exception { int count = 1000; IncrementLikes il = new IncrementLikes(); @@ -22,7 +21,8 @@ public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavio Assertions.assertEquals(count, uniqueSequences.size()); } - private Set getLikes(int count, IncrementLikes il) throws InterruptedException, ExecutionException { + private Set getLikes(int count, IncrementLikes il) + throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(10); Set uniqueSequences = new LinkedHashSet<>(); List> futures = new ArrayList<>(); @@ -33,7 +33,8 @@ private Set getLikes(int count, IncrementLikes il) throws InterruptedEx } for (Future future : futures) { - Integer result = future.get();//Future returns the datatype of the method thats been multithreaded + Integer result = future.get(); // Future returns the datatype of the method thats been + // multithreaded System.out.println("Result from Future " + result); uniqueSequences.add(result); } @@ -42,4 +43,4 @@ private Set getLikes(int count, IncrementLikes il) throws InterruptedEx executor.shutdown(); return uniqueSequences; } -} \ No newline at end of file +} diff --git a/src/test/java/nitin/multithreading/tests/Test.java b/src/test/java/nitin/multithreading/tests/Test.java index 70744ddd..7bf420b8 100644 --- a/src/test/java/nitin/multithreading/tests/Test.java +++ b/src/test/java/nitin/multithreading/tests/Test.java @@ -1,4 +1,3 @@ package nitin.multithreading.tests; -public class Test { -} +public class Test {} diff --git a/src/test/resources/json/random_vehicle_array_json.json b/src/test/resources/json/random_vehicle_array_json.json index a91e8ebc..eccb85b8 100644 --- a/src/test/resources/json/random_vehicle_array_json.json +++ b/src/test/resources/json/random_vehicle_array_json.json @@ -1,161 +1,161 @@ [ - { - "id": 1881, - "uid": "49eb2aec-92ff-4aac-acae-c99b03fc2740", - "vin": "RNGN1JVX82ED73304", - "make_and_model": "Audi A7", - "color": "Blue", - "transmission": "Manual", - "drive_type": "4x2/2-wheel drive", - "fuel_type": "Compressed Natural Gas", - "car_type": "Wagon", - "car_options": [ - "Moonroof/Sunroof", - "Rear Window Wiper", - "AM/FM Stereo", - "Moonroof/Sunroof", - "Keyless Entry" - ], - "specs": [ - "Universal garage door opener", - "Battery saver", - "12V pwr outlet", - "Floor carpeting", - "Tire pressure monitoring display" - ], - "doors": 1, - "mileage": 18499, - "kilometrage": 37444, - "license_plate": "ETZ-4908" - }, - { - "id": 8764, - "uid": "b3f2d364-b310-4e69-b1cb-233dab19e0d1", - "vin": "Y8EPHPMREBKS78282", - "make_and_model": "Ford Fiesta", - "color": "Grey", - "transmission": "Manual", - "drive_type": "4x4/4-wheel drive", - "fuel_type": "Gasoline Hybrid", - "car_type": "Regular Cab Pickup", - "car_options": [ - "Alarm", - "Tinted Glass", - "Cruise Control", - "Cassette Player", - "Power Windows", - "Cassette Player" - ], - "specs": [ - "Cargo area lamp", - "Highline door trim panel", - "Center console", - "Body color door handles", - "Rear body-color spoiler", - "Center console", - "Security alarm" - ], - "doors": 1, - "mileage": 25511, - "kilometrage": 81519, - "license_plate": "QGV-8818" - }, - { - "id": 1542, - "uid": "9df611f6-60ef-4eaf-95a9-0253d287735e", - "vin": "PE7YPXAN27CM06466", - "make_and_model": "Honda CR-V", - "color": "Orange", - "transmission": "Automanual", - "drive_type": "4x2/2-wheel drive", - "fuel_type": "Compressed Natural Gas", - "car_type": "Crew Cab Pickup", - "car_options": [ - "Moonroof/Sunroof", - "Rear Window Defroster", - "Rear Window Defroster", - "Premium Sound", - "Airbag: Side", - "Rear Window Wiper", - "A/C: Rear", - "Alloy Wheels", - "Premium Sound" - ], - "specs": [ - "Tachometer", - "Deluxe insulation group", - "Vehicle dynamics integrated management (VDIM) system -inc: vehicle stability control (VSC), traction control (TRAC)", - "Electrochromic pwr folding heated mirrors w/memory -inc: puddle lamps, integrated turn signals, auto reverse tilt-down", - "Side-impact door beams" - ], - "doors": 1, - "mileage": 33946, - "kilometrage": 63756, - "license_plate": "RGC-7001" - }, - { - "id": 2177, - "uid": "d02f7c5e-812d-4251-bd81-b01e6b8efa6d", - "vin": "PDL2JHLPMMDJ97457", - "make_and_model": "BMW M3", - "color": "Violet", - "transmission": "Manual", - "drive_type": "4x2/2-wheel drive", - "fuel_type": "Gasoline", - "car_type": "Crew Cab Pickup", - "car_options": [ - "Power Locks", - "Fog Lights", - "Antilock Brakes", - "Integrated Phone", - "DVD System", - "Bucket Seats", - "Power Locks", - "MP3 (Multi Disc)" - ], - "specs": [ - "Trim-panel-mounted storage net", - "Electronic throttle control system w/intelligence (ETCS-i)", - "Air conditioning w/in-cabin microfilter", - "Laminated side window glass", - "6.1L SRT V8 \"Hemi\" engine", - "Emergency interior trunk release", - "Pwr front windows w/(1) touch up/down feature" - ], - "doors": 1, - "mileage": 46691, - "kilometrage": 46274, - "license_plate": "LHF-3547" - }, - { - "id": 8748, - "uid": "851921f5-6852-4123-a036-0ca18033fb63", - "vin": "FTNSKPKTK1WP52284", - "make_and_model": "Audi A4", - "color": "Red", - "transmission": "CVT", - "drive_type": "4x4/4-wheel drive", - "fuel_type": "Electric", - "car_type": "Wagon", - "car_options": [ - "Power Locks", - "Airbag: Side", - "MP3 (Single Disc)", - "Airbag: Driver", - "Integrated Phone" - ], - "specs": [ - "Quadra-Trac active on demand 4WD system", - "160-amp alternator", - "Rear bench seat -inc: (3) adjustable headrests", - "Compact spare tire", - "Steel side-door impact beams", - "Variable intermittent windshield wipers w/mist function", - "Body color sill extension" - ], - "doors": 1, - "mileage": 84771, - "kilometrage": 67072, - "license_plate": "TFX-1160" - } -] \ No newline at end of file + { + "drive_type": "4x2/2-wheel drive", + "color": "Blue", + "car_options": [ + "Moonroof/Sunroof", + "Rear Window Wiper", + "AM/FM Stereo", + "Moonroof/Sunroof", + "Keyless Entry" + ], + "make_and_model": "Audi A7", + "car_type": "Wagon", + "doors": 1, + "uid": "49eb2aec-92ff-4aac-acae-c99b03fc2740", + "specs": [ + "Universal garage door opener", + "Battery saver", + "12V pwr outlet", + "Floor carpeting", + "Tire pressure monitoring display" + ], + "transmission": "Manual", + "license_plate": "ETZ-4908", + "kilometrage": 37444, + "vin": "RNGN1JVX82ED73304", + "id": 1881, + "fuel_type": "Compressed Natural Gas", + "mileage": 18499 + }, + { + "drive_type": "4x4/4-wheel drive", + "color": "Grey", + "car_options": [ + "Alarm", + "Tinted Glass", + "Cruise Control", + "Cassette Player", + "Power Windows", + "Cassette Player" + ], + "make_and_model": "Ford Fiesta", + "car_type": "Regular Cab Pickup", + "doors": 1, + "uid": "b3f2d364-b310-4e69-b1cb-233dab19e0d1", + "specs": [ + "Cargo area lamp", + "Highline door trim panel", + "Center console", + "Body color door handles", + "Rear body-color spoiler", + "Center console", + "Security alarm" + ], + "transmission": "Manual", + "license_plate": "QGV-8818", + "kilometrage": 81519, + "vin": "Y8EPHPMREBKS78282", + "id": 8764, + "fuel_type": "Gasoline Hybrid", + "mileage": 25511 + }, + { + "drive_type": "4x2/2-wheel drive", + "color": "Orange", + "car_options": [ + "Moonroof/Sunroof", + "Rear Window Defroster", + "Rear Window Defroster", + "Premium Sound", + "Airbag: Side", + "Rear Window Wiper", + "A/C: Rear", + "Alloy Wheels", + "Premium Sound" + ], + "make_and_model": "Honda CR-V", + "car_type": "Crew Cab Pickup", + "doors": 1, + "uid": "9df611f6-60ef-4eaf-95a9-0253d287735e", + "specs": [ + "Tachometer", + "Deluxe insulation group", + "Vehicle dynamics integrated management (VDIM) system -inc: vehicle stability control (VSC), traction control (TRAC)", + "Electrochromic pwr folding heated mirrors w/memory -inc: puddle lamps, integrated turn signals, auto reverse tilt-down", + "Side-impact door beams" + ], + "transmission": "Automanual", + "license_plate": "RGC-7001", + "kilometrage": 63756, + "vin": "PE7YPXAN27CM06466", + "id": 1542, + "fuel_type": "Compressed Natural Gas", + "mileage": 33946 + }, + { + "drive_type": "4x2/2-wheel drive", + "color": "Violet", + "car_options": [ + "Power Locks", + "Fog Lights", + "Antilock Brakes", + "Integrated Phone", + "DVD System", + "Bucket Seats", + "Power Locks", + "MP3 (Multi Disc)" + ], + "make_and_model": "BMW M3", + "car_type": "Crew Cab Pickup", + "doors": 1, + "uid": "d02f7c5e-812d-4251-bd81-b01e6b8efa6d", + "specs": [ + "Trim-panel-mounted storage net", + "Electronic throttle control system w/intelligence (ETCS-i)", + "Air conditioning w/in-cabin microfilter", + "Laminated side window glass", + "6.1L SRT V8 \"Hemi\" engine", + "Emergency interior trunk release", + "Pwr front windows w/(1) touch up/down feature" + ], + "transmission": "Manual", + "license_plate": "LHF-3547", + "kilometrage": 46274, + "vin": "PDL2JHLPMMDJ97457", + "id": 2177, + "fuel_type": "Gasoline", + "mileage": 46691 + }, + { + "drive_type": "4x4/4-wheel drive", + "color": "Red", + "car_options": [ + "Power Locks", + "Airbag: Side", + "MP3 (Single Disc)", + "Airbag: Driver", + "Integrated Phone" + ], + "make_and_model": "Audi A4", + "car_type": "Wagon", + "doors": 1, + "uid": "851921f5-6852-4123-a036-0ca18033fb63", + "specs": [ + "Quadra-Trac active on demand 4WD system", + "160-amp alternator", + "Rear bench seat -inc: (3) adjustable headrests", + "Compact spare tire", + "Steel side-door impact beams", + "Variable intermittent windshield wipers w/mist function", + "Body color sill extension" + ], + "transmission": "CVT", + "license_plate": "TFX-1160", + "kilometrage": 67072, + "vin": "FTNSKPKTK1WP52284", + "id": 8748, + "fuel_type": "Electric", + "mileage": 84771 + } +] diff --git a/src/test/resources/json/single_random_vehicle.json b/src/test/resources/json/single_random_vehicle.json index 7841abff..b39ae702 100644 --- a/src/test/resources/json/single_random_vehicle.json +++ b/src/test/resources/json/single_random_vehicle.json @@ -1,36 +1,36 @@ { - "id": 2536, - "uid": "33cd6af4-249c-4526-a644-a289df123f45", - "vin": "SLADNPPPFAPV10007", - "make_and_model": "Audi A4", - "color": "Red", - "transmission": "Automanual", - "drive_type": "4x2/2-wheel drive", - "fuel_type": null, - "car_type": "Regular Cab Pickup", - "car_options": [ - "Rear Window Defroster", - "Moonroof/Sunroof", - "Third Row Seats", - "Alloy Wheels", - "Cruise Control", - "A/C: Rear", - "AM/FM Stereo", - "Bucket Seats", - "Alarm", - "", - null - ], - "specs": [ - "Body color fascias w/bright insert", - "Chrome bodyside molding", - "Tire pressure monitoring system (TPMS)", - "Body color fascias w/bright insert", - "Security alarm", - "Passenger assist handles" - ], - "doors": 4, - "mileage": 12499, - "kilometrage": 40083, - "license_plate": "WKI-3540" -} \ No newline at end of file + "drive_type": "4x2/2-wheel drive", + "color": "Red", + "car_options": [ + "Rear Window Defroster", + "Moonroof/Sunroof", + "Third Row Seats", + "Alloy Wheels", + "Cruise Control", + "A/C: Rear", + "AM/FM Stereo", + "Bucket Seats", + "Alarm", + "", + null + ], + "make_and_model": "Audi A4", + "car_type": "Regular Cab Pickup", + "doors": 4, + "uid": "33cd6af4-249c-4526-a644-a289df123f45", + "specs": [ + "Body color fascias w/bright insert", + "Chrome bodyside molding", + "Tire pressure monitoring system (TPMS)", + "Body color fascias w/bright insert", + "Security alarm", + "Passenger assist handles" + ], + "transmission": "Automanual", + "license_plate": "WKI-3540", + "kilometrage": 40083, + "vin": "SLADNPPPFAPV10007", + "id": 2536, + "fuel_type": null, + "mileage": 12499 +}