0% found this document useful (0 votes)
80 views22 pages

JAVA - Coding

The document provides examples of using Java 8 streams to perform operations on collections of objects and data. It shows how to filter, map, reduce, and collect streams. Some key operations include filtering employees by age, obtaining employee names, printing results, finding employees by city, getting distinct strings, summing integers, and iterating from 0 to 50. It also demonstrates summing and averaging list elements, squaring and filtering numbers, getting even and odd numbers, filtering by starting characters, finding duplicates, getting max/min values, sorting in ascending and descending order, limiting results and summing, skipping elements and summing, and cubing numbers.

Uploaded by

Manjula OJ
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
80 views22 pages

JAVA - Coding

The document provides examples of using Java 8 streams to perform operations on collections of objects and data. It shows how to filter, map, reduce, and collect streams. Some key operations include filtering employees by age, obtaining employee names, printing results, finding employees by city, getting distinct strings, summing integers, and iterating from 0 to 50. It also demonstrates summing and averaging list elements, squaring and filtering numbers, getting even and odd numbers, filtering by starting characters, finding duplicates, getting max/min values, sorting in ascending and descending order, limiting results and summing, skipping elements and summing, and cubing numbers.

Uploaded by

Manjula OJ
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

employes.

stream()
.filter(e -> e.getAge() > 40) // filter employees with age > 40
.map(Employee::getName) // obtain each employee's name
.forEach(System.out::println); // finally, print it

I have employee and address class as below

class Employee {
private String name;
private int age;
private List<Address> addresses;
//getter and setter
}

class Address {
private String city;
private String state;
private String country;
//getter and setter
}
Using java 8 filter I want to print all employees who are having city starting with P

Distinct Strings
Collection<String> list = Arrays.asList("A", "B", "C", "D", "A", "B", "C");

Use anyMatch in filter instead of mapping :


employees.stream()
.filter(employee -> employee.getAddresses().stream()
.anyMatch(adr -> adr.getCity().startsWith("p")))
.forEach(System.out::println);

List<String> distinctElements = list.stream()


.distinct()
.boxed()
.collect(Collectors.toList());

Distinct integers
List<Integer> input = Arrays.asList(3,12,11,45,12,5,3,9,20,11,3);
System.out.print("Input:");
input.forEach(num -> System.out.print(num+" "));
System.out.println();
System.out.print("Output:");
List<Integer> distinctInput = input.stream().distinct().collect(Collectors.toList());
distinctInput.forEach(num -> System.out.print(num+" "));
##=s+I; Add the sum till 50

Int s=0;
For(int I =0;i<50;i++){
S = s+I;

IntStream.rangeClosed(1, 8)
.map(i -> 2 * i - 1)
.forEach(System.out::println);

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.*;

import java.util.Optional;

public class Java8Stream {

public static void main(String[] args) {

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int sum = integers.stream().mapToInt(Integer::intValue).sum();

System.out.println("Total : " + sum);

List<Integer> integersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Optional<Integer> sumList = integersList.stream().reduce((a,b)->a+b);

System.out.println("Total sumList-- : " + sumList);

int sum1 = 0;
for (int value : integers) {

sum1 += value;

System.out.println("Total : " + sum1);

int s=0;

for(int i =0;i<50;i++){

s=s+i;

System.out.println("Total :: " + s);

// Convert to java 8 for(int i:0 to 50)

Stream<Integer> integers2 = Stream.iterate(0, n -> n + 1).limit(50);

IntStream intStream = (integers2.mapToInt(x -> x));

int sum12 = intStream.sum();

System.out.println("Total Sum-- : " + sum12);

Input - 1
Assume you are given a list of numbers like {1,7,8,9,5,2,36,4,78,222,24,9}
Answers
1) Given a list of numbers, return the sum of all numbers.

Approach: We can use reduce() method whenever we want to produce a single


resultant value as output, for example, maximum, minimum, sum, product, etc.

You can refer Stream.reduce for more details.

Optional<Integer> sum = list.stream().reduce((a, b) -> a+b);


System.out.println("sum is: "+sum.get());

output
2) Given a list of numbers, return the average of all numbers

Approach: We can use mapToInt() followed by average() whenever we want to


perform an average on the list of integers.

output
3) Given a list of numbers, square them and filter the numbers which are
greater 100 and then find the average of them

Approach: Here we need to do 3 things

 We need to square each number ( We can use map())


 Filter whose value is greater than 100 (we can use filter())
 Find average of those (we can use mapToInt() and average() together)

If we look at the numbers, only 36, 78, 222, 24 squares are greater than 100.

 (1296 + 6084 + 49284 + 576)/4 = 14310.0

output
4) Given a list of numbers, return the even and odd numbers separately

Approach: We can use filter() and Collectors.toList() to get both even and odd
numbers as two separate lists.

Even Numbers:

output
Odd Numbers

output
5) Given a list of numbers, find out all the numbers starting with 2

Approach: Here we need to do 4 things

 Convert Integer to String to perform startsWith operation on it


 Filter the strings that starts with 2
 Convert String to Integer on filtered data
 Collect the final Integers as List and store

