Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, August 6, 2013

Sorting Maps

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.apache.poi.hssf.record.formula.functions.Weekday;


public class Aaaaaaaa {

  
  
    public static void main(String args[]){
      
        WeakHashMap hashMap=new WeakHashMap();
        hashMap.put("5","Sreedhar5" );
        hashMap.put("6","Sreedhar6" );
        hashMap.put("2","Sreedhar2" );
        hashMap.put("4","Sreedhar4" );
        hashMap.put("7","Sreedhar7" );
        hashMap.put("8","Sreedhar8" );
      
        HashMap passedMap=new HashMap();
        passedMap.put("5","Sreedhar5" );
        passedMap.put("6","Sreedhar6" );
        passedMap.put("2","Sreedhar2" );
        passedMap.put("4","Sreedhar4" );
        passedMap.put("7","Sreedhar7" );
      
      
        passedMap=sortHashMapByValuesD(passedMap);
      
        System.out.println(":::passedMap::::"+passedMap);
        System.out.println("\n hashMap::::::"+hashMap);
      
        System.out.println(":::::::"+sortHashMapByValues(passedMap, false));
    }
  
    public static LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
        List mapKeys = new ArrayList(passedMap.keySet());
        List mapValues = new ArrayList(passedMap.values());
        Collections.sort(mapValues);
        Collections.sort(mapKeys);
          
        LinkedHashMap sortedMap =
            new LinkedHashMap();
      
        Iterator valueIt = mapValues.iterator();
        while (valueIt.hasNext()) {
            Object val = valueIt.next();
            Iterator keyIt = mapKeys.iterator();
          
            while (keyIt.hasNext()) {
                Object key = keyIt.next();
                String comp1 = passedMap.get(key).toString();
                String comp2 = val.toString();
              
                if (comp1.equals(comp2)){
                    passedMap.remove(key);
                    mapKeys.remove(key);
                    sortedMap.put((String)key, (String)val);
                    break;
                }

            }

        }
        return sortedMap;
    }
  
  
    public static LinkedHashMap sortHashMapByValues(HashMap passedMap, boolean ascending) {

        //Asending and Desending
          List mapKeys = new ArrayList(passedMap.keySet());
        List mapValues = new ArrayList(passedMap.values());
        Collections.sort(mapValues);
        Collections.sort(mapKeys);

        if (!ascending)
        Collections.reverse(mapValues);

        LinkedHashMap someMap = new LinkedHashMap();
        Iterator valueIt = mapValues.iterator();
        while (valueIt.hasNext()) {
        Object val = valueIt.next();
        Iterator keyIt = mapKeys.iterator();
        while (keyIt.hasNext()) {
        Object key = keyIt.next();
        if (passedMap.get(key).toString().equals(val.toString())) {
        passedMap.remove(key);
        mapKeys.remove(key);
        someMap.put(key, val);
        break;
        }
        }
        }
        return someMap;
        }

}

decimal precision erroron Solution

to solve decimal precision erroron while doing division need to pass MathContext.DECIMAL32 in division method

Reversing Map

import java.util.Enumeration;
import java.util.ResourceBundle;
public class ResourceBundleTest {
public static void main(String[] args) {
    ResourceBundle rb = ResourceBundle.getBundle("test.bundletest.mybundle");
   Map map=new HashMap();
   Enumeration <String> keys = rb.getKeys();
   while (keys.hasMoreElements()) {
      String key = keys.nextElement();
      String value = rb.getString(key);
     // Saving values in reverse manner
      map.put(value,key);
      System.out.println(key + ": " + value);
    }
}

}

Concurrent Modification Exception Solution

When you try to add and remove items from the Collection/List then it will throw Concurrent Modification Exception ,to avoid that we need to use below code.
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); )
{
 iter.next();
iter.remove();

}

How to copy file in Java

package com.sreedhar.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

        InputStream inStream = null;
    OutputStream outStream = null;

        try{

            File afile =new File("Afile.txt");
            File bfile =new File("Bfile.txt");

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes
            while ((length = inStream.read(buffer)) &gt; 0){

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            System.out.println("File is copied successful!");

        }catch(IOException e){
            e.printStackTrace();
        }
    }

}

Cipher File Encryption

package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class CipherExample {

    public static void main(String[] args) {
        try {
            String key = "squirrel123"; // needs to be at least 8 characters for DES

            FileInputStream fis = new FileInputStream("original.txt");
            FileOutputStream fos = new FileOutputStream("encrypted.txt");
            encrypt(key, fis, fos);

            FileInputStream fis2 = new FileInputStream("encrypted.txt");
            FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
            decrypt(key, fis2, fos2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
    }

    public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
    }

    public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {

        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey desKey = skf.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE

        if (mode == Cipher.ENCRYPT_MODE) {
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            doCopy(cis, os);
        } else if (mode == Cipher.DECRYPT_MODE) {
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            CipherOutputStream cos = new CipherOutputStream(os, cipher);
            doCopy(is, cos);
        }
    }

    public static void doCopy(InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[64];
        int numBytes;
        while ((numBytes = is.read(bytes)) != -1) {
            os.write(bytes, 0, numBytes);
        }
        os.flush();
        os.close();
        is.close();
    }


}