DEV Community

Ravi Yasas
Ravi Yasas

Posted on

2

Java interview coding questions - Part 01

How to count words in a String

package com.app.interviews;
import java.util.*;
public class StringWordCount {
public static void main(String[] args) {
String line = "Sri Lanka is a beautiful country. It is an island.";
String[] words = line.trim().replace(".", "").replace(",", "").split(" ");
// get the word count method 1
System.out.println(Arrays.toString(words));
System.out.println(words.length);
// get the word count method 2
StringTokenizer tokenizer = new StringTokenizer(line);
System.out.println(tokenizer.countTokens());
// get unique words
Set<String> set = new HashSet<>();
for (String s : Arrays.asList(words)) {
set.add(s);
}
System.out.println(set);
// get the longest word
String temp = "";
for (String word : Arrays.asList(words)) {
if (word.length() > temp.length()) {
temp = word;
}
}
System.out.println(temp);
// word occurrence of a specific word
int count = 0;
for (int i = 0; i < words.length; i++) {
if (words[i].equalsIgnoreCase("is")) {
count++;
}
}
System.out.println(count);
// get the word count
Map<String, Integer> stringMap = new HashMap<>();
for (int i = 0; i < words.length; i++) {
if (stringMap.containsKey(words[i])) {
int wordCount = stringMap.get(words[i]);
stringMap.put(words[i], wordCount + 1);
} else {
stringMap.put(words[i], 1);
}
}
System.out.println(stringMap);
}
}

How to remove duplicates in a String

package com.app.interviews;
import java.util.*;
import java.util.stream.Collectors;
public class RemoveDuplicates {
public static void main(String[] args) {
String line = "Sri Lanka is a beautiful country. It is an island";
String[] array = line.trim().replace(".", "").split(" ");
// method 1 - using Java 7
Set<String> stringSet = new HashSet<>(Arrays.asList(array));
System.out.println(stringSet);
// method 2 - using Java 8
Set<String> set = Arrays.stream(array).collect(Collectors.toSet());
System.out.println(set);
// using java 8 stream
Arrays.stream(array).distinct().forEach(System.out::println);
}
}

How to reverse a String

package com.app.interviews;
public class ReverseString {
public static void main(String[] args) {
String name = "abcdefg";
// method 1
StringBuffer stringBuffer = new StringBuffer(name);
System.out.println(stringBuffer.reverse());
// method 2
char[] nameArray = name.toCharArray();
char temp;
for (int i = 0; i < nameArray.length - 1; i++) {
for (int j = 0; j < nameArray.length - 1 - i; j++) {
temp = nameArray[j];
nameArray[j] = nameArray[j + 1];
nameArray[j + 1] = temp;
}
}
System.out.println(nameArray);
// method 3
String email = "abcdefg@live.com";
char[] emailArray = email.toCharArray();
for (int i = emailArray.length - 1; i >= 0; i--) {
System.out.print(emailArray[i]);
}
System.out.println();
// method 4
String homeTome = "Colombo";
byte[] bytes = homeTome.getBytes();
byte[] result = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
result[i] = bytes[bytes.length - 1 - i];
}
System.out.println(new String(result));
}
}

How to add a List to a Map

package com.app.other.map;
import java.util.*;
import java.util.stream.Collectors;
public class ListToMap {
public static void main(String[] args) {
List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("Jeny", "jeny@live.com"));
employeeList.add(new Employee("Ann", "ann@live.com"));
employeeList.add(new Employee("Meliessa", "meliessa@live.com"));
employeeList.add(new Employee("Natali", "natali@live.com"));
employeeList.add(new Employee("Hash", "hash@live.com"));
// Using Java 7
Map<Integer, Employee> employeeMap = new HashMap<>();
for(Employee employee : employeeList){
employeeMap.put(employee.getId(), employee);
}
// Add list to a map, by default it creates a HashMap
Map<String, String> map1 = employeeList.stream().collect(Collectors.toMap(
Employee::getUsername,
Employee::getEmail,
(oldValue, newValue) -> newValue)); // This will remove duplicates.
Map<String, String> map2 = employeeList.stream().collect(Collectors.toMap(
emp -> emp.getUsername(),
emp -> emp.getEmail(),
(oldValue, newValue) -> oldValue));
// Add list to a LinkedHashMap
Map<String, String> map3 = employeeList.stream()
.collect(Collectors.toMap(
Employee::getUsername,
Employee::getEmail,
(oldValue, newValue) -> newValue,
LinkedHashMap::new));
// Add list to a LinkedHashMap and sort ascending order
Map<String, String> map4 = employeeList.stream()
.sorted(Comparator.comparing(Employee::getUsername))
.collect(Collectors.toMap(
Employee::getUsername,
Employee::getEmail,
(oldValue, newValue) -> newValue,
LinkedHashMap::new));
// Add list to a LinkedHashMap and sort reverse order
Map<String, String> map5 = employeeList.stream()
.sorted(Comparator.comparing(Employee::getUsername).reversed())
.collect(Collectors.toMap(
Employee::getUsername,
Employee::getEmail,
(oldValue, newValue) -> newValue,
LinkedHashMap::new));
System.out.println(map1);
System.out.println(map2);
System.out.println(map3);
System.out.println(map4);
System.out.println(map5);
}
}
view raw ListToMap.java hosted with ❤ by GitHub

How to add a List to a Set

package com.app.other.set;
import java.util.*;
import java.util.stream.Collectors;
public class ListToSet {
public static void main(String[] args) {
List<String> list = Arrays.asList("FFF", "BBB", "CCC", "DDD", "DDD");
Set<String> set1 = new TreeSet<>(); // TreeSet will return an ordered collection. But you cannot add null values
// using java 7 - using foreach loop
for(String word: list){
set1.add(word);
}
System.out.println(set1);
// using java 7 - using constructor
Set<String> set2 = new TreeSet<>(list);
System.out.println(set2);
// using java 7 - using constructor to reverse order
Set<String> set3 = new TreeSet<>(Comparator.reverseOrder());
set3.addAll(list);
System.out.println(set3);
// using java 8 - to default collection
Set<String> set4 = list.stream().collect(Collectors.toSet()); // Here it will return a HashSet by default, it doesn't have a order
System.out.println(set4);
// using java 8 - to specific collection
Set<String> set5 = list.stream().collect(Collectors.toCollection(TreeSet::new)); // This will return an ordered collection because of the TreeSet
System.out.println(set5);
}
}
view raw ListToSet.java hosted with ❤ by GitHub

How to add a List to an array

package com.app.other;
import java.util.*;
public class ListToArray {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,3,2,1);
// Add list to array
int[] numberList = new int[list.size()];
for(int i=0; i<list.size(); i++){
numberList[i] = list.get(i);
}
System.out.println(Arrays.toString(numberList));
// remove duplicates
Set<Integer> integerSet = new HashSet<>();
integerSet.clear();
integerSet.addAll(list);
System.out.println(integerSet);
// This returns a immutable list, you cannot add new elements to an immutable empty list.
List<String> myList = Collections.emptyList();
System.out.println(myList);
}
}

How to sort an array

package com.app.interviews;
import java.util.Arrays;
public class ArraySort {
public static void main(String[] args) {
int[] array = {1, 5, 2, 3, 6, 5, 3, 5, 8};
int temp = 0;
// Using Java 7
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(array));
// Using sort method
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// Using Java 8
Arrays.stream(array).boxed().sorted().forEach(System.out::print);
}
}
view raw ArraySort.java hosted with ❤ by GitHub

Top comments (1)

Collapse
 
dinuka00 profile image
dinuka00

thanks for share