output
6) Given a list of numbers, print the duplicate numbers

Approach 1: Using frequency() method of Collections class. It counts the frequency


of the specified element in the given list. If count > 1 then that element is duplicate
one

output

duplicates: [9]

Approach 2: Using Set to collect only duplicates.


output

duplicates: [9]

7) Given a list of numbers, print the maximum and minimum values

Approach: Using max() and min() we can get maximum and minimum values from
a list along with Comparator.comparing().

Maximum Value:

output

Maximum Value: 222

Minimum Value:

output

Minimum Value: 1

8) Given a list of numbers, sort them in ASC and DESC order and print

Approach: Using sorted(), We can sort a list in ASC or DESC order.

ASC Order
output

ASC Order: [1, 2, 4, 5, 7, 8, 9, 9, 24, 36, 78, 222]

DESC Order

output

DESC Order: [222, 78, 36, 24, 9, 9, 8, 7, 5, 4, 2, 1]

9) Given a list of numbers, return the first 5 elements and their sum

Approach: We can use limit() followed by reduce().

First 5 Elements

output
First 5 Elements Sum

output

first5elementsSum: 30

10) Given a list of numbers, skip the first 5 numbers and return the sum of the
remaining numbers

Approach: We can use skip() to skip the first n numbers in a list.


output

Sum after first 5 elements skip: 375

11) Given a list of numbers, return the cube of each number

Approach: We can use map() here.

List<Integer> cubes = list.stream().map(num -> num*num*num).collect(Collectors.toList());


System.out.println("Cubes: "+cubes);

output

Cubes: [1, 343, 512, 729, 125, 8, 46656, 64, 474552, 10941048, 13824, 729]

public class TestTaker {


public static Integer find_total( Integer[] my_numbers ) {
int running_total = 0;
for (int i = 0; i < my_numbers.length; i++)
{
if(my_numbers[i] % 2 != 0)
{
if (my_numbers[i] == 5)
{
running_total += 5;
}
else
{
running_total += 3;
}
}
else
{
running_total += 1;
}
}
return running_total;
}
}

Normal string scan is possible using scnnaer , when I add int to String ,we need to use
bufferedreader

import java.util.*;
import java.io.*;
import java.lang.*;

public class Solution {

public static void main(String[] args) throws Exception{


InputStreamReader read=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(read);

int n=Integer.parseInt(br.readLine());

double d=Double.parseDouble(br.readLine());

String name=br.readLine();

System.out.println("String: "+name);
System.out.println("Double: "+d);
System.out.println("Int: "+n);
/** Scanner scan = new Scanner(System.in);
int i=0; ;
Double d = 0.0;
// String s = "";
// Write your code here.
while (scan.hasNextInt()) {
i= scan.nextInt();
}
while (scan.hasNextDouble()) {
d= scan.nextDouble();
}

String s = "";
while(scan.hasNext()){
s = s.concat(scan.next());
if(scan.hasNext()){
s = s.concat(" ");
}
}
//String s = scan.nextLine();
System.out.println("String: " + s );
System.out.println("Double: " + d);
System.out.println("Int: " + i);
scan.close();
**/
}
}

String s1=sc.next();
int x=sc.nextInt();
//Complete this line
System.out.printf("%-15s%03d%n",s1,x);

• Good knowledge of Java, Dependency Injection (Spring), Hibernate and Web Services.

• RDMS experience an advantage.

• Containerisation (Docker), Message Broker (RabbitMQ) and Microservice knowledge an advantage.

financial contract that is arranged between


Working on trading application,
two counterparties but with minimal intermediation or regulation
OTC derivates rates, credit, default swap, swap, hedge funds, equity, fixed income asset,

Working on new enhancements in Aggrisk, which is used for displaying Profit and Loss, and Risk
data in Live , intraday and EOD mode of foreign exchange and local market using Ag-grid and
following the regulatory components.
Eod we will send an email to team and BOD regd, the trade which are completed ,@risk , what si
the profit n loss incurred for the day .

Portfolio maintenance – IAM security and Identity management – users , roles, access to
websites, copy from emp ,
PAM (Privileged access management ), IGA identity governance solution.
, Spectre,
Service Now request – application – filter out the message in core dir queue many request
we will get like iam, core dir,
1. Webservice sampl
2. Docker file template
3. Rest sample
4. Java 8,9 ,11, 17 features

Java 9
1.ArrayList to toArray before we use for each-
2. New utility methods in String class – repeat,isLines, isBlank – check for
whitespaces and empty string – return true,
stripLeading(): It is used to remove the white space at beginning of string

stripTrailing(): It is used to remove the white space at begining of the string


strip (): It is used to remove the white space at end and begin of the string.
3. var , Local-Variable Syntax for Lambda Parameters:
(exp) -> {(return or set of statements);}
Only (var a,var b) allowed as parameter,
*single var not allowed, we have to use both param as var or use as in java8
and var s1 -> s1 //not allowed. Need parentheses if you use var in lambda.
()should be there.
(var s1, s2) -> s1 + s2 //no skipping allowed
(var s1, String y) -> s1 + y //no mixing allowed
var s1 -> s1 //not allowed. Need parentheses if you use var in lambda

