viernes, 31 de agosto de 2018

Useful tools in java

Index

1. Grouping elements of a List -Java 8

import java.io.*;
import java.util.*;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.function.Function;
...

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(1);
list.add(3);
list.add(2);
list.add(1);

Map<Integer,Long> group = list
                          .stream()
                          .collect
                           (
                             Collectors
                             .groupingBy
                              (
                                 Function.identity()
                                ,Collectors.counting()
                              )
                           )
  ;
System.out.println(group); // out: {1=3, 2=1, 3=2} 

2. Sorting a map by values - Java 8

 import java.io.*;
 import java.util.*;
...
 Map<Integer,Long> list = new HashMap<Integer,Long>();
list.put(3,0L);
list.put(2,5L);
list.put(1,3L);
list.put(4,2L);
 Map<Integer, Long> finalMap = new LinkedHashMap<>();
//This method does not mutate the original map
list
.entrySet()
.stream()
.sorted
(
  Map
  .Entry
  .<Integer,Long>comparingByValue()
  .reversed()
)
.forEachOrdered(e -> finalMap.put(e.getKey(),e.getValue()));

System.out.println(finalMap); //out: {2=5, 1=3, 4=2, 3=0}

3. Get first element in a map 

import java.io.*;
import java.util.*;
...
Map<Integer,Long> map = new HashMap<Integer,Long>();
map.put(3,0L);
map.put(2,5L);
map.put(1,3L);
map.put(4,2L);

System.out.println("Key:"+map.entrySet().stream().findFirst().get().getKey()); //out: Key:1
System.out.print("Value:"+map.entrySet().stream().findFirst().get().getValue());//out: Value:3

Solution to common problems in java

Solution to common problems in java

Index

Here are some solutions about common problems that you might get by applying to technical interviews. You can find the solutions that I developed for these problems. Feel free to share a better solution in the comments. Most of the code problems I solved were taken from https://www.dailycodingproblem.com/ by subscribing to the page and https://www.udemy.com/11-essential-coding-interview-questions/.

3. Find two numbers within an array that their sum be K - java 8

3. Find two numbers within an array that their sum be K - java 8

 

Tools:

-JDK 8
-CoderPad/Sanbox

Solution:

import java.io.*;
 import java.util.*;
 import java.util.Map;
 import java.util.stream.Collectors;

 class Solution
 {
   public static void main(String[] args)
   {
     //Init array
     ArrayList<Integer> array = new ArrayList<Integer>();
     array.add(10);
     array.add(15);
     array.add(3);
     array.add(7);
     int k=17;
     List<Integer> result=getNumbers(k,array);
     /*Verify result. If result size is higher than 2 then the method found the       numbers */
     if(result.size()==2)
       System.out.println(result.get(0)+" + "+result.get(1)+" = "+ k);
     else
       System.out.println("No numbers found");

   }
   //Method which seach two numbers that get K by adding each other

   public static List<Integer> getNumbers(int k, List<Integer>array)
   {
     /*Get a sorted map of the array. This help to find numbers faster than prove one by one*/
     Map<Integer,Integer> map = array
                               .stream()
                               .sorted()
                               .collect(Collectors
                                         .toMap(Integer::intValue,Integer::intValue));
    
     List <Integer> result= new ArrayList<Integer>();
     //check the results
     for (Map.Entry<Integer, Integer> entry : map.entrySet())
     {
       //get the resudue between key and k
       int reo = k - entry.getKey();
      /*If resudue is equal to itself and resudue is higher than k then it is impossible to get k by adding other number in array*/
       if((reo == entry.getKey() && reo + entry.getKey()> k) )
       {
         break;
       }
       /*if resudue is lower than key + 1 then it is impossible to get k by adding */
       else if(reo < (1+entry.getKey()))
       {
         break;
       }
       /*search resudue in map if the residue is found then the solution is gotten*/
       else
       {
         if(map.containsKey(reo))
         {
           result.add(reo);
           result.add(entry.getKey());
           break;
         }
       }
     }
     return result;
   }
 }

Comment: Leave a comment if you have a doubt or you have a better solution, also if you have any suggestion

2. Get the elements in common between two lists - java 8

2. Get the elements in common between two lists - java 8

 

Tools:

-JDK 8
-CoderPad/Sanbox

Solution:

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
class Solution
 {
   public static void main(String[] args)
   {
     //Init a
     List<Integer> a = new ArrayList<Integer>();
     a.add(1);
     a.add(3);
     a.add(4);
     a.add(6);
     a.add(8);
     a.add(9);

     //Init b
     List<Integer> b= new ArrayList<Integer>();
     b.add(1);
     b.add(2);
     b.add(3);
     b.add(5);
     b.add(6);
     b.add(8);

     List<Integer> commons = commonElements(a,b);
     //Print Result
     System.out.print("The elements in common between a and b are :"+ commons);
   }
  
   //method that find common elements between two lists
   public static List<Integer> commonElements(List<Integer> a,List<Integer>b)
   {
     List<Integer> result = new ArrayList<Integer>();
     //Maybe you would need to override equals and hash method for complex objects
     //This method find an element of a in b
     //This can be work in java 7 and less by replacing forEach to for block
     a.forEach(item->
                    {
                      if(b.contains(item))
                         result.add(item);
                    });
     return result;
   }
 }

Comment:

Leave a comment if you have a doubt or you have a better solution, also if you have any suggestion

1. Get the most frequent element in a list - java 8

1.  Get the most frequent element in a list - java 8

Tools:

-JDK 8
-CoderPad/Sanbox

Solution:


import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
/*
 * To execute Java, please define "static void main" on a class
 * named Solution.
 *
 * If you need more classes, simply define them inline.
 */
class Solution
{
  public static void main(String[] args)
  {
     //Init list
     List<Integer> list = new ArrayList<Integer>();
     list.add(1);
     list.add(3);
     list.add(1);
     list.add(3);
     list.add(2);
     list.add(1);

     int most=mostFrequentElement(list);
     //Print result
     System.out.print("The most frequent element in list is:"+most);
  }
  //Method that return the most frequent element in array
  public static int mostFrequentElement(List<Integer> list)
  {
    //Group the list in a map by the number of appareance
    Map<Integer,Long> group = list
                             .stream()
                             .collect
                              (
                                Collectors
                                .groupingBy
                                (
                                   Function.identity()
                                  ,Collectors.counting()
                                )
                             )
    ;
  
    Map<Integer, Long> finalMap = new LinkedHashMap<>();
    //This method does not mutate the original map.
    //Put in first place the element which have more appearances than the others one based on the previous group
    group
   .entrySet()
   .stream()
   .sorted
   (
     Map
     .Entry
     .<Integer,Long>comparingByValue()
     .reversed()
   )
   .forEachOrdered(e -> finalMap.put(e.getKey(),e.getValue()));
   
   return finalMap.entrySet().stream().findFirst().get().getKey();
 }
}

Comment:

Leave a comment if you have a doubt or you have a better solution, also if you have any suggestion