CodeByAkram: Interview Questions
Showing posts with label Interview Questions. Show all posts
Showing posts with label Interview Questions. Show all posts

Write a program to print first non repeated char in a string in Java.


Write a program to print first non repeated char in a string in Java.

We are using the HashMap to store the character as key and count of times it is repeated as value.


package com.string.codebyakram;

import java.util.HashMap;

public class NonReapingCahr {
 public static void main(String[] args) {
  String string = "hello";
  System.out.println(findNonReapingCahr(string));
 }

 public static char findNonReapingCahr(String string) {

  HashMap< character > countChar = new HashMap<>();

  for (int i = 0; i < string.length(); i++) {
   int count = countChar.get(string.charAt(i)) == null ? 1 : countChar.get(string.charAt(i)) + 1;
   countChar.put(string.charAt(i), count);
  }

  for (int i = 0; i < string.length(); i++) {
   if (countChar.get(string.charAt(i)) == 1) {
    return string.charAt(i);
   }
  }
  return '\0';

 }
}

How to delete log4j/log file older than N number of days?

How to delete log4j/log file by N number of days?

package com.avaya.deletelogs;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;

public class DeleteLogs {

 private String baseDir = "/opt/java/IVRLog";
 private int daysBack = 4;

 public void invokeProcess() {
  getFolders();
 }

 public void getFolders() {

  try {
   File file = new File(baseDir);
   String[] directories = file.list(new FilenameFilter() {

    public boolean accept(File current, String name) {
     return new File(current, name).isDirectory();
    }
   });
   deleteFiles(daysBack, baseDir, Arrays.asList(directories));
  } catch (Exception e) {
   System.out.println(e);
  }
 }

 public void deleteFiles(int daysBack, String dirWay, List< string> directories) {
  for (String dir : directories) {
   deleteFilesOlderThanNdays(daysBack, dir);
  }

 }

 public void deleteFilesOlderThanNdays(int daysBack, String dirWay) {

  File directory = new File(baseDir + "/" + dirWay);
  if (directory.exists()) {

   File[] listFiles = directory.listFiles();
   long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
   for (File listFile : listFiles) {
    try {
     if (listFile.isFile()) {
      if (listFile.lastModified() < purgeTime) {
       if (!listFile.delete()) {
        System.err.println("Unable to delete file: " + listFile);
       }
      }
     } else {
      continue;
     }
    } catch (Exception e) {
     System.out.println(e);
    }
   }
  }
 }

}

Java 8 Lambda Comparator

Lets se how we can sort the object by using java 8 lambda comparator. For this let take a Employee class.

Java 8 Lambda Comparator, codebyakram

public class Employee {
    private String name;
    private int salary;
 
    // standard constructors, getters/setters, equals and hashcode
}

1. Classic sort (without lambda)

Comparator< Employee > bySalary = new Comparator< Employee >() {
  @Override
  public int compare(Employee o1, Employee o2) {
   return o1.getSalary().compareTo(o2.getSalary());
  }
 };
2. Lambda expression equivalent.

 Comparator< Employee > bySalary = 
  (Employee o1, Employee o2)->o1.getSalary().compareTo(o2.getSalary());

You may also like to read What do you mean by Aspect, Join Point, Advice?

How to get keys and values from Map in Java?

As we know, map is based on key-value pair associations, so interviewer can ask you this question if you are a beginner or having less than 3 years of experience.

So lets see how we can the key and values from a Map?

How to get keys and values from Map, codebyakram


In Java we have and Map.Entry method that returns a collection-view of map.


Map< string string=""> map = new HashMap<>();

 // Get keys and values
 for (Map.Entry< string string=""> entry : map.entrySet()) {
  String k = entry.getKey();
  String v = entry.getValue();
  System.out.println("Key: " + k + ", Value: " + v);
 }

 // In Java 8 we can use for each
 map.forEach((k, v) -> {
  System.out.println("Key: " + k + ", Value: " + v);
 });

How to set connection timeout for RestTemplate in spring?

How to set connection timeout for RestTemplate in spring? codebyakram

We can set the timeout for RestTemplate by doing some custom configuration for RestTemplate.

First you need to create a class named as HttpClientConfig in this class we configure HttpClient because RestTemplate internally uses the HttpClient.


package com.codebyakram;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {

 public static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(HttpClientConfig.class.getName());
 // Determines the timeout in milliseconds until a connection is established.
 private static final int CONNECT_TIMEOUT = 30000;

 // The timeout when requesting a connection from the connection manager.
 
 private int REQUEST_TIMEOUT = 10000;
 
 @Bean
 public CloseableHttpClient httpClient() {
  RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).build();
  return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
 }
}

