Tuesday, June 5, 2012

Google Guava Collections are awesome

Guava introduces a number of new collection types that are not in the JDK, but that we have found to be broadly useful. These are all designed to coexist happily with the JDK collections framework, without shoehorning things into the JDK collection abstractions.


1 line joiner : String groupConfiguration = Joiner.on(SMSConstants.commaDelimiter).join(uniqGroupConcats);
1 line splitter : String ilcId = Lists.newArrayList(Splitter.on(SMSConstants.rowidFieldDelimiter).split(Bytes.toString(values.getRow()))).get(1);

1 line to print the map values : Joiner.on("\n").withKeyValueSeparator("=>").join(defaultExpectedPS)

MultiMap : A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

List Partition : Lists.partition is again easy to split list into multiple list and loop it.

http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table

In our application i am trying to use Table from guava. Below is the example :


             // We can create a table in java memory using guava ;)
Table> ilcGroupConfiguration =   HashBasedTable.create();

ilcGroupConfiguration.put("SCID 1", "G1+G2", Arrays.asList("Zigbee1", "Zigbee2"));
ilcGroupConfiguration.put("SCID 2", "G1+G2+G3", Arrays.asList("Zigbee3", "Zigbee4"));

// RowKeySet() :  Returns a set of row keys that have one or more values in the table.
for (String ilcGroup1 : ilcGroupConfiguration.rowKeySet()) {

System.out.println("Keys SC : " + ilcGroup1);
// row(rowKey) : Returns a view of all mappings that have the given row key.
Map> ilcGroupCommand = new HashMap>();
ilcGroupCommand = ilcGroupConfiguration.row(ilcGroup1);

for (String ilcGroupCommandgc : ilcGroupCommand.keySet()) {
System.out.println("Keys GC : " + ilcGroupCommandgc);
List ilcIds = ilcGroupCommand.get(ilcGroupCommandgc);
System.out.println("Keys ILC Ids : " + ilcIds);
}
}

Lists.partition is again easy. If you want to split the for loop every 1000 use lists.partition
for (List devices : Lists.partition(devicesLists, 1000) {
    for (Device device : devices) {
    }
}

Amazing Things mentioned about guava examples : http://blog.solidcraft.eu/2010/10/googole-guava-v07-examples.html
OrderingExplainedGood 

No comments :

// Below script tag for SyntaxHighLighter