4.Pattern Recognizing Methods:

asMatchPredicate(): This method will create a predicate if the pattern matches


with the input string

var str = Pattern.compile("aba").asMatchPredicate();


System.out.println(str.test("aba")); //it returns true if pattern matched
else it returns false Output: true

Optional.isEmpty(): This method returns true if the value of any object is null and
else returns false.

Optional str = Optional.empty();System.out.println(str.isEmpty());Output:


true

TimeUnit Conversion: This method is used to convert the given time to a unit like
DAY, MONTH, YEAR, and for time too

Lets try converting Days into Minutes:


TimeUnit c1 = TimeUnit.MINUTES;

System.out.println(c1.convert(Duration.ofDays(3)));

Output:4320

Hope you understand above example like wise you can convert minutes to
hours ,seconds to days and many more scenarios which ever is possible.

5.Reading/Writing Strings to and from the Files:

It has introduced the following methods for reading and writing to/from the files

writeString(): This method is used to write some content in a file.

Files.writeString(Path.of(“D:\test.txt”), “AnilAppana”)

Using above code we are able to insert some text into file at that location but what
if we want to read data from it check below snippet

readString(): This method is used to read the contents of a file.

String s1 = Files.readString(Path.of("D:\\test.txt"));

Console Output:
isSameFile(): This method is used to know whether two paths locate the same file
or not, isSameFile() returns boolean value if files are sae it returns true if files are
no matched it returns false

public class Lines {

public static void main(String[] args) {

String str = "JD\nJD\nJD";

System.out.println(str);

System.out.println(str.lines().collect(Collectors.toList())

}}

Console Output:

6.Nested Based Access Control:


ava 11 introduced nest-based access control that allows classes to access each
other’s private members without the need for bridge methods created by the
compiler. These methods are called accessibility-broadening bridge methods and
the compiler inserts these into the code during the program execution.

Before Java 11, if we have private members in our code then the compiler creates
accessibility-broadening bridge methods that increase the size of the deployed
applications and may lead to confusion. That’s why Java improved nest-based
access control.

Java 11 allows classes and interfaces to be nested within each other. These nested
type can be private fields, methods, and constructors

7.HTTP Client:

The new HTTP client from the java.net.http package was introduced in Java 9. It
has now become a standard feature in Java 11.

The new HTTP API improves overall performance and provides support for both
HTTP/1.1 and HTTP/2

💡 Post #7 - Springboot Annotations

I am running a series, where I share interesting topics that every developer should know about.

( To follow - https://lnkd.in/d62YuzpW )

1. @SpringBootApplication
- This annotation is a combination of @Configuration, @EnableAutoConfiguration, &
@ComponentScan.
- It is used to configure a Spring Boot application, including its dependencies, beans, and
configuration.

2. @RestController
- This annotation is used to create a RESTful web service that is capable of handling HTTP
requests and sending HTTP responses.

3. @Autowired
- This annotation is used to inject dependencies into a class or a bean.

4. @Service
- This annotation is used to indicate that a class is a service layer component.

5. @Repository
- This annotation is used to indicate that a class is a data access layer component.

6. @Controller
- This annotation is used to indicate that a class is a web controller.

7. @Configuration
- This annotation is used to define a class as a configuration class. It is used to configure beans
and other settings in the Spring application context.

8. @Value
- This annotation is used to inject values from properties files or other sources into a bean.

9. @ComponentScan
- This annotation is used to specify the base package(s) for component scanning.

10. @ConditionalOnProperty
- This annotation is used to conditionally enable/disable certain features based on properties.

11. @Scheduled
- This annotation is used to schedule tasks in a Spring Boot application.

12. @EnableScheduling
- This annotation is used to enable scheduling in a Spring Boot application.

13. @Transactional
- This annotation is used to indicate that a method or a class should be executed within a
transaction.

14. @Cacheable
- This annotation is used to cache the results of expensive method calls.

15. @PostConstruct
- This annotation is used to annotate a method that should be executed after a bean is initialized.

16. @PreDestroy
- This annotation is used to annotate a method that should be executed before a bean is
destroyed.
17. @ExceptionHandler
- This annotation is used to handle exceptions in a RESTful web service.

18. @ResponseBody
- This annotation is used to indicate that a method should return the HTTP response body.

19. @PathVariable
- This annotation is used to extract a variable from a URL path.

20. @RequestBody
- This annotation is used to extract the request body from an HTTP request.

21. @EnableConfigurationProperties
- This annotation is used to enable configuration properties binding to a bean.

22. @Bean: This annotation is used to define a bean in the Spring application context.

23. @ResponseStatus
- This annotation is used to specify the HTTP response status code for an exception.

24. @ConfigurationProperties
- This annotation is used to bind externalized configuration properties to a bean.

👉 Doc by jrebel

You might also like