Pages

Showing posts with label core java. Show all posts
Showing posts with label core java. Show all posts

Tuesday, April 11, 2017

Checking that 2 Lists have elements in common

How many times have we created loops to check if any of the elements of one list are contained among any of the elements of other list?

Lists have a contains() and also a containsAll() methods but they doesn't seem to do what we want and we end up writing spaghetti that looks like this often:

1:  boolean isSafeToEat(List<String> allergicFoods) {  
2:    for (String ingredient : getIngredients()) {  
3:      if (allergicFoods.contains(ingredient)) {  
4:        return false;  
5:      }  
6:    }  
7:    return true;  
8:  }  


Sometimes we forget that the Java API has so many useful things. Like this disjoint() method, from Collections.

1:    boolean isSafeToEat(List<String> allergicFoods) {  
2:      return Collections.disjoint(ingredients, allergicFoods);  
3:    }  

Its not Java 8 ;) its being there for a bit already, have a look at this docs:
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#disjoint(java.util.Collection,%20java.util.Collection)

Monday, November 12, 2012

The all mighty regex

We often use regular expressions when programming.
In many occasions they make our live easier and help us avoiding lots of lines of code. I was just navigating around, and by a chance I found a blog that shows probably the one of coolest regex.
Have a look at this regular expression:


                                                                    
Personally I never used this one before. The thing that I find cool about it is, its simplicity.
For those who are not familiar with regex terminology, this one matches a character that is within(inclusive )the characters SPACE and tilde in the ASCII table.



Hehe.. cool, isn't it? I am looking forward to use it somewhere.

I can't resist, let's just give it a quick try :)

1:  import java.util.regex.Matcher;  
2:  import java.util.regex.Pattern;  
3:  public class AllMightyRegex {  
4:       public static void main(String[] args) {  
5:            String someASCIICharacters = "!#$%&\'()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";  
6:            Pattern pattern = Pattern.compile("[ -~]");  
7:            Matcher matcher;   
8:            for (int variableIndex = 0; variableIndex < someASCIICharacters.length(); variableIndex++) {  
9:                 matcher = pattern.matcher(getCharAt(someASCIICharacters, variableIndex));  
10:                 if(matcher.matches()) {  
11:                      System.out.println("The character: " + getCharAt(someASCIICharacters, variableIndex) + " matches the pattern");  
12:                 }  
13:            }  
14:       }  
15:       private static String getCharAt(String someASCIICharacters,  
16:                 int variableIndex) {  
17:            return someASCIICharacters.charAt(variableIndex) + "";  
18:       }  
19:  }  


Friday, August 10, 2012

Dynamic initialization of HashMap using double braces

Often we have to work with data structures like: Maps, Arrays,Sets...
And many times it is just more comfortable to initialize them dynamically.

In the following example i use double brace initialization technique to dynamically initialize a map that uses a constant as a key and a List as a value. When we want to initialize this types of structures in a dynamical way, this approach is probably the most comfortable and easy.


1:  new HashMap<ProductCategories, List<Products>>() {  
2:                 {  
3:                      put(ProductCategories.DAIRY_PRODUCTS,  
4:                                new ArrayList<Products>() {  
5:                                     {  
6:                                          add(Products.CHEESE);  
7:                                          add(Products.SOUR_CREAM);  
8:                                          add(Products.YOGURTH);  
9:                                     }  
10:                                 }  
11:                      );  
12:                      put(ProductCategories.MEAT,   
13:                                new ArrayList<Products>() {  
14:                                     {  
15:                                          add(Products.BEEF);  
16:                                          add(Products.CHICKEN);  
17:                                          add(Products.TURKEY);  
18:                                     }  
19:                                }  
20:                      );  
21:                      put(ProductCategories.VEGETABLES,   
22:                                new ArrayList<Products>() {  
23:                                     {  
24:                                          add(Products.TOMATO);  
25:                                          add(Products.ONION);  
26:                                          add(Products.CAGABE);  
27:                                     }  
28:                                }  
29:                      );  
30:                 }  
31:            };  

Wednesday, May 30, 2012

How many lines of java code does your workspace contain

