Importing and debugging Eclipse projects in IntelliJ IDEA

Last week I faced a situation to import some Eclipse projects to IntelliJ IDEA, my default Java IDE. IntelliJ IDEA supports this integration, just go to File > New > Project from Existing Sources… and select a directory where Eclipse .project or .classpath files are located.

The project was imported successfully, it had some test compilation errors and it was all done for that moment. But, after running the project, I noted that I couldn’t debug some classes as well as I got used at Eclipse.

It was because, by default, IntelliJ IDEA uses the javac compiler and Eclipse has its own Java compiler that is part of JDT core. IntelliJ IDEA doesn’t proceed on code compilation when it finds the first error, even for test code or code that isn’t part of the build. The Eclipse compiler is able to proceed on code compilation even if it has compilation errors, so it is possible to run / debug code that doesn’t compile at all.

The solution, in this case, is to switch IntelliJ IDEA to use the Eclipse compiler. Just go to File > Settings > Build, Execution, Deployment > Compiler > Java compiler and change the drop down box "Use compiler:" to Eclipse and that is done.

I did that and now I am able to run / debug the Eclipse project using IntelliJ IDEA very well.

I have found the solution here:

Enable Partial Compile IntelliJ
What is the difference between javac and the Eclipse compiler?

Have you faced a situation like this? Have you done another solution than mine? Drop your comments here! 🙂

Tags: , , , ,

Integration tests in a Gradle build

Here is an interesting post about how to add integration tests and configure its dependencies in a Gradle build.

Tags: ,

Converting a Map to a List in Java 8, Groovy and Ruby

Some days ago I was developing a task on a Gradle project and I faced with a situation where I had to convert a Map < String, List < String >> to List < Pair >, each pair containing the key and one element from the List<String>.

I decided to compare the solution in three different languages: Java 8 (using lambdas and the Streams API), Groovy and Ruby to see how concise and expressive they would be. Then, I created the Groovy code and it looked like this:

#!/usr/bin/env groovy

def map = ["a" : ["1", "2", "3"], "b" : ["4", "5", "6"], "c" : ["7"]]

println map.collectMany { key, values -> values.collect {value -> [key, value]}}

Running the above code, the result is below:

[[a, 1], [a, 2], [a, 3], [b, 4], [b, 5], [b, 6], [c, 7]]

The Ruby version looked like this:

#!/usr/bin/env ruby

map = { "a" => ["1", "2", "3"], "b" => ["4", "5", "6"], "c" => ["7"] }

p map.collect {|key, values| values.map {|value| [key, value] } }.flatten(1)

The Ruby program generated the following output:

[["a", "1"], ["a", "2"], ["a", "3"], ["b", "4"], ["b", "5"], ["b", "6"], ["c", "7"]]

Below is the Java 8 version, using lambdas, Streams and the Collectors API:

        
        Map> values = new HashMap<>();
        values.put("a", Arrays.asList("1", "2", "3"));
        values.put("b", Arrays.asList("4", "5", "6"));
        values.put("c", Collections.singletonList("7"));

        final List result = values
                .entrySet()
                .stream()
                .collect(ArrayList::new,
                        (pairs, entry) -> pairs.addAll(entry
                                .getValue()
                                .stream()
                                .map(value -> new Pair(entry.getKey(), value))
                                .collect(Collectors.toList())),
                        List::addAll);

private static class Pair {

    private final String first;
    private final String second;

    public Pair(String first, String second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public String toString() {
        return "Pair{first='" + first + "', second='" + second + "'}";
    }
}

Running the Java 8 version produced the following output:

[Pair{first='a', second='1'}, Pair{first='a', second='2'}, 
Pair{first='a', second='3'}, Pair{first='b', second='4'}, 
Pair{first='b', second='5'}, Pair{first='b', second='6'}, 
Pair{first='c', second='7'}]

The Groovy and Ruby version are very expressive and concise. Note the use of the collectMany method on the Groovy version and the use of the flatten method on the Ruby version to flatten the result list into a single list of pairs.
The Java 8 version made use of the collect method of the Stream API, to collect the results in a list of Pair instances, each one holding the key and value of each element from the List< String >.

What do you think about this comparison? Leave your comments here!

Tags: , , , , , , ,

JavaCodeKata – Lambdas

I’ve came across that kata from @brjavaman and @yanaga to teach lambdas, one of the new features of JDK 8.

There are some unit tests to validate the solution. I’ve found it a good opportunity to exercise the use of lambdas so I decided to solve it. Below is my solution to this kata.

The first method should take the String list and sort all the String elements in ascending (ASCII) order:

    /**
     * This method should take the String List and sort all the String elements in ascending (ASCII) order.
     *
     * @return The sorted values in ascending ASCII order.
     */
    public List getSortedStrings() {
        return values
                .stream()
                .sorted()
                .collect(Collectors.toList());
    }

The other method should take the String list and:

  1. filter the elements that contains one or more digits
  2. transform (map) the remaining Strings into Integers
  3. sort the Integers in ascending order
        
