Loading...

Follow Java Interview Questions and Answers on Feedspot

Continue with Google
Continue with Facebook
or

Valid
     In the current post, we can discuss the binary sort i.e 0 and 1 in Java. Given a binary array contains 0 & 1 in unsorted order, the output should be in sorted but we have to traverse only once.

Example:-

Input , array - {0,1,1,0,0,0,1,0,1}
Output, array - {0,0,0,0,0,1,1,1,1}

Java code:-

SortBinaryArray.java

package com.practice;

public class SortBinaryArray {

public static void main(String[] args) {

int arr[] = {1, 0, 1, 0, 0, 1, 1};
SortBinaryArray sort = new SortBinaryArray();

sort.sortBinaryArray(arr);

for (int i =0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
}

private void sortBinaryArray(int arr[]) {

int length = arr.length;
int j = -1;
for (int i = 0; i < length; i++) {

if (arr[i] < 1) {
j++;
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}

}

Output:-   0 0 0 1 1 1 1 


Related Posts:-
1) Java Program for Bubble Sort in Ascending and Descending order
2) Java Program to implement Selection Sort
3) Implementation of merge sort in Java
4) Java Object sorting example (Comparable and Comparable)
5) Difference between Comparable and Comparator Interface in Java
6) Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface
7) Java program to find second largest number in an array
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
        This question is also important for experienced java developers to know about type of locks in multithreading.         
        As we know that java supports multiple threads to be executed concurrently. If  two or more threads accessing the same resource at a time then conflict/inconsistent will occur. To avoid this inconsistency we are following synchronization concept i.e at a time one thread can access resource and wait for another thread to access. Using synchronized keyword to achieve the synchronization.  The synchronized keyword can be used as method level or block level.

   There are two types of locking in java in threading,

  • Object level lock
  • Class level lock

Object level lock:-

         Object level locking is about synchronizing a non-static method or non-static code block such that only one thread will execute the code block on given instance of the class. Object level locking make instance level data thread safe.

There are different ways we can lock the object in thread as below,

public class ThreadClassEx {
       public synchronized void syncMethod(){
             //method implementation here
       }
}

public class ThreadClassEx {
       public void syncMethod(){
              synchronized(this) {
//block implementation here
}
       }
}

public class ThreadClassEx {
         private final Object lock = new Object();

public void syncMethod(){
                   synchronized(lock) {
//block implementation here
}
}
}


Class level lock:-

         Class level locking is about a synchronizing a static method or block so that it can be accessed by only one thread for whole class. If you have 100 instances of class, only one thread will be able to access only one method or block of any one instance at a time.

        This should always be done to make static data thread safe.

Various ways of class level locking is as follows,

public class ThreadClassEx {

public synchronized static void syncMethod(){
//method implementation here
}
}

public class ThreadClassEx {

public void syncMethod(){

synchronized(ThreadClassEx.class) {
//block implementation here
}
}
}

public class ThreadClassEx {

private final static Object lock = new Object();

public void syncMethod(){

synchronized(lock) {
//block implementation here
}
}
}

Thank you for visiting blog.


Related Posts:-
1) Producer Consumer Problem - Solution using wait and notify In Java
2) Thread join() method example in Java
3) Difference between the Runnable and Callable interface in Java
4) Explain Thread life cycle and difference between wait() and sleep() method.
5) How many ways to create a thread in Java? Which one Prefer and why?
6) Producer Consumer Problem - Solution using BlockingQueue in Java
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
       We discussed in previous post about How to create the Immutable object in Java.  We discussed the all steps or rules we need to follow while creating immutable class in java. But if any field in the custom immutable class contains reference to any other mutable class then it will break immutable behavior. The reference class can be from imported jar files or any other imported application class and we can not access/control that mutable class. In this post, we will discuss how to make/convert mutable reference to immutable so that the complete class will become immutable.

      In the below example, Employee class is immutable but filed Address is mutable, it's another java class . 

Employee.java,
package com.practice;

public final class Employee {

private final String empName;
private final int age;
private final Address address;

public Employee(String name, int age, Address address) {
super();
this.empName = name;
this.age = age;
this.address = address;
}

public String getEmpName() {
return empName;
}

public int getAge() {
return age;
}

public Address getAddress() {
return address;
}

}

        In the above code, empName and age fields are immutable, we can not change the value but Address field it's reference of another java class and we can not have access or to modify the Address class.Here Address field is mutable, so we can restrict to modify the Address object/field in Employee class.

Address.java,
package com.practice;

