Java 8

¡Supera tus tareas y exámenes ahora con Quizwiz!

What are java 8 features?

-Functional Interfaces and Lambda Expressions. · Java Stream API For Bulk Data Operations On Collections. · forEach() Method In Iterable Interface. · Optional Class. · Default and Static Methods In Interfaces. · Java Date Time API. · Collection API Improvements. · Java IO Improvements

Can a functional interface extend another functional interface?

A functional interface can extends another interface only when it does not have any abstract method.

What are functional interfaces?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods.

Write a method to run second largest number in an array/list, use only java 8 features

ArrayList<Integer> al = new ArrayList<>(); al.add(10);al.add(15);al.add(8);al.add(49);al.add(25);al.add(98);al.add(32); al.stream().sorted(Collections.reverseOrder()).limit(2).skip(1).forEach(System.out::println);

What is parallel stream?

By using parallel streams, one can separate the Java code into more than one stream, which is executed in parallel on their separate cores, and the end result is the combination of the individual results.

What are default methods and why its required

Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces. In particular, default methods enable you to add methods that accept lambda expressions as parameters to existing interfaces

Show me one example using both lambda expression, method references in streaming API java 8 feature

Employee employee = Stream.of(empIds) .map(employeeRepository::findById) .filter(e -> e != null) .filter(e -> e.getSalary() > 100000) .findFirst() .orElse(null);

Some use cases of Stream API?

Filtering, sorting, preprocessing, conversion, reduction, grouping, finding, sorting

What is the difference between map vs flat map

Function passed to map() operation returns a single value for a single input. While flatmap() returns an arbitrary number of values as the output. If you had a list of lists, then you could use flat map to make it all one list. Map produces a stream of value and flatmap produces a stream of stream value.

What is the main reason behind functional interfaces in java 8

Functional interfaces in java contain only one abstract unimplemented method, but can have any number of default and static methods. The are used to make code more readable, clean, and straightforward.

What is predicate in java 8

In Java 8, Predicate is a functional interface, which accepts an argument and returns a boolean. Usually, it used to apply in a filter for a collection of objects

How does Hashmap work internally? What changes were made in Java8 ?

Internally HashMap uses a hashCode of the key Object and this hashCode is further used by the hash function to find the index of the bucket where the new entry can be added. In Java 8, HashMap replaces linked list with a binary tree when the number of elements in a bucket reaches certain threshold.

What types of lambda expressions are used in stream API?

Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only

Make an ArrayList of Ints then using Java8 features print the maximum in the list and then print them sorted in descending order

List<Integer> desc = listOfInts.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); System.out.println("Max: " + desc.get(0)); For(int I = 1; I < desc.size(); I++){ System.out.println(desc.get(i)); }

String str = "aabbcdeaa" and display - a = 4 b=2 c=1 d=1 e=1

Map<Character, Integer> map = new Stream.of(str).collect(Collectors.toMap(Function.identity(), value->1, Integer::sum));

Write a java 8 code to display average salaries of female employees of given list

Map<String, Double> avgSalaryOfFemaleEmployees = employeeList.stream() .filter(e -> e.getGender().equals("Female") .collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingDouble(Employee::getSalary))); System.out.println(avgSalaryOfFemaleEmployees);

What is functional programming and how to implement it in java?

Programming using expressions i.e. declaring functions, passing functions as arguments and using functions as statements (rightly called expressions in Java8) The basic objective of functional programming is to make code more concise, less complex, more predictable, and easier to test compared to the legacy style of coding Java 8 provides many features to implement functional programming.

write a java code to square of odd numbers from 1 to 20 (using java 8 features)

Stream.iterate(1, x -> x+ 1).filter(x->x%2!=0).map(x->x*x).limit(20);

Make a stream of cubes of numbers from 1 to 100 [using java 8 features]

Stream.iterate(1, x->x+1).map(x->x*x*x).limit(100).forEach(System.out::println);

Write a java code to display reverse of given string without duplicates

String str = "hello"; StringBuilder sb = new StringBuilder(str).chars().distinct().forEach(c -> sb.append((char) c))); system.out.println(sb.reverse().toString());

What is the diff between collection API and stream API

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hash tables they effectively replace. The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result

What is optional class

The Optional class in Java is a container that can hold, at max, one value and gracefully deals with null values. The class was introduced in the java. util package to remove the need for multiple null checks to protect against the dreaded NullPointerExceptions during run-time

forEach method in java 8

The forEach() method of ArrayList is used to perform a certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been processed by the method or an exception is raised

What are method references, explain with examples

They allow you to reference an instance method of an arbitrary object of a particular type. See notes for example.

What are concurrency features in java 8

concurrent. ConcurrentHashMap. The Collections Framework has undergone a major revision in Java 8 to add aggregate operations based on the newly added streams facility and lambda expressions. As a result, the ConcurrentHashMap class introduces over 30 new methods in this release.

How to sort list of employee objects using java 8 features How can you sort list of employee objects?

employeelist.sort((Employee e1, Employee e2) -> e1.getAge() - 2.getAge()); In order to sort Employee objects on different criteria, we need to create multiple comparators e.g. NameComparator, AgeComparator, and SalaryComparator, this is known as custom sorting in Java. This is different from the natural ordering of objects, provided by the compareTo() method of java. lang

A num1={0,1,0,1,0,1,0,1,0,1}, display = 0,0,0,0,0,1,1,1,1,1 using java8

num1.stream().sorted.forEach(Sytem.out::print);

Create a list of person class and display name of those person whose age >= 25. Use Java8 Lambda expression

pList.stream().filter(p->p.getAge()>25).map(Person::getName).forEach(System.out::println);

Using java 8 features make a call to a function that checks if the string is null

public String checkNull(String checkThis){ Optional<String> opt = Optional.of(notNull); return opt.ifPresent(this::print); }


Conjuntos de estudio relacionados

State Laws, Rules, and Regulations

View Set

AP Art History Semester 1 Final Review

View Set

Microeconomics: private and public choice, ch 6

View Set

Chapter 4 - Energy and Cellular Metabolism

View Set

Final Exam Review Actividad 9- 39

View Set

Ch.3.2 Sound Byte:Finding Information on the Web

View Set

PSYC 3082 Ch. 8: Eating Disorders and Sleep-Wake Disorders

View Set

A.P. Computer Science Principles

View Set