    /**
     * This method should take the String List and:
     * 
    *
  1. filter the elements that contains one or more digits;
  2. *
  3. transform (map) the remaining Strings into Integers;
  4. *
  5. sort the Integers in ascending order.
  6. *
* * @return */ public List getSortedIntegers() { return values .stream() .filter(s -> s.matches("\\d+")) .map(Integer::valueOf) .sorted() .collect(Collectors.toList()); }

The last method should take the String list and:

  1. filter the elements that contains one or more digits
  2. transform (map) the remaining Strings into Integers
  3. sort the Integers in descending order
    
    /**
     * This method should take the String List and:
     * 
    *
  1. filter the elements that contains one or more digits;
  2. *
  3. transform (map) the remaining Strings into Integers;
  4. *
  5. sort the Integers in descending order.
  6. *
* * @return */ public List getSortedDescendingIntegers() { return values .stream() .filter(s -> s.matches("\\d+")) .map(Integer::valueOf) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); }

Note that the steps filter the elements that contains one or more digits and transform (map) the remaining Strings into Integers are identical. So I decided to extract the partial Stream into a method with the Extract Method refactoring support on IntelliJ IDEA:

    private Stream integersWithOneOrMoreDigits() {
        return values
                .stream()
                .filter(s -> s.matches("\\d+"))
                .map(Integer::valueOf);
    }

Then I refactored the the solution to use the new extracted method:

    
    public List getSortedIntegers() {
        return integersWithOneOrMoreDigits()
                .sorted()
                .collect(Collectors.toList());
    }
    public List getSortedDescendingIntegers() {
        return integersWithOneOrMoreDigits()
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());
    }

I re-run the tests and they all passed. What do you think about this solution? Do you suggest other ones?

K Palindromes puzzle

Here we have the K Palindromes puzzle from Javalobby:

You probably already know what a palindrome is: a string to results in the same word, whether read left to right, or right to left. A K Palindrome is when a string can be tranformed into a palindrome by changing K characters at most. Regular palindromes have K=0.

Your challenge today is to write a method which takes a string and a value for k and returns true if it the string qualifies as a K palindrome.

Below is the code in Ruby. Our input string is omississimo and it’s a 0 palindrome String.

def isKPalindrome(s, k)
	chars = s.chars.to_a
	limit = chars.size - 1
	count = chars[0...chars.size / 2].each_index.count {|i| !chars[i].eql?(chars[limit - i])}
	k == count ? true : false
end

puts(isKPalindrome("omississimo", 0)) #true

The output is true. Do you have another solution? Drop your comments here!

Tags: , , , , , , ,

Minimum difference puzzle in Ruby

Folks, here we are for another puzzle from Javalobby:

Given two arrays, sorted and exactly the same length, write a function that finds a pair of numbers – one from each of the arrays – such that the difference between both is as small as possible.

Suppose our input arrays are [1,2,3,4,5] and [6,7,8,9,10]. Below is my solution in Ruby, it’s a one liner code :-):

[1,2,3,4,5].product([6,7,8,9,10]).map {|x, y| [x, y, (x-y).abs]}.sort { |a, b| a.last<=> b.last }.first.take(2)

The output is [5, 6].

Have another solution? Leave your comments here!

Tags: , , , , , , ,

Balancing arrays puzzle in Ruby

Here we are for another puzzle from Javalobby:

Given an array of numbers, return the index at which the array can be balanced by all numbers on the left side add up the the sum of all numbers of the right side.

For example, an array with [1,5,6,7,9,10] can be balanced by splitting the array at position 4

Here is the solution in Ruby:

v=[1,5,6,7,9,10];sum = v.reduce(:+);count=0;index = (0...v.size).detect { |i| count += v[i]; count * 2 == sum};index == nil ? nil : index + 1

The input array [1,5,6,7,9,10] will split the array at position 4, as stated above.

Any other solutions? Drop comments here 🙂

Tags: , , , , , , ,

Finding the second highest frequency

It’s been a long time since I posted for the last time, but I promise I’ll try to keep this blog up-to-date 🙂

One of the purposes of this blog is to explore new technologies and recently I’ve been studying Ruby solving some puzzles posted by on JavaLobby.

The problem is about finding the second highest frequency of a character in a String. Below is the Ruby code, using the powerful concept of Ruby closures.

v="aabbbc".chars;h=Hash[v.map{|k| [k, v.count(k)] }];max=h.values.max;found=h.select { |k, v| v < max};found.keys.first if found

For the input String "aabbbc", the result is "a". I could done it in a more OOP style, but I chose a more concise solution :-)

If you have another version in Ruby, feel free to post a comment!

Tags: , , , , ,

Undo svn add operation

If you want to cancel an svn add operation, do not use svn delete or svn remove, according to this post. You can issue the following command to undo a svn add:

svn revert --recursive your_folder

This tip was very useful for me today :-)

Tags: , , ,

Checkout only one file from Subversion

I was wondering how to checkout only one folder/file from SVN when I found this interesting tip. The command I issued to do it is the following:

svn co <url_of_big_dir> <target> –depth empty

The above command checkout only one versioned directory, with its content empty. Now it’s possible to add other files and directories under the directory who was checked out.

Tags: , , , ,