IQ, Java

Java important points

|
Divnesh BLOG


  • Convert 2d array to Map


            String[][] details = { { "ram", "gopal" }, { "varma", "gopal" }, { "chetti", "pandi" }, { "gopal", "ntr" } };
            Map<String, String> detailMap = new HashMap<>();
            final Map<String, String> map = new HashMap<String, String>(details.length);
            for (String[] mapping : details)
            {
                map.put(mapping[0], mapping[1]);
            }
            for (int i = 0; i < details.length; i++) {
            List<String> convertor = new ArrayList<>();
            for (int j = 0; j < details[i].length; j++) {
                convertor.add(details[i][j]);
            }
            detailMap.put(convertor.get(0), convertor.get(1));
            }

  • Iterate through Map
        Method 1: 
        for (Map.Entry<String, String> mapper : detailMap.entrySet()) {
if (mapper.getValue().equals(parent)) {
    children = mapper.getKey();
}
}

        Method 2: 

        Iterator itr = map.entrySet().iterator();

        while(itr.hasNext()) {
            Map.Entry me = (Map.Entry) itr.next();
            System.out.println("Key is " + me.getKey() + " Value is " + me.getValue());
        }

  • Reverse the String

        String value = "indian";
        System.out.println(value.length());
        char[] chars = value.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i=chars.length-1;i>=0;i--){
            sb.append(chars[i]);
        }
         StringBuilder sb1 = new StringBuilder(value);
        sb1.reverse();    

        System.out.println(sb.toString());

  •      Arrays
    •          Arrays.sort()    
    •          Arrays.equals(string1, string2)
    •         Arrays.toString(inputArray)
    •         Arrays.deepToString(oneDArray)
    •         Collections.sort(list);
    •         Collections.sort(list, Collections.reverseOrder());
  • conversion


  • Map

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

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

// add based on frequency
Map<Character, Integer> mapper = new HashMap<>();
for (Character c : "malayalam".toCharArray()) {
mapper.put(c, mapper.containsKey(c) ? mapper.get(c) + 1 : 1);
}

//Sort by value - ascending
List<Entry<Character, Integer>> list = new ArrayList<>(mapper.entrySet());
list.sort(Entry.comparingByValue());
//reverse the list
Collections.reverse(list);

Map<Character, Integer> valueAscending = new LinkedHashMap<>();
for (Entry<Character, Integer> entry : list) {
valueAscending.put(entry.getKey(), entry.getValue());
}
//Sort by value - descending java 8
 List<Map.Entry<String, Integer>> list1 =new LinkedList<Map.Entry<String, Integer>>(mapper.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                               Map.Entry<String, Integer> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

//Sort by key -descending
1.
Map<Character, Integer> keyDescending = new TreeMap<Character, Integer>(Collections.reverseOrder());
keyDescending.putAll(mapper);
//Sort by key -ascending
Map<Character, Integer> keyAscending = new TreeMap<Character, Integer>(mapper);
2.
TreeMap<Integer, String> mapper1 = new TreeMap<Integer, String>();
mapper1.put(1, "x");
mapper1.put(2, "c");
mapper1.put(3, "r");
 NavigableMap<Integer, String> nmap = mapper1.descendingMap();
 for (NavigableMap.Entry<Integer, String> entry : nmap.entrySet()) {
 System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
 }

//print the map
for (Map.Entry<Character, Integer> c : valueAscending.entrySet()) {
    System.out.println(c);
}
for (Character c : mapper.keySet()) {
    System.out.println(c + " - " + mapper.get(c));
}
for (Integer c : mapper.values()) {
}
}
}

  • cube root
static double diff(double n, double mid) {
if (n > (mid * mid * mid))
return (n - (mid * mid * mid));
else
return ((mid * mid * mid) - n);
}

static double cubicRoot(double n) {
double start = 0, end = n;
double e = 0.0000001;
while (true) {
double mid = (start + end) / 2;
double error = diff(n, mid);
if (error <= e)
return mid;
if ((mid * mid * mid) > n)
end = mid;
else
start = mid;
}
}

  • squareRoot
