sorted() - intermediate - used to sort the elements
public class Main {
public static void main(String...args) {
List<String> l=List.of("9","A","z","1","B","4","e","f");
List<String> l2=l.stream().sorted().collect(Collectors.toList());
System.out.println(l2); //asc order [1, 4, 9, A, B, e, f, z]
List<String> l3=l.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(l3); //desc order
List<Student> l1=new ArrayList<>();
l1.add(new Student(23,"PK"));
l1.add(new Student(26,"KK"));
l1.add(new Student(22,"MK"));
l1.add(new Student(21,"SK"));
l1.add(new Student(20,"AK"));
l1.add(new Student(33,"TK"));
l1.add(new Student(24,"BK"));
l1.add(new Student(25,"GK"));
l1.add(new Student(27,"DK"));
//comparingInt(), comparingDouble(),comparingLong()
List<Student> l4=l1.stream().sorted(Comparator.comparingInt(Student::getId))
.collect(Collectors.toList());
l4.forEach(System.out::println); //sort student based on id in asc order
System.out.println();
List<Student> l5=l1.stream().sorted(Comparator.comparing(Student::getName).reversed())
.collect(Collectors.toList());
l5.forEach(System.out::println); //sort student based on name in desc order
}
}
Other ways to create stream
1. builder() - create finite stream
2. generate(Supplier) - create infinite stream
3. iterate(int initialvalue, UnaryOperator) - create infinite stream
Create streams based on primitive datatype
1. IntStream - create stream based on int values
2. DoubleStream - create stream based on double values
3. LongStream - create stream based on long values
Collectors.summarizingInt() - summarize all int info like count, max, min, avg, sum
Collectors.summarizingDouble() - summarize all double info like count, max, min, avg, sum
Collectors.summarizingLong() - summarize all long info like count, max, min, avg, sum
From JDK1.9
takeWhile(Predicate) - intermediate - if stream does not match the predicate, it will discard the rest of values
dropWhile(Predicate)- intermediate - if stream does not match the predicate, it will print the rest of values
public class Main {
public static void main(String...args) {
Stream<String> st1=Stream.<String>builder().add("Ram").add("Sam").add("Tam").build();
st1.forEach(System.out::println);
Stream<Integer> st2=Stream.<Integer>builder().add(10).add(20).add(30).build();
st2.forEach(System.out::println);
Stream<String> st3=Stream.generate(()->"hello").limit(5);
st3.forEach(System.out::println);
Stream<Integer> st4=Stream.iterate(2, (i)->i*2).skip(2).limit(5);
st4.forEach(System.out::println);
IntStream i1=IntStream.range(1, 6); //start to end-1
i1.forEach(System.out::println); //1 2 3 4 5
IntStream i2=IntStream.rangeClosed(1, 6); //start to end
i2.forEach(System.out::println); //1 2 3 4 5 6
IntStream i3="ABCD".chars();
i3.forEach(System.out::println); //65 66 67 68
Random r=new Random();
DoubleStream d1=r.doubles(5);
d1.forEach(System.out::println);
List<Student> l1=new ArrayList<>();
l1.add(new Student(23,"PK"));
l1.add(new Student(26,"KK"));
l1.add(new Student(22,"MK"));
l1.add(new Student(21,"SK"));
l1.add(new Student(20,"AK"));
l1.add(new Student(33,"TK"));
l1.add(new Student(24,"BK"));
l1.add(new Student(25,"GK"));
l1.add(new Student(27,"DK"));
IntStream i4=l1.stream().mapToInt(Student::getId);
i4.forEach(System.out::println);
OptionalInt op1=l1.stream().mapToInt(Student::getId).max();
System.out.println(op1.getAsInt()); //33
OptionalDouble op2=l1.stream().mapToInt(Student::getId).average();
System.out.println(op2.getAsDouble()); //24.555555555555557
int s=l1.stream().mapToInt(Student::getId).sum();
System.out.println(s);
//IntSummaryStatistics, DoubleSummaryStatistics,LongSummaryStatistics
IntSummaryStatistics i5=l1.stream().collect(Collectors.summarizingInt(Student::getId));
System.out.println(i5);
System.out.println(i5.getSum()+" "+i5.getCount());
// DoubleSummaryStatistics d2=l1.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
Stream.of(2,4,6,8,9,10,12).takeWhile(e->e%2==0).forEach(System.out::println); //2 4 6 8
Stream.of(2,4,6,8,9,10,12).dropWhile(e->e%2==0).forEach(System.out::println); //9 10 12
}
}
ParallelStream
- We want to access the stream elements parallelly
- If we create stream using of(), then to access parallelly we have to use parallel()
- If we create stream from some source by stream(), then to access parallelly we have to use parallelStream()
public class Main {
public static void main(String...args) {
/*Stream.of(1,2,3,4,5,6,7,8,9).forEach(n -> {
System.out.println(Thread.currentThread().getName()+" "+n);
});*/
/* Stream.of(1,2,3,4,5,6,7,8,9).parallel().forEach(n -> {
System.out.println(Thread.currentThread().getName()+" "+n);
}); */
/*Stream.of(1,2,3,4,5,6,7,8,9).parallel().forEachOrdered(n -> {
System.out.println(Thread.currentThread().getName()+" "+n);
});*/
List<Integer> l1=List.of(1,2,3,4,5,6,7,8,9);
l1.parallelStream().forEachOrdered(n -> {
System.out.println(Thread.currentThread().getName()+" "+n);
});
}
}
Before JDK1.8, Date class is present in java.util.* package
1. Date class
- print current date and time
1. Date() - print current date and time
2. Date(long msec) - print date and time from Jan 1st 1970
2. Calendar class
- abstract class, used to extract useful components from date and time
3. GregorianCalendar class - it is concrete implementation(we can create an object) of Calendar class, used to extract useful components from date and time
4. DateFormat class - present in java.text.* package
- abstract class, used for formatting(convert date to string and display in different format like SHORT, MEDIUM, LONG, FULL) and parsing(convert string to date)
5. SimpleDateFormat - present in java.text.* package
- concrete implementation(we can create an object) of DateFormat class, used for formatting(convert date to string and display in different format like SHORT, MEDIUM, LONG, FULL and also our own format) and parsing(convert string to date)
public class Main {
public static void main(String...args) {
Date d1=new Date();
System.out.println(d1); //Mon Sep 01 11:53:15 IST 2025
Date d2=new Date(1000000);
System.out.println(d2); //Thu Jan 01 05:46:40 IST 1970
Calendar c=Calendar.getInstance(); //current date and time
System.out.println(c.get(Calendar.YEAR)); //2025
System.out.println(c.get(Calendar.MONTH)); //8 starts from 0
String month[]= {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
System.out.println(month[c.get(Calendar.MONTH)]); //Sep
System.out.println(c.get(Calendar.DAY_OF_MONTH)); //1
System.out.println(c.get(Calendar.DAY_OF_YEAR)); //244
//GregorianCalendar g=new GregorianCalendar(); //current date and time
GregorianCalendar g=new GregorianCalendar(2000,10,23,13,14,15);
System.out.println(g.get(Calendar.MINUTE)); //14
System.out.println(g.get(Calendar.YEAR)); //2000
DateFormat df=DateFormat.getInstance(); //default in SHORT style
System.out.println(df.format(d1));
DateFormat df1=DateFormat.getDateInstance(); //default in MEDIUM style
System.out.println(df1.format(d1));
DateFormat df2=DateFormat.getDateInstance(DateFormat.LONG);
System.out.println(df2.format(d1));
df2=DateFormat.getTimeInstance(); //default in MEDIUM style
System.out.println(df2.format(d1));
df2=DateFormat.getTimeInstance(DateFormat.FULL);
System.out.println(df2.format(d1));
df2=DateFormat.getDateTimeInstance(); //default date and time in MEDIUM style
System.out.println(df2.format(d1));
df2=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.FULL);
System.out.println(df2.format(d1));
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
String str="10/12/2000";
try {
Date d3=sdf.parse(str);
System.out.println(d3);
System.out.println(sdf.format(d3));
}catch(ParseException e) {
System.out.println(e);
}
}
}
Date API
- Available from JDK1.8
- present in java.time.* package
- Date is immutable class whereas lower version of date is mutable
class and interface
1. LocalDate class - print only date in yyyy-MM-dd format
2. TemporalAdjuster interface - used to get extra info abt date and time - we have to use with()
3. LocalTime class - print only time in hh:mm:ss format
4. LocalDateTime class - print both date and time
5. Period class - used to find difference between 2 dates
6. Duration class - used to find difference between 2 time
7. DateTimeFormatter interface - used to print date and time in our own format
public class Main {
public static void main(String...args) {
LocalDate l1=LocalDate.now(); //current date
System.out.println(l1); //2025-09-01
Clock c=Clock.systemDefaultZone();
LocalDate l2=LocalDate.now(c);
System.out.println(l2);
ZoneId z=ZoneId.of("America/Chicago");
LocalDate l3=LocalDate.now(z);
System.out.println(l3);
LocalDate l4=LocalDate.of(2000, 10, 20); //create our own date
System.out.println(l4); //2000-10-20
LocalDate l5=LocalDate.parse("2000-10-20"); //convert string to date
System.out.println(l5);
LocalDate l6=l5.plusMonths(2);
System.out.println(l6); //2000-12-20
LocalDate l7=l6.plus(4, ChronoUnit.YEARS);
System.out.println(l7); //2004-12-20
LocalDate l8=l7.minusDays(200);
System.out.println(l8); //2004-06-03
LocalDate l9=l8.minus(10, ChronoUnit.WEEKS);
System.out.println(l9);
DayOfWeek d1=LocalDate.parse("2025-09-01").getDayOfWeek();
System.out.println(d1); //Monday
int m1=LocalDate.parse("2025-09-01").getDayOfMonth();
System.out.println(m1); //1
int y1=LocalDate.parse("2025-09-01").getDayOfYear();
System.out.println(y1); //244
System.out.println(l9.isLeapYear());
boolean b1=LocalDate.parse("2025-09-01").isAfter(LocalDate.parse("2025-08-01"));
System.out.println(b1); //true
boolean b2=LocalDate.parse("2025-09-01").isBefore(LocalDate.parse("2025-08-01"));
System.out.println(b2); //false
boolean b3=LocalDate.parse("2025-09-01").isEqual(LocalDate.parse("2025-08-01"));
System.out.println(b3); //false
LocalDate l10=LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
System.out.println(l10); //2025-09-01
LocalDate l11=LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
System.out.println(l11); //2025-09-30
LocalDate l12=LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
System.out.println(l12); //2025-09-03
LocalDate l13=LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
System.out.println(l13); //2025-08-31
LocalTime t1=LocalTime.now(); //current time
System.out.println(t1);
LocalTime t2=LocalTime.now(c);
System.out.println(t2);
LocalTime t3=LocalTime.now(z);
System.out.println(t3);
LocalTime t4=LocalTime.of(9, 30); //create our own time
System.out.println(t4); //09:30
LocalTime t5=LocalTime.parse("09:30"); //convert string to time
System.out.println(t5);
LocalTime t6=t5.plusMinutes(20);
System.out.println(t6);
LocalTime t7=t6.plus(4, ChronoUnit.HOURS);
System.out.println(t7);
LocalTime t8=t7.minusSeconds(2000);
System.out.println(t8);
LocalTime t9=t8.minus(20000,ChronoUnit.NANOS);
System.out.println(t9);
System.out.println(LocalTime.MAX);
System.out.println(LocalTime.MIN);
System.out.println(LocalTime.MIDNIGHT);
LocalDateTime ld1=LocalDateTime.now(); //current date and time
System.out.println(ld1); //2025-09-01T12:36:24
LocalDateTime ld2=LocalDateTime.of(LocalDate.now(),LocalTime.now());
System.out.println(ld2);
LocalDateTime ld3=LocalDateTime.parse("2025-01-02T10:20:30");
System.out.println(ld3);
System.out.println(ld3.toLocalDate());
System.out.println(ld3.toLocalTime());
System.out.println(LocalDateTime.MAX);
System.out.println(LocalDateTime.MIN);
//convert JDK1.5 Date to LocalDate
Date dt=new Date();
LocalDateTime ld4=LocalDateTime.ofInstant(dt.toInstant(), ZoneId.systemDefault());
System.out.println(ld4);
//convert Calendar to LocalDate
Calendar c2=Calendar.getInstance();
LocalDateTime ld5=LocalDateTime.ofInstant(c2.toInstant(), ZoneId.systemDefault());
System.out.println(ld5);
LocalDate l14=LocalDate.now();
LocalDate l15=LocalDate.of(2000, 10, 20);
int diff=Period.between(l14, l15).getDays();
System.out.println(diff);
int diff1=Period.between(l14, l15).getYears();
System.out.println(diff1);
long l=ChronoUnit.MONTHS.between(l14, l15);
System.out.println(l);
LocalTime t10=LocalTime.now();
LocalTime t11=LocalTime.of(9, 30);
long du1=Duration.between(t10, t11).getSeconds();
System.out.println(du1);
long du2=Duration.between(t10, t11).toMinutes();
System.out.println(du2);
long du3=Duration.between(t10, t11).toHours();
System.out.println(du3);
long du4=ChronoUnit.MINUTES.between(t10, t11);
System.out.println(du4);
LocalDateTime ld6=LocalDateTime.now();
System.out.println(ld6);
String s1=ld6.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(s1);
String s2=ld6.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
System.out.println(s2);
String s3=ld6.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
System.out.println(s3);
String s4=ld6.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG));
System.out.println(s4);
String s5=ld6.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL,FormatStyle.SHORT));
System.out.println(s5);
}
}
Optional class
- objects will contain memory reference or null reference, so if we access anything with null reference we get NullPointerException
- To avoid unexpected NPE we have to write some logic to do null check, so in order to avoid unpredictable NPE we can use a class called Optional class
- present in java.util.* package
Methods
1. static Optional empty() - create empty optional
2. static Optional of(T...t) - return non empty optional, if value is null it returns NPE
3. static Optional ofNullable(T...t) - return non empty optional, if value is null it returns Optional.empty
4. Object get() - return original value from Optional object
5. boolean isPresent() - return true if value is present otherwise false
6. void ifPresent(Consumer) - if value is present then it invokes the Consumer object
7. Object orElse(object) - return the value if present otherwise it returns other value
8. Object orElseGet(Supplier) - return the value if present otherwise it invokes another logic defined by Supplier and return the result
9. Object orElseThrow(Supplier) - return the value if present otherwise it throws an exception
public class Main {
public static void main(String...args) throws Throwable {
Optional op1=Optional.empty();
System.out.println(op1); //Optional.empty
Optional op2=Optional.of("John");
System.out.println(op2); //Optional[John]
//Optional op2=Optional.of(null);
//System.out.println(op2); //NPE
Optional op3=Optional.ofNullable("Jim");
System.out.println(op3);//Optional[Jim]
Optional op4=Optional.ofNullable(null);
System.out.println(op4); //Optional.empty
Optional op5=Optional.ofNullable("Jimmy");
System.out.println(op5);//Optional[Jimmy]
System.out.println(op5.get()); //Jimmy
Optional op6=Optional.of("Jack");
System.out.println(op6.get()); //Jack
System.out.println(op6.isPresent()); //true
Optional op7=Optional.empty();
System.out.println(op7.isEmpty()); //true
System.out.println(op7.isPresent()); //false
Optional op8=Optional.of("Johny");
// System.out.println(op8.get()); //Johny
op8.ifPresent(System.out::println); //Johny
Optional op9=Optional.empty();
System.out.println(op9); //optional.empty
System.out.println(op9.orElse("Peter")); //Peter
System.out.println(op9.orElseGet(()->"Tim")); //Tim
System.out.println(op9.orElseThrow(NullPointerException::new));
}
}
Handson
1.Display Date
Given a date in the form of string, write a program to convert the given string to date .
Include a class UserMainCode with a static method displayDate which accepts a string. In this method display the given string in date format yyyy-MM-dd. The return type is void.
Create a Class Main which would be used to accepts a string and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of Date.
Refer sample output for formatting specifications.
Sample Input 1:
May 1, 2016
Sample Output 1:
2016-05-01
Sample Input 2:
March 21, 2016
Sample Output 2:
2016-03-21
2.Extract Date and time
Write a program to extract date and time from the input string which is in yyyy-MM-dd HH:mm:ss date format.
Include a class UserMainCode with a static method displayDateTime which accepts a string. In this method display date and time in the format as given in sample input and output . The return type is void.
Create a Class Main which would be used to accept string and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output should be in date format
Refer sample output for formatting specifications.
Sample Input :
Enter String in this format(yyyy-MM-DD HH:mm:ss)
2016-07-14 09:00:02
Sample Output :
07/14/2016, 9:00:02
3.Day Of The Year
Given a date, write a program to display day of the year.
Include a class UserMainCode with a static method displayDay which accepts a date. In this
method, display day in the format as given in sample input and output . The return type is void.?
?Input date Format is yyyy-MM-dd
Create a Class Main which would be used to accept date and call the static method present in
UserMainCode.?
?
Input and Output Format:?
Input consists of a string.
Refer sample output for formatting specifications.
Sample Input :
2013-03-23
Sample Output :
Day of year: 82
4.Name Of the Day
Given a date in the date format, write a program to get the day of the corresponding date .
Include a class UserMainCode with a static method displayDay which accepts a date. In this method display the day of given date . The return type is void.
Create a Class Main which would be used to accept a date and call the static method present in UserMainCode.
?Input date Format is yyyy-MM-dd
Input and Output Format:
Input consists of a date.
Refer sample output for formatting specifications.
Sample Input 1:
2011-10-21
Sample Output 1:
Friday
Sample Input 2:
2011-07-11
Sample Output 2:
Monday
5.Difference between dates in month
Given a method with two date strings in yyyy-mm-dd format as input. Write code to find the difference between two dates in months.
Include a class UserMainCode with a static method getMonthDifference which accepts two date strings as input.
The return type of the output is an integer which returns the diffenece between two dates in months.
Create a class Main which would get the input and call the static method getMonthDifference present in the UserMainCode.
Input and Output Format:
Input consists of two date strings.
Format of date : yyyy-mm-dd.
Output is an integer.
Refer sample output for formatting specifications.
Sample Input 1:
2012-03-01
2012-04-16
Sample Output 1:
1
Sample Input 2:
2011-03-01
2012-04-16
Sample Output 2:
13
No comments:
Post a Comment