public class Address implements Cloneable{

public String addressType;
public String address;
public String city;

public Address(String addressType, String address, String city) {
super();
this.addressType = addressType;
this.address = address;
this.city = city;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

         public Object clone() throws CloneNotSupportedException {  
return super.clone();
}

        @Override
public String toString() {
return "Address Type - "+addressType+", address - "+address+", city - "+city;
}
}

         In the below main class, you can create the Employee object using constructor, pass all parameters i.e empName, age and address. In the next line again we can set the addressType, address and city into the Address object. Now you try to access the address field from employee object it will get change. So in this case it will break the immutable behavior.

MainClass.java,
package com.practice;

public class MainClass {

public static void main(String[] args) {

Employee emp = new Employee("Mahesh", 34, new Address("Home", "JP Nagar", "Bangalore"));

Address address = emp.getAddress();

System.out.println(address);

address.setAddress("Jayanagar");
address.setAddressType("Office");
address.setCity("Sangli");

System.out.println(emp.getAddress());
}

}

Output:-
Address Type - Home, address - JP Nagar, city - Bangalore
Address Type - Office, address - Jayanagar, city - Sangli


Solution : -

The best solution is to modify the getAddress method in employee class, and instead of returning original Address object, we will return deep cloned copy of that instance. But one condition Address class must implements cloneable interface.

Modified employee class is as follow,

Employee.java,
package com.practice;

public final class Employee {

private final String empName;
private final int age;
private final Address address;

public Employee(String name, int age, Address address) {
super();
this.empName = name;
this.age = age;
this.address = address;
}

public String getEmpName() {
return empName;
}

public int getAge() {
return age;
}

public Address getAddress() throws CloneNotSupportedException {
return (Address) address.clone();
}

}

Now we can check to execute main class,

MainClass.java,
package com.practice;

public class MainClass {

public static void main(String[] args) {

Employee emp = new Employee("Mahesh", 34, new Address("Home", "JP Nagar", "Bangalore"));

Address address = emp.getAddress();

System.out.println(address);

address.setAddress("Jayanagar");
address.setAddressType("Office");
address.setCity("Sangli");

System.out.println(emp.getAddress());
}

}

Output:-
Address Type - Home, address - JP Nagar, city - Bangalore
Address Type - Home, address - JP Nagar, city - Bangalore


Related Posts:-
1) String Interview Questions and Answers
2) Why String is immutable or final in java?
3) Difference between Loose Coupling and Tight Coupling in Java With Examples.
4) Builder Design Pattern in Java
5) What is call by value and call by reference in Java ?
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
       This is familiar interview question for the middle level developers. Interviewer will check the coding logic of the candidate and best solution(performance level).

       In this question, there are two solutions to find the second largest number in the given array.

1) Using Sort - This is simple one, you have to sort the array in descending order and return the second element from the sorted array. Time complexity of this approach is O(nlogn)

2) Single Loop using Traversal :- Use single for loop,Inside for loop find the largest number and second condition to find the second largest number using first largest number.
Time complexity of this approach is O(n). This is the better solution compared to first one.

Let's see the below example to find the second largest number in an array,

SecondLargestNumber.java,

package com.test;

public class SecondLargestNumber {

public static void main(String[] args) {

int[] arr = {2, 3, 4, 10, 28, 38, 88, 10};

int firstLargeNum = 0;

int secondLargeNum = 0;

for (int i = 0; i<arr.length; i++) {

if (arr[i] > firstLargeNum) {

secondLargeNum = firstLargeNum;

firstLargeNum = arr[i];

} else if(arr[i] > secondLargeNum && arr[i] != firstLargeNum) {

secondLargeNum = arr[i];

}
}

System.out.println("Second Largest Number is - "+secondLargeNum);
}

}

Output:-
Second Largest Number is - 38.


Related Posts:--
1) Java Code to Print the Numbers as Pyramid - Examples
2) Java Program to find the Missing Number in an Array
3) Java program to print the first n prime numbers
4)  Java Program to check the given number is a palindrome or not
5) Write a Java program to print the Floyd's triangle
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
     This also one of the important question for experienced Java developers. In this post, we need understand what is call by value(pass by value) and call by reference .  

     Call by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments of the method are always passed by value. 

     With Java objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same Java object. Java primitives too are passed by value.

Read Top Java Blogs - Feedspot Top 40 Java Blogs

Is Java call by value or call by reference ?

    Java doesn't pass method arguments by reference; it passes them by value. So Java uses or supports call by value.

     In call by value, the modification done to the parameter passed does not reflect in the caller's scope while in the call by reference, the modification done to the parameter passed are persistent and changes are reflected in the caller's scope. The below example explains the call by value and call by reference with output.