public static double squareRoot(int number) {
double temp;
double sr = number / 2;
do {
temp = sr;
sr = (temp + (number / temp)) / 2;
} while ((temp - sr) != 0);
return sr;
    }
  • largest common prefix 
//Checks for the largest common prefix
public static String lcp(String s, String t){
int n = Math.min(s.length(),t.length());
  for(int i = 0; i < n; i++){
    if(s.charAt(i) != t.charAt(i)){
       return s.substring(0,i);
     }
  }
return s.substring(0,n);
}

public static void main(String[] args) {
String str = "acbdfghybdf";
String lrs="";
int n = str.length();
 for(int i = 0; i < n; i++){
    for(int j = i+1; j < n; j++){
    //Checks for the largest common factors in every substring
    String x = lcp(str.substring(i,n),str.substring(j,n));
     //If the current prefix is greater than previous one
     //then it takes the current one as longest repeating sequence
     if(x.length() > lrs.length()) lrs=x;
     }
 }
System.out.println("Longest repeating sequence: "+lrs);
}

  • permutation of string
    if (start == end-1) 
  1.     System.out.println(str);
    for (int i = start; i < end; i++)    
{    
                //Swapping the string by fixing a character    
                str = swapString(str,start,i);    
                //Recursively calling function generatePermutation() for rest of the characters     
                generatePermutation(str,start+1,end);   
                         str = swapString(str,start,i);    
        }

  • subset
    String str = "FUNS";  
    int len = str.length();  
    int temp = 0;  
    int number= len*(len+1)/2;
    String arr[] = new String[number];
    for(int i = 0; i < len; i++) {  
        for(int j = i; j < len; j++) {  
            arr[temp] = str.substring(i, j+1);  
            temp++;  
        }  
    }  

    System.out.println("All subsets for given string are: ");  
    for(int j = 0; j < arr.length; j++) {  
        System.out.println(arr[j]);  
    }  

  • SimpleDateFormat
        java.text.
        format -date to specific format parse -String to date

         Date startDate = formatter.parse(s1);   
            Date endDate = formatter.parse(s2); 
            long diffInMilliSec = endDate.getTime() - startDate.getTime();  
            long seconds = (diffInMilliSec / 1000) % 60;    
            long minutes = (diffInMilliSec / (1000 * 60)) % 60;  
            long hours = (diffInMilliSec / (1000 * 60 * 60)) % 24;   
            long days = (diffInMilliSec / (1000 * 60 * 60 * 24)) % 365;
            long years =  (diffInMilliSec / (1000l * 60 * 60 * 24 * 365));
             
  • File
        File file = new File()
        file.exists()
        file.setWritable
        file.setExecutable
        file.setReadable

        BufferedReader reader2 = new BufferedReader(new FileReader("C:\file2.txt"));  
        String line1 = reader1.readLine();
        String line2 = reader2.readLine();

       FileInputStream  inStream = new FileInputStream(new File("C:/SourceFile.txt"););       
       FileOutputStream      outStream = new FileOutputStream(new File("C:/des.txt"););    
            byte[] buffer = new byte[1024];       
            int length;  
            while ((length = inStream.read(buffer)) != -1) 
            {
                outStream.write(buffer, 0, length);
            }

Set 
 intersectionSet.retainAll(set);






move to next line
System.lineSeparator();

class MyComparator implements Comparator<Student>
{
    @Override
    public int compare(Student s1, Student s2)
    {
        if(s1.id == s2.id)
        {
            return 0;
        }
        else
        {
            return s2.perc_Of_Marks_Obtained - s1.perc_Of_Marks_Obtained;
        }
    }
}




  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigneddivideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigneddivideUnsigned etc to support arithmetic operations for unsigned long.

  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Featured Post

HTML cheetsheet

List: Link tgs Dropdown

Popular Post

(C) Copyright 2018, All rights resrved InShortView. Template by colorlib