Java 8 Questions.

what is functional interface.
Ans :- An interface defined with only on abstract method. That interface can have multiple default and static methods.

Supplier, consumer and predicate are the functional interface provided by 8.

Supplier FI can used as factory pattern to create object using get method of that interface.
i.e.

import jdk.nashorn.internal.objects.annotations.Setter;

import java.util.UUID;

@Setter
public class Car {
    UUID id;
    String name;
}
public class MarutiCar extends car {

}

import jdk.nashorn.internal.objects.annotations.Setter;

import java.util.UUID;
import java.util.function.Supplier;

public class CarSupplier {

    private static <T extends Car> T getCar(final Supplier<T> supplier, final String name) {
        T car = supplier.get();
        car.setId(UUID.randomUUID());
        car.setName(name);
        return car;
    }

    public static void main(String args[]) {
        MarutiCarr car = getCar(MarutiCar::new, "Maruti Car");
    }
}

Predicate FI has test method. which do verification/checking of data.
i.e.
import com.sun.deploy.util.StringUtils;
import com.sun.istack.internal.Nullable;

import java.util.Date;
import java.util.function.Predicate;

public class DateValidator {
    private static final Predicate<String> IS_NA = "NA"::equals;
    private static final Predicate<String> IS_NOT_BLANK = String::isEmpty;
    private static final Predicate<String> NA_FIELD = IS_NOT_BLANK.and(IS_NA);

    @Nullable
    static String getDate(final String date) {
           if(NA_FIELD.test(date)) {
               return date;
           }

           return null;
    }
}

Consumer FI has accept method. which works as assignment operator.
i.e
import java.util.function.Consumer;

public class ConsumerNotNull {

    public static <T> void consumeNotNull(final Consumer<T> consumer, final T value) {
        if (value != null) {
            consumer.accept(value);
        }
    }
}


Developer can create their own functional interface provided that should have only one abstract method or add annotation as "@FunctionalINterface"

There are built in functional interfaces like predicate, binary operator, function.


What is predicate().
Ans. :- Predicate is functional interface. Predicate FI mostly used for constructing conditions, conditions like validate date. ( explain above ).


What is stream() api?
Ans:- stream works on view where elements stored by collections. any changes made by stream does not reflect on reflect on original collection. Stream api is lazy that means all methods defined in class stream are lazy. that is they wont work just by including them on stream pipe line. They work only when terminate methods called.

What are the terminate methods of stream api()?
Ans :- collect() and forEach() are the terminal methods.

What are the stream() api functions ?
Ans:- Stream api functions are
map();
flatMap();
filter();
reduce();
collect();
peek();

What does map() function do ?
Ans :- map function transform one object type into another.

package Stream;

public class CarLine {
    public CarLine(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    String name;

    @Override
    public String toString() {
        return "CarLine{" +
                "name='" + name + '\'' +
                '}';
    }
}

package Stream;

import java.util.UUID;

public class CarGroup{
    public CarGroup(UUID id) {
        this.id = id;
    }

    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    UUID id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    String name;

    @Override
    public String toString() {
        return "CarGroup{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

package Stream;

import Stream.CarGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class StreamMap {

    public static void main(String args[]) {
        List<CarLine> carLines =  new ArrayList<CarLine>();
        carLines.add(new CarLine("Alto"));
        carLines.add(new CarLine("Zen"));

        StreamMap streamMap = new StreamMap();
        streamMap.transformCarLines(carLines).forEach(System.out::println);
    }

    private List<CarGroup> transformCarLines(final List<CarLine> carLines) {
        return carLines.stream()
                                   .map(this::transformToCarGroup)
                                   .collect(Collectors.toList());
    }

    private CarGroup transformToCarGroup(CarLine carLine) {
        CarGroup carGroup = new CarGroup(UUID.randomUUID());
                carGroup.setName(carLine.getName());
        return carGroup;
    }
}



what does filter() function do?
Ans:- filter method of stream api used to filter data.

package Stream;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFilter {

    public static void main(String args[]) {
        List<CarLine> carLines =  new ArrayList<CarLine>();
        carLines.add(new CarLine("Alto"));
        carLines.add(new CarLine("Zen"));

        List<CarLine> filteredCarLines = carLines.stream()
                .filter(carLine -> carLine.getName().equals("Zen"))
                .collect(Collectors.toList());

        filteredCarLines.forEach(System.out::println);
    }
}




what does flatMap() function do?
Ans:- flatMap() flatten the collection. Lets say list of list is there and developer want to collect single list instate of having the list inside list.

package Stream;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class StreamFlatMap {

    public static void main(String args[]) {
        List<Car> altoCars = new ArrayList<Car>();
        altoCars.add(new Car(UUID.randomUUID(),"ALTO 1"));
        altoCars.add(new Car(UUID.randomUUID(),"ALTO 2"));

        List<Car> zenCars = new ArrayList<Car>();
        zenCars.add(new Car(UUID.randomUUID(),"ZEN 1"));
        zenCars.add(new Car(UUID.randomUUID(),"ZEN 2"));

        List<CarGroup> carGroups = new ArrayList<CarGroup>();
        carGroups.add(new CarGroup(UUID.randomUUID(),"ALTO GROUP",altoCars ));
        carGroups.add(new CarGroup(UUID.randomUUID(),"ZEN GROUP",zenCars));

        List<Car> cars = carGroups.stream()
                 .flatMap(carGrpup -> carGrpup.getCars().stream() )
                 .collect(Collectors.toList());

        cars.forEach(System.out::println);

    }
}


What are the intermediate and terminate operations on stream() api.
Ans:- collect() and forEach() are the terminate operation and others are intermediate.

How to convert the arrays to stream().
Ans :- Stream api provides of() operations which is called as factory method. That of() operation does the conversion of arrays into stream.

package StreamP;

import java.util.stream.Stream;

public class StreamOf {

    public static void main(String args[]) {
        String[] languages = {"MARATHI","HINDI", "ENGLISH"};
        Stream streamLanguages = Stream.of(languages);
        streamLanguages.forEach(System.out::println);
    }
}


How to convert the Iterable to stream().
Ans :- Stream api provides spliterator operation which does the conversion of Iterable to stream.
package javaeight.streamapi;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static java.util.stream.StreamSupport.stream;

public class StreamSpliterator {

    public static void main(String args[]) {
        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        Iterable<String> it = list;
        stream(it.spliterator(),false)
        .forEach(System.out::println);
    }
}


Comments

Popular posts from this blog

Custom DataType in Oracle Database.

Reverse String, Unchanged position of special characters.