Call by value example:-

   The following code shows an example of call by value. The values of the arguments will remain the same even after the method invocation.

PassByValueExample.java,

package com.test;

public class PassByValueExample {

public static void main(String[] args) {
int x = 10;
System.out.println("Value of x before calling method changeValue() - " +x);
changeValue(x);
System.out.println("Value of x after calling method changeValue() - " +x);
}

public static void changeValue(int x) {
x = 12;
System.out.println("Value of x inside method - "+x);
}
}

Output:-
Value of x before calling method changeValue() - 10
Value of x inside method - 12
Value of x after calling method changeValue() - 10

In the above output, the value of x after invoking the method, will remain same, it doesn't impact on original value.


Call by reference example:-

    The following code is the example of call by reference where List reference passed as an argument of  method. The elements of list will get change when we modify the element in the calling method.

PassByReferenceExample.java

package com.test;

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

public class PassByReferenceExample {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("A");
System.out.println("List before calling method - "+list);
addElement(list);
System.out.println("List after calling method - "+list);
}

public static void addElement(List<String> list) {
list.add("B");
System.out.println("List elements inside method - "+list);
}
}

Output:-
List before calling method - [A]
List elements inside method - [A, B]
List after calling method - [A, B]


Related Posts:-
1) String Interview Questions and Answers
2) Exception Handling Interview questions and answers
3) Difference between Loose Coupling and Tight Coupling in Java With Examples.
4) Interface and Abstract Class Interview Questions and Answers
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
        The  Design Pattern is an important question for the experienced(4+ exp) candidates.  For freshers interviewer will check the Singleton or Factory design pattern knowledge but when comes to experience we need to know other design patterns also. In the current post, we will discuss one of the important design pattern i.e Builder Design Pattern. 

Read Top Java blogs, Feedspot Top 40 Java Blogs

What is Builder Design Pattern? 

According to wikipedia definition:-

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

It is used to construct a complex object step by step and the final step will return the object.

When to use ?

 Following are the conditions where we can use builder design pattern,

  • When multiple representation of objects are required.
  • Number of parameter required in constructor is more than manageable(more than 4 or 5)
  • Object creation contains optional parameter.

Guidelines to create the Builder Design Pattern:-

1) Create a static builder class inside the class whose object is to be build by the builder. EmployeeBuilder class is a static class created as in the example.

2) Builder class should have public constructor  with required parameters and outside class should have private constructor. All fields of class should be private.

3) Needs to write methods to get the values of optional parameters.
e.g withFieldPhone(), withFieldAddress and withFieldDateOfBirth().
In example, phone,address and dob are optional parameters.

4) Create builder method in the builder class to get the desired object.

Example:--

Employee.java,

package com.test;