Here in this class we setting HttpClient in RestTemplate

package com.codebyakram;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

 @Autowired
 CloseableHttpClient httpClient;


 @Bean
 public RestTemplate restTemplate() {
  RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
  return restTemplate;
 }

 @Bean
 public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
  HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
  clientHttpRequestFactory.setHttpClient(httpClient);
  return clientHttpRequestFactory;
 }

 @Bean
 public TaskScheduler taskScheduler() {
  ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
  scheduler.setThreadNamePrefix("poolScheduler");
  scheduler.setPoolSize(50);
  return scheduler;
 }
}

So now we are done with the cofiguration of request timeout for RestTemplate.

How to Sort a Stack using Merge Sort?

Interviewer may ask you this question if you have more than 3 years of experience in java development. So lets have a look, how to sort a stack using merge sort?

Lets see sample input and output for better understanding:

How to Sort a Stack using Merge Sort? codebyakram


Algorithm
For this we will follow these below two steps,
1. Break the stack into two parts by using two temporary stack.

2. When only one element remains on a Stack, Merge it.

Lets have a look on the program,


package com.codebyakram;
 
import java.util.Stack;
 
public class SortStack {
 
    public static void main(String args[]) {
        Stack stack = new Stack();
        stack.push(5);
        stack.push(9);
        stack.push(4);
        stack.push(1);
        stack.push(2);
        stack.push(-1);

 
        sort(stack);
 
        System.out.println(stack);
    }
 
    private static void sort(Stack stack) {
        Stack s1 = new Stack();
        Stack s2 = new Stack();
 
        while (stack.size() != 0) {
            if (stack.size() % 2 == 0) {
                s1.push(stack.pop());
            } else {
                s2.push(stack.pop());
            }
        }
 
        if (s1.size() > 1) {
            sort(s1);
        }
 
        if (s2.size() > 1) {
            sort(s2);
        }
 
        merge(s1, s2, stack);
    }
 
    private static void merge(Stack s1, Stack s2, Stack stack) {
        Stack mergedStack = new Stack();
        while (!s1.isEmpty() && !s2.isEmpty()) {
            if ((Integer) s1.peek() < (Integer) s2.peek()) {
                mergedStack.push(s2.pop());
            } else {
                mergedStack.push(s1.pop());
            }
        }
 
        while (!s1.isEmpty()) {
            mergedStack.push(s1.pop());
        }
 
        while (!s2.isEmpty()) {
            mergedStack.push(s2.pop());
        }
 
        while (!mergedStack.isEmpty()) {
            stack.push(mergedStack.pop());
        }
    }
}

Adjacency List in Java

An adjacency list represents a graph as an array of linked list.

The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex.

Adjacency List representation
A graph and its equivalent adjacency list representation is shown below.

Adjacency List in Java, codebyakram
An adjacency list is efficient in terms of storage because we only need to store the values for the edges. For a sparse graph with millions of vertices and edges, this can mean a lot of saved space.

Adjacency List Structure
The simplest adjacency list needs a node data structure to store a vertex and a graph data structure to organize the nodes.


We stay close to the basic definition of graph - a collection of vertices and edges {V, E}. For simplicity we use an unlabeled graph as opposed to a labeled one i.e. the vertexes are identified by their indices 0,1,2,3.

Let's dig into the data structures.

struct node
{
    int vertex;
    struct node* next;
};
struct Graph
{
    int numVertices;
    struct node** adjLists;
};

Don't let the struct node** adjLists overwhelm you.

All we are saying is we want to store a pointer to struct node*. This is because we don't know how many vertices the graph will have and so we cannot create an array of Linked Lists at compile time.

Adjacency List Java
We use Java Collections to store the Array of Linked Lists.

class Graph
{
    private int numVertices;
    private LinkedList adjLists[];
}

The type of LinkedList is determined what data you want to store in it. For a labeled graph, you could store a dictionary instead of an Integer

Adjacency List code Java

import java.io.*;
import java.util.*;
class Graph
{
    private int numVertices;
    private LinkedList adjLists[];
 
    Graph(int vertices)
    {
        numVertices = vertices;
        adjLists = new LinkedList[vertices];
        
        for (int i = 0; i < vertices; i++)
            adjLists[i] = new LinkedList();
    }
 
    void addEdge(int src, int dest)
    {
        adjLists[src].add(dest);
    }
 
    public static void main(String args[])
    {
        Graph g = new Graph(4);
 
         g.addEdge(0, 1);
         g.addEdge(0, 2);
         g.addEdge(1, 2);
         g.addEdge(2, 3);
    }
}