Search code examples
javaidefolding

Is it possible in any Java IDE to collapse the type definitions in the source code?


Lately I often have to read Java code like this:

LinkedHashMap<String, Integer> totals =  new LinkedHashMap<String, Integer>(listOfRows.get(0))
for (LinkedHashMap<String, Integer> row : (ArrayList<LinkedHashMap<String,Integer>>) table.getValue()) {    
    for(Entry<String, Integer> elem : row.entrySet()) {
        String colName=elem.getKey();
        int Value=elem.getValue();
        int oldValue=totals.get(colName);

        int sum = Value + oldValue;
        totals.put(colName, sum);
    }
}

Due to the long and nested type definitions the simple algorithm becomes quite obscured. So I wished I could remove or collapse the type definitions with my IDE to see the Java code without types like:

totals =  new (listOfRows.get(0))
for (row : table.getValue()) {    
    for(elem : row.entrySet()) {
        colName=elem.getKey();
        Value=elem.getValue();
        oldValue=totals.get(colName);

        sum = Value + oldValue;
        totals.put(colName, sum);
    }
}

The best way of course would be to collapse the type definitions, but when moving the mouse over a variable show the type as a tooltip. Is there a Java IDE or a plugin for an IDE that can do this?


Solution

  • IntelliJ IDEA will convert the types on the right-hand side of a declaration to <~>. So that:

    Map<Integer, String> m = new HashMap<Integer, String>();
    

    Will appear folded as:

    Map<Integer, String> m = new HashMap<~>();
    

    This is settable via the Editor / Code Folding / Generic Constructor and Method Parameters property and the community edition of the IDE is free.


    Or you could use Scala, which has type inference:

    val totals = new mutable.Map[String, Int]
    for { 
        row <- table.getValue
        (colName, value) <- row.entrySet 
    } totals += (colName -> (value + totals.get(colName) getOrElse 0)