public class Employee {

private int id;
private String name;
private int age;
private String phone;
private String address;
private String dob;

private Employee(EmployeeBuilder builder) {
this.id = builder.id;
this.name = builder.name;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
this.dob = builder.dob;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getPhone() {
return phone;
}

public String getAddress() {
return address;
}

public String getDob() {
return dob;
}

public static class EmployeeBuilder {

private int id;
private String name;
private int age;
private String phone;
private String address;
private String dob;

//id, name and age are manadatory fields
public EmployeeBuilder(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

public EmployeeBuilder withFieldPhone(String phone) {
this.phone = phone;
return this;
}

public EmployeeBuilder withFieldAddress(String address) {
this.address = address;
return this;
}

public EmployeeBuilder withFieldDateOfBirth(String dob) {
this.dob = dob;
return this;
}

public Employee build() {
return new Employee(this);
}
}

@Override
     public String toString() { 
return "Id - "+id+", Name - "+name+", age - "+age+ ",address - "+ address+
", Phone - "+phone;
}

}

The above code is an example of Builder Design pattern, Now this we can access in below code.

BuilderDesignPatternEx.java,

package com.test;

public class BuilderDesignPatternEx {

public static void main(String[] args) {
Employee pattern = new Employee.EmployeeBuilder(10, "Kiran",10).withFieldAddress("Sonyal").build();
System.out.println(pattern);
//System.out.println(pattern.getName());
}

}

Output:--

Id - 10, Name - Kiran, age - 10,address - Sonyal, Phone - null


Java built in builder design pattern examples:

StringBuilder and StringBuffer classes are internally used builder design pattern concept.

Thank you for visiting blog..

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
        We discussed in earlier posts, Java 8 Consumer Interface, method reference and forEach() method with examples. In this page or post, we will discuss about BiConsumer, BiFunction and BiPredicate Interface with examples.

       All these Interfaces accept two input parameters and returns a result. We will discuss more details of each interface as below.

  • BiConsumer (java.util.function package)

        BiConsumer is a functional interface, has one abstract method i.e accept(), similar to a Consumer Interface. The difference between consumer and BiConsumer is Consumer interface accepts single parameter where as BiConsumer accepts two input parameters, and both doesn’t return anything.

Example:-

package com.test;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class BiConsumerExample {

public static void main(String[] args) {
                   //Consumer example
Consumer<String> strConsumer = str -> System.out.println(str);
strConsumer.accept("Java Wolrd");

//BiConsumer example
Map<String, String> map = new HashMap<String, String>();
map.put("Hello", "World");
BiConsumer<String, String> consumer = (key, value) -> System.out.println("Key - "+ key+", Value - "+value);

map.forEach(consumer);
}

}

Output:-
Java World
Key - Hello, Value - World


  • BiFunction (java.util.function package)
         BiFunction interface is also similar to Function interface(It is also functional interface), difference is Function interface will accept one parameter but BiFunction interface accepts two parameters as a input and returns results.

Declaration:-

Interface BiFunction<T,U,R>

Here, 

T - the type of the first argument as input
U - the type of the second argument as input
R - the type of the result of the function

Example:-

package com.test;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample {

public static void main(String[] args) {
                 //Function example
Function<Integer, Integer> printNumber = a -> a*10;
System.out.println("Number is "+printNumber.apply(10));

//BiFunction example
                BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
System.out.println("Summation of two number is "+add.apply(3,2));
}

}

Output:-
Number is 100
Summation of two number is 5


  • BiPredicate (java.util.function package)

        This interface also similar to Predicate interface and it's also functional interface. Predicate interface takes one agrument as input and return boolean value. But BiPredicate interface takes two arguments as input and returns boolean data type same as Predicate interface.

Example:-

package com.test;

import java.util.function.BiPredicate;
import java.util.function.Predicate;

public class BiPredicateExample {

public static void main(String[] args) {
                
                 //Predicate example
Predicate<String> pr = a -> a.contains("A");
System.out.println(pr.test("Anil"));

//BiPredicate example
                BiPredicate<Integer, Integer> biPrdt = (a,b) -> a>10 && b<5;
System.out.println(biPrdt.test(11, 2));
}
}

Output:-
true
true


Related Posts:-
1) Java 8 forEach method with examples
2) Method References in Java 8
3) Java 8 features with examples
4) Java 8 - Consumer Interface with examples
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
       In previous post, we learned Consumer Interface in Java 8 with examples. In this post, we will discuss another new feature of java 8, i.e method references.

      A method reference is the shorthand notation for a lambda expression to call a method. In previous versions of Java, we will use object dot method name to call method of the given object. In java 8, using :: operator after the object, to call the method.

Below is the general syntax of a method reference:

Object :: methodName

The example of Method Reference uses,

Using lambda expression,

s -> System.out.println(s)

It replaces using method reference as below,

System.out::println

Examples:-

1)  Instance method of object example(Object::instanceMethod)

MethodRefExample.java,

package com.test;

interface MethodRefInterface {  
void abstractMethod();
}
 
public class MethodRefExample {
  
public void method(){
System.out.println("This is a method reference example");
}

public static void main(String[] args) {
                    MethodRefExample methodRef = new MethodRefExample();  
MethodRefInterface ref= methodRef::method;
ref.abstractMethod();
}
}

Output:- 

This is a method reference example


2) Static method of a Class(ClassName::methodName)

MethodRefStatic.java,

package com.test;

import java.util.Arrays;
import java.util.List;

public class MethodRefStatic {

public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
System.out.println("Using lambda expression");
list.forEach(num -> printNumbers(num)); //using lambda expression
System.out.println("Using method references");
list.forEach(MethodRefStatic::printNumbers); //using method references
}

public static void printNumbers(int number) {
System.out.println("Number - " + number);
}
}

Output:-
Using lambda expression
Number - 1
Number - 2
Number - 3
Number - 4
Using method references
Number - 1
Number - 2
Number - 3
Number - 4


3) Example of method reference to a Constructor(Class::new)

MethodRefConstruct.java,

package com.test;

interface MessageInterface{
MethodRefEx getMessage(String msg);
}

