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.