Did you ever wonder how many lines of java code does your workspace have? Here a little program that can help you find out:

Class 1:

1:  package sample;  
2:  import java.io.File;  
3:  import java.util.Scanner;  
4:  public class LinesOfCodeCounter {  
5:    private long linesOfCode;  
6:    private int scannedProjects;  
7:    public void analizeFolder(File file) {  
8:  //Check if the current file is a file or a folder  
9:      if (file.isDirectory()) {  
10:  //If it is a folder get the inner files  
11:        File[] filesInFolder = file.listFiles();  
12:  //For each of the inner files check if it is a folder or a file(Recursion)  
13:        for (File innerFile : filesInFolder) {  
14:          analizeFolder(innerFile);  
15:        }  
16:      } else if (file.isFile()) {  
17:  //When you find a file that is not a folder, check if it contains java code  
18:        if (file.getName().endsWith(".java")) {  
19:  //Scan the file  
20:          scanFile(file);  
21:        }  
22:      }  
23:    }  
24:    public void scanFile(File file) {  
25:      try {  
26:        Scanner fileScanner = new Scanner(file);  
27:  //Read each line of code  
28:        String tempDataHolder = fileScanner.nextLine();  
29:  //While the file contain lines of code count them  
30:        while (fileScanner.hasNext()) {  
31:          linesOfCode++;  
32:          tempDataHolder = fileScanner.nextLine();  
33:        }  
34:      } catch (Exception ex) {  
35:        ex.printStackTrace();  
36:      }  
37:    }  
38:    public long getLinesOfCode() {  
39:      return linesOfCode;  
40:    }  
41:  }  



Class 2:
1:  package sample;  
2:  import java.io.File;  
3:  public class Main {  
4:    public static void main(String[] args) {  
5:      //The workspace root  
6:      final File workSpaceRoot = new File("D:\\JavaWorkspace");  
7:      //Check if the root contains files inside its self  
8:      LinesOfCodeCounter counter = new LinesOfCodeCounter();  
9:      counter.analizeFolder(workSpaceRoot);  
10:      System.out.print(counter.getLinesOfCode());  
11:    }    
12:  }  

Wednesday, April 4, 2012

The use of marker interfaces

When programming, we often use interfaces, to hide the realization. But in some occasions, we want just want to group classes. We call marker interfaces, to empty interfaces(No methods at all). 

A very simple example is the Serializabe interface: 
It has no methods at all, but all classes that whant to be writen into some kind of file, or network stream, need to implement Serializable. 

In the same way, you could make a Program with classes like Dog,Bird,Cow... and you dont need to add them any functionality extra, just to mark them, because somewhere in the code there will be a method that could look like this : String method(Flyer); So you need to create a marker interface called Flyer, to mark the animals that can fly(So you dont need to have unnecesary variables boolean like isFlyer, in classes Dog and Cow). 




maybe i should give a more pragmatical example, so it is easier to understand. Lets try:

See the folowing code:

1:  //Marking interface flyer  
2:  public interface Flyer {  
3:  //If this is a marker interface, there is no methods in it  
4:  }  
5:  public class Mammal {  
6:  private String someVariable;  
7:  }  
8:  public class Cow extends Mammal {  
9:  //Some code specific to cows  
10:  }  
11:  public class Bat extends Mammal implements Flyer {  
12:  //Some code specific to Mammal  
13:  //Note that the Bat is marked as a Flyer  
14:  }  



I think this example more or less explains my point. Bats are mammals and can fly,so why would you have a boolean variable that can be either true or false, when you can just mark the class. Another reason why i think this is a good approach, i because if the future we need to upgrade the program, we can just mark the classes that can fly with the interface.

Imagine somewhere in the program there is a method like this:

1:  public class AirportControl {  
2:  public void testFly(Animal a) {  
3:  if(a instanceof Flyer) {  
4:  //Perform a test fly  
5:  }  
6:  public void testFly(Vehicle v) {  
7:  if(a instanceof Flyer) {  
8:  //Perform a test fly  
9:  }  
10:  }  


I think this approach is pretty flexible,when creating your domain model.

Share with your friends