class MethodRefEx {

MethodRefEx(String msg){
System.out.print(msg);
}
}
class MethodRefConstruct {

public static void main(String[] args) {
MessageInterface msg = MethodRefEx::new;
msg.getMessage("Hello World");
}
}

Output:-
Hello World


Related Posts:--
1) Java 8 - Consumer Interface with examples
2) Java 8 forEach method with examples
3) Java 8 features with examples
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
        In the current post, I will explain you the in-built functional interface Consumer introduced in Java 8 with examples. It contains two methods accept() & andThen(), comes under java.util.function package.

What is java.util.function.Consumer ?

       Consumer<T> is an in-built functional interface introduced in Java 8 and it is in the java.util.function package.  Here T is any type of input arguments. Consumer can be used in all contexts where an object needs to be consumed, i.e it will take argument as an input and some operation needs to be performed on the object without returning any result.  

       This is a functional interface because it contains only one abstract method i.e accept().

Methods in Consumer Interface

  • accept()
  • andThen()

       The accept() method is abstract method, need to implement in the code, it will take one parameter as argument and doesn't return anything.

syntax:-

    void accept(T t);

The following example shows how to use the accept() method of the Consumer interface.

package com.test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerInterface {

public static void main(String[] args) {

List<Integer> values = Arrays.asList(2,3,5,8);
Consumer<Integer> printInt = new Consumer<Integer>() {
@Override
public void accept(Integer var) {
System.out.println("Number - "+var);
}
};

//print the single integer number using consumer interface.
printInt.accept(10);

//print the integers using consumer interface
values.forEach(printInt);
}

}

Output:--
Number - 10
Number - 2
Number - 3
Number - 5
Number - 8


andThen() -   is a default method in Consumer interface. Method andThen(), when applied on a Consumer interface, takes as input another instance of Consumer interface and returns as a result a new consumer interface which represents aggregation of both of the operations defined in the two Consumer interfaces.

syntax:-

default Consumer <T> 
andThen(Consumer<? super T> after)

The return type of the above method is Consumer and this accepts a parameter after which is the Consumer to be applied after the current one.

The below code is to illustrate the andThen() method,

package com.test;

import java.util.function.Consumer;

public class ConsumerInterface {

public static void main(String[] args) {

Consumer<String> cons1 = str -> {
System.out.println(str + " World");
};
              Consumer<String> cons2 = str -> {
System.out.println(str + " Java");
};

cons1.andThen(cons2).accept("Hello");
}

}

Output:-

Hello World
Hello Java



Related Posts:-
1) Java 8 forEach method with examples
2) Java 8 features with examples
Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
        In this post, we will discuss or learn how to iterate the Map, List and Stream in java 8 using forEach method. I have given some sample examples of each collection.


  • Java 8 forEach method to iterate List

The below example is to iterate the list using foreach method and lambda expression in java 8.

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8forEach {
public static void main(String[] args) {

List<String> list = new ArrayList<String>(Arrays.asList("A", "B", "C"));

//Java 7, to iterate the above list
for (String str : list) {
System.out.println(str);
}

//java 8, foreach method to iterate list
list.forEach(str -> {System.out.println(str);});
}

}

If you see the above example, you can reduce the code in Java 8 compared to earlier versions of Java.


  • Java 8 forEach method to iterate Map
In Java 8, you can iterate the map using Map.forEach(action) method and lambda expression. 

package com.test;

import java.util.HashMap;
import java.util.Map;

public class JavaforEachMap {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Dell");
map.put(2, "HCL");
map.put(3, "Toshiba");

//Java 7(earlier versions), iterate a Map
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key - "+entry.getKey() +" Value - "+entry.getValue());
}

//Java 8, iterate Map using forEach() method and lambda expression
map.forEach((k,v) -> {
System.out.println("key - "+k + " Value - "+v);
});
}

}


  • Iterate a List using Stream API and forEach() method

        In java 8, java.util.Stream represents a stream on which one or more operations can be performed. Stream operations are either intermediate or terminal. Stream terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a java.util.Collection like lists or sets (maps are not supported). Stream operations can either be executed sequential or parallel.

      Compare java 7 and earlier versions and java 8 code to iterate a list with certain conditions as follows,

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Java8Stream {

public static void main(String[] args) {

List<String> list = new ArrayList<String>(Arrays.asList("abc", "bcd", "afd", "art"));

//Java 7, to iterate list with some conditions
for (String str : list) {
if (str.contains("a")) {
System.out.println(str);
}
}

//same example in java 8 using foreach() and stream api
list.stream().filter(a -> a.contains("a")).forEach(str -> {
System.out.println(str);
});
}
}

Read Full Article

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview