You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@calcite.apache.org by jh...@apache.org on 2018/07/09 07:49:23 UTC

[01/30] calcite git commit: [CALCITE-2403] Upgrade quidem to 0.9

Repository: calcite
Updated Branches:
  refs/heads/master 5bbc501a5 -> 3fa294556


[CALCITE-2403] Upgrade quidem to 0.9


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/c749f25d
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/c749f25d
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/c749f25d

Branch: refs/heads/master
Commit: c749f25dcb8b0f9be41014af181666b6eed6350b
Parents: d59b639
Author: Julian Hyde <jh...@apache.org>
Authored: Thu Jul 5 16:08:02 2018 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 10:16:26 2018 -0700

----------------------------------------------------------------------
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/c749f25d/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index eb1c58c..8ac7193 100644
--- a/pom.xml
+++ b/pom.xml
@@ -124,7 +124,7 @@ limitations under the License.
     <pig.version>0.16.0</pig.version>
     <aggdesigner.version>6.0</aggdesigner.version>
     <postgresql.version>9.3-1102-jdbc3</postgresql.version>
-    <quidem.version>0.8</quidem.version>
+    <quidem.version>0.9</quidem.version>
     <scala.version>2.10.3</scala.version>
     <scott-data-hsqldb.version>0.1</scott-data-hsqldb.version>
     <servlet.version>3.0.1</servlet.version>


[02/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/main/java/org/apache/calcite/chinook/EnvironmentFairy.java
----------------------------------------------------------------------
diff --git a/plus/src/main/java/org/apache/calcite/chinook/EnvironmentFairy.java b/plus/src/main/java/org/apache/calcite/chinook/EnvironmentFairy.java
index 34c005f..4896512 100644
--- a/plus/src/main/java/org/apache/calcite/chinook/EnvironmentFairy.java
+++ b/plus/src/main/java/org/apache/calcite/chinook/EnvironmentFairy.java
@@ -26,11 +26,8 @@ package org.apache.calcite.chinook;
  */
 public class EnvironmentFairy {
 
-  private static final ThreadLocal<User> USER = new ThreadLocal<User>() {
-    @Override protected User initialValue() {
-      return User.ADMIN;
-    }
-  };
+  private static final ThreadLocal<User> USER =
+      ThreadLocal.withInitial(() -> User.ADMIN);
 
   private EnvironmentFairy() {
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/test/java/org/apache/calcite/adapter/os/OsAdapterTest.java
----------------------------------------------------------------------
diff --git a/plus/src/test/java/org/apache/calcite/adapter/os/OsAdapterTest.java b/plus/src/test/java/org/apache/calcite/adapter/os/OsAdapterTest.java
index 50e80b7..a2d7f78 100644
--- a/plus/src/test/java/org/apache/calcite/adapter/os/OsAdapterTest.java
+++ b/plus/src/test/java/org/apache/calcite/adapter/os/OsAdapterTest.java
@@ -24,23 +24,20 @@ import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.util.Holder;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-
 import org.hamcrest.CoreMatchers;
 import org.junit.Assume;
 import org.junit.Test;
 
 import java.io.ByteArrayInputStream;
 import java.io.File;
-import java.io.FilenameFilter;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.nio.charset.StandardCharsets;
-import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.notNullValue;
@@ -76,12 +73,7 @@ public class OsAdapterTest {
         return false; // abandon hope
       }
       File[] files =
-          f.listFiles(
-              new FilenameFilter() {
-                public boolean accept(File dir, String name) {
-                  return name.equals(".git");
-                }
-              });
+          f.listFiles((dir, name) -> name.equals(".git"));
       if (files != null && files.length == 1) {
         return true; // there is a ".git" subdirectory
       }
@@ -93,20 +85,16 @@ public class OsAdapterTest {
     Assume.assumeFalse("Skip: the 'du' table does not work on Windows",
         isWindows());
     sql("select * from du")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  assertThat(r.next(), is(true));
-                  assertThat(r.getInt(1), notNullValue());
-                  assertThat(r.getString(2), CoreMatchers.startsWith("./"));
-                  assertThat(r.wasNull(), is(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            assertThat(r.next(), is(true));
+            assertThat(r.getInt(1), notNullValue());
+            assertThat(r.getString(2), CoreMatchers.startsWith("./"));
+            assertThat(r.wasNull(), is(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testDuFilterSortLimit() {
@@ -114,22 +102,18 @@ public class OsAdapterTest {
         isWindows());
     sql("select * from du where path like '%/src/test/java/%'\n"
         + "order by 1 limit 2")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  assertThat(r.next(), is(true));
-                  assertThat(r.getInt(1), notNullValue());
-                  assertThat(r.getString(2), CoreMatchers.startsWith("./"));
-                  assertThat(r.wasNull(), is(false));
-                  assertThat(r.next(), is(true));
-                  assertThat(r.next(), is(false)); // because of "limit 2"
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            assertThat(r.next(), is(true));
+            assertThat(r.getInt(1), notNullValue());
+            assertThat(r.getString(2), CoreMatchers.startsWith("./"));
+            assertThat(r.wasNull(), is(false));
+            assertThat(r.next(), is(true));
+            assertThat(r.next(), is(false)); // because of "limit 2"
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testFiles() {
@@ -144,61 +128,49 @@ public class OsAdapterTest {
     Assume.assumeFalse("Skip: the 'ps' table does not work on Windows",
         isWindows());
     sql("select * from ps")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  assertThat(r.next(), is(true));
-                  final StringBuilder b = new StringBuilder();
-                  final int c = r.getMetaData().getColumnCount();
-                  for (int i = 0; i < c; i++) {
-                    b.append(r.getString(i + 1)).append(';');
-                    assertThat(r.wasNull(), is(false));
-                  }
-                  assertThat(b.toString(), notNullValue());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            assertThat(r.next(), is(true));
+            final StringBuilder b = new StringBuilder();
+            final int c = r.getMetaData().getColumnCount();
+            for (int i = 0; i < c; i++) {
+              b.append(r.getString(i + 1)).append(';');
+              assertThat(r.wasNull(), is(false));
+            }
+            assertThat(b.toString(), notNullValue());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testPsDistinct() {
     Assume.assumeFalse("Skip: the 'ps' table does not work on Windows",
         isWindows());
     sql("select distinct `user` from ps")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  assertThat(r.next(), is(true));
-                  assertThat(r.getString(1), notNullValue());
-                  assertThat(r.wasNull(), is(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            assertThat(r.next(), is(true));
+            assertThat(r.getString(1), notNullValue());
+            assertThat(r.wasNull(), is(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testGitCommits() {
     Assume.assumeTrue("no git", hasGit());
     sql("select count(*) from git_commits")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  assertThat(r.next(), is(true));
-                  assertThat(r.getString(1), notNullValue());
-                  assertThat(r.wasNull(), is(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            assertThat(r.next(), is(true));
+            assertThat(r.getString(1), notNullValue());
+            assertThat(r.wasNull(), is(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testGitCommitsTop() {
@@ -213,39 +185,32 @@ public class OsAdapterTest {
     Assume.assumeFalse("Skip: the 'files' table does not work on Windows",
         isWindows());
     sql("select * from vmstat")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  assertThat(r.next(), is(true));
-                  final int c = r.getMetaData().getColumnCount();
-                  for (int i = 0; i < c; i++) {
-                    assertThat(r.getLong(i + 1), notNullValue());
-                    assertThat(r.wasNull(), is(false));
-                  }
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            assertThat(r.next(), is(true));
+            final int c = r.getMetaData().getColumnCount();
+            for (int i = 0; i < c; i++) {
+              assertThat(r.getLong(i + 1), notNullValue());
+              assertThat(r.wasNull(), is(false));
+            }
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testStdin() throws SQLException {
     try (Hook.Closeable ignore = Hook.STANDARD_STREAMS.addThread(
-        new Function<Holder<Object[]>, Void>() {
-          public Void apply(Holder<Object[]> o) {
-            final Object[] values = o.get();
-            final InputStream in = (InputStream) values[0];
-            final String s = "First line\n"
-                + "Second line";
-            final ByteArrayInputStream in2 =
-                new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
-            final OutputStream out = (OutputStream) values[1];
-            final OutputStream err = (OutputStream) values[2];
-            o.set(new Object[] {in2, out, err});
-            return null;
-          }
+        (Consumer<Holder<Object[]>>) o -> {
+          final Object[] values = o.get();
+          final InputStream in = (InputStream) values[0];
+          final String s = "First line\n"
+              + "Second line";
+          final ByteArrayInputStream in2 =
+              new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
+          final OutputStream out = (OutputStream) values[1];
+          final OutputStream err = (OutputStream) values[2];
+          o.set(new Object[] {in2, out, err});
         })) {
       assertThat(foo("select count(*) as c from stdin"), is("2\n"));
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/test/java/org/apache/calcite/adapter/tpcds/TpcdsTest.java
----------------------------------------------------------------------
diff --git a/plus/src/test/java/org/apache/calcite/adapter/tpcds/TpcdsTest.java b/plus/src/test/java/org/apache/calcite/adapter/tpcds/TpcdsTest.java
index f100197..b4c079f 100644
--- a/plus/src/test/java/org/apache/calcite/adapter/tpcds/TpcdsTest.java
+++ b/plus/src/test/java/org/apache/calcite/adapter/tpcds/TpcdsTest.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.adapter.tpcds;
 
-import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.plan.RelTraitDef;
 import org.apache.calcite.prepare.Prepare;
@@ -35,8 +34,6 @@ import org.apache.calcite.util.Bug;
 import org.apache.calcite.util.Holder;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
-
 import net.hydromatic.tpcds.query.Query;
 
 import org.junit.Ignore;
@@ -44,6 +41,7 @@ import org.junit.Test;
 
 import java.util.List;
 import java.util.Random;
+import java.util.function.Consumer;
 
 /** Unit test for {@link org.apache.calcite.adapter.tpcds.TpcdsSchema}.
  *
@@ -51,20 +49,13 @@ import java.util.Random;
  * command-line.
  * (See {@link org.apache.calcite.test.CalciteAssert#ENABLE_SLOW}.)</p> */
 public class TpcdsTest {
-  private static Function<Pair<List<Prepare.Materialization>, Holder<Program>>, Void> handler(
-      final boolean bushy, final int minJoinCount) {
-    return new Function<Pair<List<Prepare.Materialization>, Holder<Program>>,
-        Void>() {
-      public Void apply(
-          Pair<List<Prepare.Materialization>, Holder<Program>> pair) {
-        pair.right.set(
-            Programs.sequence(
-                Programs.heuristicJoinOrder(Programs.RULE_SET, bushy,
-                    minJoinCount),
-                Programs.CALC_PROGRAM));
-        return null;
-      }
-    };
+  private static Consumer<Pair<List<Prepare.Materialization>, Holder<Program>>>
+      handler(boolean bushy, int minJoinCount) {
+    return pair -> pair.right.set(
+        Programs.sequence(
+            Programs.heuristicJoinOrder(Programs.RULE_SET, bushy,
+                minJoinCount),
+            Programs.CALC_PROGRAM));
   }
 
   private static String schema(String name, String scaleFactor) {
@@ -206,13 +197,9 @@ public class TpcdsTest {
   public Frameworks.ConfigBuilder config() throws Exception {
     final Holder<SchemaPlus> root = Holder.of(null);
     CalciteAssert.model(TPCDS_MODEL)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection input) {
-                root.set(input.getRootSchema().getSubSchema("TPCDS"));
-                return null;
-              }
-            });
+        .doWithConnection(connection -> {
+          root.set(connection.getRootSchema().getSubSchema("TPCDS"));
+        });
     return Frameworks.newConfigBuilder()
         .parserConfig(SqlParser.Config.DEFAULT)
         .defaultSchema(root.get())

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/test/java/org/apache/calcite/adapter/tpch/TpchTest.java
----------------------------------------------------------------------
diff --git a/plus/src/test/java/org/apache/calcite/adapter/tpch/TpchTest.java b/plus/src/test/java/org/apache/calcite/adapter/tpch/TpchTest.java
index eaf9c91..3d9de10 100644
--- a/plus/src/test/java/org/apache/calcite/adapter/tpch/TpchTest.java
+++ b/plus/src/test/java/org/apache/calcite/adapter/tpch/TpchTest.java
@@ -17,12 +17,10 @@
 package org.apache.calcite.adapter.tpch;
 
 import org.apache.calcite.plan.RelOptUtil;
-import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.util.TestUtil;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 
 import org.junit.Ignore;
@@ -831,14 +829,11 @@ public class TpchTest {
   @Test public void testQuery02Conversion() {
     query(2, true)
         .enable(ENABLE)
-        .convertMatches(
-          new Function<RelNode, Void>() {
-            public Void apply(RelNode relNode) {
-              String s = RelOptUtil.toString(relNode);
-              assertThat(s, not(containsString("Correlator")));
-              return null;
-            }
-          });
+        .convertMatches(relNode -> {
+          String s = RelOptUtil.toString(relNode);
+          assertThat(s, not(containsString("Correlator")));
+          return null;
+        });
   }
 
   @Test public void testQuery03() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/codegen/includes/parserImpls.ftl
----------------------------------------------------------------------
diff --git a/server/src/main/codegen/includes/parserImpls.ftl b/server/src/main/codegen/includes/parserImpls.ftl
index 0fd9b87..82210a0 100644
--- a/server/src/main/codegen/includes/parserImpls.ftl
+++ b/server/src/main/codegen/includes/parserImpls.ftl
@@ -70,7 +70,7 @@ SqlCreate SqlCreateForeignSchema(Span s, boolean replace) :
 SqlNodeList Options() :
 {
     final Span s;
-    final List<SqlNode> list = Lists.newArrayList();
+    final List<SqlNode> list = new ArrayList<SqlNode>();
 }
 {
     <OPTIONS> { s = span(); } <LPAREN>
@@ -102,7 +102,7 @@ void Option(List<SqlNode> list) :
 SqlNodeList TableElementList() :
 {
     final Span s;
-    final List<SqlNode> list = Lists.newArrayList();
+    final List<SqlNode> list = new ArrayList<SqlNode>();
 }
 {
     <LPAREN> { s = span(); }
@@ -194,7 +194,7 @@ void TableElement(List<SqlNode> list) :
 SqlNodeList AttributeDefList() :
 {
     final Span s;
-    final List<SqlNode> list = Lists.newArrayList();
+    final List<SqlNode> list = new ArrayList<SqlNode>();
 }
 {
     <LPAREN> { s = span(); }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateForeignSchema.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateForeignSchema.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateForeignSchema.java
index 96ce3f9..68f24c4 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateForeignSchema.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateForeignSchema.java
@@ -49,6 +49,7 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -71,7 +72,7 @@ public class SqlCreateForeignSchema extends SqlCreate
       SqlIdentifier name, SqlNode type, SqlNode library,
       SqlNodeList optionList) {
     super(OPERATOR, pos, replace, ifNotExists);
-    this.name = Preconditions.checkNotNull(name);
+    this.name = Objects.requireNonNull(name);
     this.type = type;
     this.library = library;
     Preconditions.checkArgument((type == null) != (library == null),

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateMaterializedView.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateMaterializedView.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateMaterializedView.java
index 9e32429..2ffd6f0 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateMaterializedView.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateMaterializedView.java
@@ -43,10 +43,10 @@ import org.apache.calcite.sql2rel.NullInitializerExpressionFactory;
 import org.apache.calcite.util.ImmutableNullableList;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -68,9 +68,9 @@ public class SqlCreateMaterializedView extends SqlCreate
       boolean ifNotExists, SqlIdentifier name, SqlNodeList columnList,
       SqlNode query) {
     super(OPERATOR, pos, replace, ifNotExists);
-    this.name = Preconditions.checkNotNull(name);
+    this.name = Objects.requireNonNull(name);
     this.columnList = columnList; // may be null
-    this.query = Preconditions.checkNotNull(query);
+    this.query = Objects.requireNonNull(query);
   }
 
   public List<SqlNode> getOperandList() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateSchema.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateSchema.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateSchema.java
index 84eab77..2a04bec 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateSchema.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateSchema.java
@@ -34,9 +34,8 @@ import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.util.ImmutableNullableList;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -54,11 +53,11 @@ public class SqlCreateSchema extends SqlCreate
   SqlCreateSchema(SqlParserPos pos, boolean replace, boolean ifNotExists,
       SqlIdentifier name) {
     super(OPERATOR, pos, replace, ifNotExists);
-    this.name = Preconditions.checkNotNull(name);
+    this.name = Objects.requireNonNull(name);
   }
 
   @Override public List<SqlNode> getOperandList() {
-    return ImmutableNullableList.<SqlNode>of(name);
+    return ImmutableNullableList.of(name);
   }
 
   @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateTable.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateTable.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateTable.java
index 5ae3669..3550831 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateTable.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateTable.java
@@ -73,6 +73,7 @@ import java.lang.reflect.Type;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -92,7 +93,7 @@ public class SqlCreateTable extends SqlCreate
   SqlCreateTable(SqlParserPos pos, boolean replace, boolean ifNotExists,
       SqlIdentifier name, SqlNodeList columnList, SqlNode query) {
     super(OPERATOR, pos, replace, ifNotExists);
-    this.name = Preconditions.checkNotNull(name);
+    this.name = Objects.requireNonNull(name);
     this.columnList = columnList; // may be null
     this.query = query; // for "CREATE TABLE ... AS query"; may be null
   }
@@ -245,7 +246,7 @@ public class SqlCreateTable extends SqlCreate
         ColumnStrategy strategy) {
       this.expr = expr;
       this.type = type;
-      this.strategy = Preconditions.checkNotNull(strategy);
+      this.strategy = Objects.requireNonNull(strategy);
       Preconditions.checkArgument(
           strategy == ColumnStrategy.NULLABLE
               || strategy == ColumnStrategy.NOT_NULLABLE
@@ -299,10 +300,10 @@ public class SqlCreateTable extends SqlCreate
         RelProtoDataType protoRowType,
         InitializerExpressionFactory initializerExpressionFactory) {
       super(name);
-      this.protoStoredRowType = Preconditions.checkNotNull(protoStoredRowType);
-      this.protoRowType = Preconditions.checkNotNull(protoRowType);
+      this.protoStoredRowType = Objects.requireNonNull(protoStoredRowType);
+      this.protoRowType = Objects.requireNonNull(protoRowType);
       this.initializerExpressionFactory =
-          Preconditions.checkNotNull(initializerExpressionFactory);
+          Objects.requireNonNull(initializerExpressionFactory);
     }
 
     public Collection getModifiableCollection() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateType.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateType.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateType.java
index c6d7991..f565126 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateType.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateType.java
@@ -34,9 +34,8 @@ import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.util.ImmutableNullableList;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Parse tree for {@code CREATE TYPE} statement.
@@ -54,7 +53,7 @@ public class SqlCreateType extends SqlCreate
   SqlCreateType(SqlParserPos pos, boolean replace, SqlIdentifier name,
       SqlNodeList attributeDefs, SqlDataTypeSpec dataType) {
     super(OPERATOR, pos, replace, false);
-    this.name = Preconditions.checkNotNull(name);
+    this.name = Objects.requireNonNull(name);
     this.attributeDefs = attributeDefs; // may be null
     this.dataType = dataType; // may be null
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateView.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateView.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateView.java
index e9e3076..4332c27 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateView.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlCreateView.java
@@ -39,10 +39,10 @@ import org.apache.calcite.util.ImmutableNullableList;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -62,9 +62,9 @@ public class SqlCreateView extends SqlCreate
   SqlCreateView(SqlParserPos pos, boolean replace, SqlIdentifier name,
       SqlNodeList columnList, SqlNode query) {
     super(OPERATOR, pos, replace, false);
-    this.name = Preconditions.checkNotNull(name);
+    this.name = Objects.requireNonNull(name);
     this.columnList = columnList; // may be null
-    this.query = Preconditions.checkNotNull(query);
+    this.query = Objects.requireNonNull(query);
   }
 
   public List<SqlNode> getOperandList() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/server/src/main/java/org/apache/calcite/sql/ddl/SqlDropObject.java
----------------------------------------------------------------------
diff --git a/server/src/main/java/org/apache/calcite/sql/ddl/SqlDropObject.java b/server/src/main/java/org/apache/calcite/sql/ddl/SqlDropObject.java
index 523c96e..dacc093 100644
--- a/server/src/main/java/org/apache/calcite/sql/ddl/SqlDropObject.java
+++ b/server/src/main/java/org/apache/calcite/sql/ddl/SqlDropObject.java
@@ -49,7 +49,7 @@ abstract class SqlDropObject extends SqlDrop
   }
 
   public List<SqlNode> getOperandList() {
-    return ImmutableList.<SqlNode>of(name);
+    return ImmutableList.of(name);
   }
 
   @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/site/.gitignore
----------------------------------------------------------------------
diff --git a/site/.gitignore b/site/.gitignore
index aa7624f..74fb5fa 100644
--- a/site/.gitignore
+++ b/site/.gitignore
@@ -1,3 +1,3 @@
 .sass-cache
 Gemfile.lock
-.jekyll-metadata
\ No newline at end of file
+.jekyll-metadata

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/site/README.md
----------------------------------------------------------------------
diff --git a/site/README.md b/site/README.md
index 4b5a108..cee5aa2 100644
--- a/site/README.md
+++ b/site/README.md
@@ -113,4 +113,4 @@ subversion, to publish the site, of course). If the edit is to appear
 on the site immediately, the committer should then cherry-pick the
 change into the "site" branch.  If there have been no feature-related
 changes on the site since the release, then "site" should be a
-fast-forward merge of "master".
\ No newline at end of file
+fast-forward merge of "master".

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/site/docker-compose.yml
----------------------------------------------------------------------
diff --git a/site/docker-compose.yml b/site/docker-compose.yml
index 2827861..eb1d7e7 100644
--- a/site/docker-compose.yml
+++ b/site/docker-compose.yml
@@ -35,4 +35,6 @@ services:
       - ../:/usr/src/calcite
       - maven-repo:/root/.m2
 volumes:
-  maven-repo:
\ No newline at end of file
+  maven-repo:
+
+# End docker-compose.yml

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/spark/src/main/java/org/apache/calcite/adapter/spark/EnumerableToSparkConverterRule.java
----------------------------------------------------------------------
diff --git a/spark/src/main/java/org/apache/calcite/adapter/spark/EnumerableToSparkConverterRule.java b/spark/src/main/java/org/apache/calcite/adapter/spark/EnumerableToSparkConverterRule.java
index d9f2b9e..28dc0a9c 100644
--- a/spark/src/main/java/org/apache/calcite/adapter/spark/EnumerableToSparkConverterRule.java
+++ b/spark/src/main/java/org/apache/calcite/adapter/spark/EnumerableToSparkConverterRule.java
@@ -23,7 +23,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -40,7 +40,7 @@ public class EnumerableToSparkConverterRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableToSparkConverterRule(RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(),
+    super(RelNode.class, (Predicate<RelNode>) r -> true,
         EnumerableConvention.INSTANCE, SparkRel.CONVENTION, relBuilderFactory,
         "EnumerableToSparkConverterRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/spark/src/main/java/org/apache/calcite/adapter/spark/HttpServer.java
----------------------------------------------------------------------
diff --git a/spark/src/main/java/org/apache/calcite/adapter/spark/HttpServer.java b/spark/src/main/java/org/apache/calcite/adapter/spark/HttpServer.java
index abef523..b9dc2b4 100644
--- a/spark/src/main/java/org/apache/calcite/adapter/spark/HttpServer.java
+++ b/spark/src/main/java/org/apache/calcite/adapter/spark/HttpServer.java
@@ -165,21 +165,17 @@ class HttpServer {
   }
 
   private static <E> Iterable<E> iterable(final Enumeration<E> enumeration) {
-    return new Iterable<E>() {
-      public Iterator<E> iterator() {
-        return new Iterator<E>() {
-          public boolean hasNext() {
-            return enumeration.hasMoreElements();
-          }
+    return () -> new Iterator<E>() {
+      public boolean hasNext() {
+        return enumeration.hasMoreElements();
+      }
 
-          public E next() {
-            return enumeration.nextElement();
-          }
+      public E next() {
+        return enumeration.nextElement();
+      }
 
-          public void remove() {
-            throw new UnsupportedOperationException();
-          }
-        };
+      public void remove() {
+        throw new UnsupportedOperationException();
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverter.java
----------------------------------------------------------------------
diff --git a/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverter.java b/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverter.java
index 1c70cbe..1e986e2 100644
--- a/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverter.java
+++ b/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverter.java
@@ -90,7 +90,7 @@ public class JdbcToSparkConverter
     final Expression primitivesLiteral =
         list.append("primitives",
             Expressions.constant(
-                primitives.toArray(new Primitive[primitives.size()])));
+                primitives.toArray(new Primitive[0])));
     final Expression enumerable =
         list.append(
             "enumerable",

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverterRule.java
----------------------------------------------------------------------
diff --git a/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverterRule.java b/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverterRule.java
index f8c30ee..51faf75 100644
--- a/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverterRule.java
+++ b/spark/src/main/java/org/apache/calcite/adapter/spark/JdbcToSparkConverterRule.java
@@ -22,7 +22,7 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -33,7 +33,7 @@ public class JdbcToSparkConverterRule extends ConverterRule {
   /** Creates a JdbcToSparkConverterRule. */
   public JdbcToSparkConverterRule(JdbcConvention out,
       RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(), out,
+    super(RelNode.class, (Predicate<RelNode>) r -> true, out,
         SparkRel.CONVENTION, relBuilderFactory, "JdbcToSparkConverterRule");
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java
----------------------------------------------------------------------
diff --git a/spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java b/spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java
index 8b313ac..3989768 100644
--- a/spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java
+++ b/spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java
@@ -71,7 +71,6 @@ import java.lang.reflect.Type;
 import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.Collections;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
 import java.util.Random;
@@ -396,27 +395,14 @@ public abstract class SparkRules {
     final JavaSparkContext sc = new JavaSparkContext("local[1]", "calcite");
     final JavaRDD<String> file = sc.textFile("/usr/share/dict/words");
     System.out.println(
-        file.map(
-            new Function<String, Object>() {
-              @Override public Object call(String s) throws Exception {
-                return s.substring(0, Math.min(s.length(), 1));
-              }
-            }).distinct().count());
+        file.map(s -> s.substring(0, Math.min(s.length(), 1)))
+            .distinct().count());
     file.cache();
     String s =
-        file.groupBy(
-            new Function<String, String>() {
-              @Override public String call(String s) throws Exception {
-                return s.substring(0, Math.min(s.length(), 1));
-              }
-            }
+        file.groupBy((Function<String, String>) s1 -> s1.substring(0, Math.min(s1.length(), 1))
             //CHECKSTYLE: IGNORE 1
-        ).map(
-            new Function<Tuple2<String, Iterable<String>>, Object>() {
-              @Override public Object call(Tuple2<String, Iterable<String>> pair) {
-                return pair._1() + ":" + Iterables.size(pair._2());
-              }
-            }).collect().toString();
+        ).map((Function<Tuple2<String, Iterable<String>>, Object>) pair ->
+            pair._1() + ":" + Iterables.size(pair._2())).collect().toString();
     System.out.print(s);
 
     final JavaRDD<Integer> rdd = sc.parallelize(
@@ -433,23 +419,15 @@ public abstract class SparkRules {
           }
         });
     System.out.println(
-        rdd.groupBy(
-            new Function<Integer, Integer>() {
-              public Integer call(Integer integer) {
-                return integer % 2;
-              }
-            }).collect().toString());
+        rdd.groupBy((Function<Integer, Integer>) integer -> integer % 2).collect().toString());
     System.out.println(
-        file.flatMap(
-            new FlatMapFunction<String, Pair<String, Integer>>() {
-              public Iterator<Pair<String, Integer>> call(String x) {
-                if (!x.startsWith("a")) {
-                  return Collections.emptyIterator();
-                }
-                return Collections.singletonList(
-                    Pair.of(x.toUpperCase(Locale.ROOT), x.length())).iterator();
-              }
-            })
+        file.flatMap((FlatMapFunction<String, Pair<String, Integer>>) x -> {
+          if (!x.startsWith("a")) {
+            return Collections.emptyIterator();
+          }
+          return Collections.singletonList(
+              Pair.of(x.toUpperCase(Locale.ROOT), x.length())).iterator();
+        })
             .take(5)
             .toString());
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/splunk/src/test/java/org/apache/calcite/test/SplunkAdapterTest.java
----------------------------------------------------------------------
diff --git a/splunk/src/test/java/org/apache/calcite/test/SplunkAdapterTest.java b/splunk/src/test/java/org/apache/calcite/test/SplunkAdapterTest.java
index bf30881..99d4b46 100644
--- a/splunk/src/test/java/org/apache/calcite/test/SplunkAdapterTest.java
+++ b/splunk/src/test/java/org/apache/calcite/test/SplunkAdapterTest.java
@@ -18,7 +18,6 @@ package org.apache.calcite.test;
 
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableSet;
 
 import org.junit.Ignore;
@@ -33,6 +32,7 @@ import java.util.Collection;
 import java.util.HashSet;
 import java.util.Properties;
 import java.util.Set;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
@@ -192,21 +192,18 @@ public class SplunkAdapterTest {
    * Reads from a table.
    */
   @Test public void testSelect() throws SQLException {
-    checkSql(
-        "select \"source\", \"sourcetype\"\n"
-            + "from \"splunk\".\"splunk\"",
-        new Function<ResultSet, Void>() {
-          public Void apply(ResultSet a0) {
-            try {
-              if (!(a0.next() && a0.next() && a0.next())) {
-                throw new AssertionError("expected at least 3 rows");
-              }
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        });
+    final String sql = "select \"source\", \"sourcetype\"\n"
+        + "from \"splunk\".\"splunk\"";
+    checkSql(sql, resultSet -> {
+      try {
+        if (!(resultSet.next() && resultSet.next() && resultSet.next())) {
+          throw new AssertionError("expected at least 3 rows");
+        }
+        return null;
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+    });
   }
 
   @Test public void testSelectDistinct() throws SQLException {
@@ -220,16 +217,14 @@ public class SplunkAdapterTest {
 
   private static Function<ResultSet, Void> expect(final String... lines) {
     final Collection<String> expected = ImmutableSet.copyOf(lines);
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet a0) {
-        try {
-          Collection<String> actual =
-              CalciteAssert.toStringList(a0, new HashSet<String>());
-          assertThat(actual, equalTo(expected));
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    return a0 -> {
+      try {
+        Collection<String> actual =
+            CalciteAssert.toStringList(a0, new HashSet<>());
+        assertThat(actual, equalTo(expected));
+        return null;
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
@@ -239,19 +234,16 @@ public class SplunkAdapterTest {
   @Test public void testSelectNonBuiltInColumn() throws SQLException {
     checkSql(
         "select \"status\"\n"
-        + "from \"splunk\".\"splunk\"",
-        new Function<ResultSet, Void>() {
-          public Void apply(ResultSet a0) {
-            final Set<String> actual = new HashSet<>();
-            try {
-              while (a0.next()) {
-                actual.add(a0.getString(1));
-              }
-              assertThat(actual.contains("404"), is(true));
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
+        + "from \"splunk\".\"splunk\"", a0 -> {
+          final Set<String> actual = new HashSet<>();
+          try {
+            while (a0.next()) {
+              actual.add(a0.getString(1));
             }
+            assertThat(actual.contains("404"), is(true));
+            return null;
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
           }
         });
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/src/main/config/forbidden-apis/signatures.txt
----------------------------------------------------------------------
diff --git a/src/main/config/forbidden-apis/signatures.txt b/src/main/config/forbidden-apis/signatures.txt
index 9c08b23..a415c28 100644
--- a/src/main/config/forbidden-apis/signatures.txt
+++ b/src/main/config/forbidden-apis/signatures.txt
@@ -51,4 +51,39 @@ java.lang.Runtime#exec(java.lang.String[], java.lang.String[], java.io.File)
 @defaultMessage For an enum, use == rather than equals
 java.lang.Enum#equals(java.lang.Object)
 
+# Preconditions.checkArgument,
+# Preconditions.checkPositionIndex, and
+# Preconditions.checkState are still OK
+@defaultMessage Use Objects.requireNonNull
+com.google.common.base.Preconditions#checkNotNull(java.lang.Object)
+com.google.common.base.Preconditions#checkNotNull(java.lang.Object, java.lang.Object)
+
+@defaultMessage Use java.util.Objects.equals
+com.google.common.base.Objects#equal(java.lang.Object, java.lang.Object)
+
+@defaultMessage Use java.util.Objects
+com.google.common.base.Objects
+
+@defaultMessage Use java.lang.String.join
+com.google.common.base.Joiner
+
+# Remove Guava calls to construct empty collections;
+# Sets.identityHashSet(),
+# Sets.newHashSet(Iterable) are still OK
+
+@defaultMessage Use "new ArrayList<>()"
+com.google.common.collect.Lists#newArrayList()
+
+@defaultMessage Use "new HashMap<>()"
+com.google.common.collect.Maps#newHashMap()
+
+@defaultMessage Use "new IdentityHashMap<>()"
+com.google.common.collect.Maps#newIdentityHashMap()
+
+@defaultMessage Use "new TreeMap<>()"
+com.google.common.collect.Maps#newTreeMap()
+
+@defaultMessage Use "new HashSet<>()"
+com.google.common.collect.Sets#newHashSet()
+
 # End signatures.txt


[30/30] calcite git commit: [CALCITE-2299] TIMESTAMPADD(SQL_TSI_FRAC_SECOND) should be nanoseconds (Sergey Nuyanzin)

Posted by jh...@apache.org.
[CALCITE-2299] TIMESTAMPADD(SQL_TSI_FRAC_SECOND) should be nanoseconds (Sergey Nuyanzin)

1) Add NANOSECONDS time unit;
2) Fix SQL_TSI_FRAC_SECOND which should be interpreted as nanoseconds;
3) Add tests.

Close apache/calcite#731


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/3fa29455
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/3fa29455
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/3fa29455

Branch: refs/heads/master
Commit: 3fa29455664bec0056c436491b369e0cd72242ea
Parents: df774b9
Author: snuyanzin <sn...@gmail.com>
Authored: Mon Jul 2 11:27:28 2018 +0300
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:46:20 2018 -0700

----------------------------------------------------------------------
 core/src/main/codegen/templates/Parser.jj       |  5 ++-
 .../calcite/sql/SqlIntervalQualifier.java       |  1 +
 .../sql/fun/SqlTimestampAddFunction.java        |  4 +--
 .../sql/fun/SqlTimestampDiffFunction.java       | 28 ++++++++++++---
 .../sql2rel/StandardConvertletTable.java        | 38 +++++++++++++-------
 .../calcite/sql/parser/SqlParserTest.java       |  4 +--
 .../calcite/sql/test/SqlOperatorBaseTest.java   | 18 +++++++++-
 site/_docs/reference.md                         |  1 +
 8 files changed, 76 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/main/codegen/templates/Parser.jj
----------------------------------------------------------------------
diff --git a/core/src/main/codegen/templates/Parser.jj b/core/src/main/codegen/templates/Parser.jj
index a89352f..be05d9c 100644
--- a/core/src/main/codegen/templates/Parser.jj
+++ b/core/src/main/codegen/templates/Parser.jj
@@ -4107,7 +4107,8 @@ TimeUnit TimestampInterval() :
 {
     <FRAC_SECOND> { return TimeUnit.MICROSECOND; }
 |   <MICROSECOND> { return TimeUnit.MICROSECOND; }
-|   <SQL_TSI_FRAC_SECOND> { return TimeUnit.MICROSECOND; }
+|   <NANOSECOND> { return TimeUnit.NANOSECOND; }
+|   <SQL_TSI_FRAC_SECOND> { return TimeUnit.NANOSECOND; }
 |   <SQL_TSI_MICROSECOND> { return TimeUnit.MICROSECOND; }
 |   <SECOND> { return TimeUnit.SECOND; }
 |   <SQL_TSI_SECOND> { return TimeUnit.SECOND; }
@@ -5774,6 +5775,7 @@ SqlPostfixOperator PostfixRowOperator() :
 |   < MUMPS: "MUMPS" >
 |   < NAME: "NAME" >
 |   < NAMES: "NAMES" >
+|   < NANOSECOND: "NANOSECOND" >
 |   < NATIONAL: "NATIONAL" >
 |   < NATURAL: "NATURAL" >
 |   < NCHAR: "NCHAR" >
@@ -6261,6 +6263,7 @@ String CommonNonReservedKeyWord() :
     |   <MUMPS>
     |   <NAME>
     |   <NAMES>
+    |   <NANOSECOND>
     |   <NESTING>
     |   <NORMALIZED>
     |   <NULLABLE>

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java b/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
index a25d93d..d5d9c74 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
@@ -166,6 +166,7 @@ public class SqlIntervalQualifier extends SqlNode {
     case MILLISECOND:
     case EPOCH:
     case MICROSECOND:
+    case NANOSECOND:
       return SqlTypeName.INTERVAL_SECOND;
     default:
       throw new AssertionError(timeUnitRange);

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
index a9bf004..bc459d0 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
@@ -39,8 +39,8 @@ import org.apache.calcite.sql.type.SqlTypeName;
  * </blockquote>
  *
  * <p>The interval time unit can one of the following literals:<ul>
- * <li>MICROSECOND (and synonyms SQL_TSI_MICROSECOND, FRAC_SECOND,
- *     SQL_TSI_FRAC_SECOND)
+ * <li>NANOSECOND (and synonym SQL_TSI_FRAC_SECOND)
+ * <li>MICROSECOND (and synonyms SQL_TSI_MICROSECOND, FRAC_SECOND)
  * <li>SECOND (and synonym SQL_TSI_SECOND)
  * <li>MINUTE (and synonym  SQL_TSI_MINUTE)
  * <li>HOUR (and synonym  SQL_TSI_HOUR)

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampDiffFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampDiffFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampDiffFunction.java
index 5ca25b3..d4aefa0 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampDiffFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampDiffFunction.java
@@ -16,12 +16,17 @@
  */
 package org.apache.calcite.sql.fun;
 
+import org.apache.calcite.avatica.util.TimeUnit;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.sql.SqlFunction;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.SqlOperatorBinding;
 import org.apache.calcite.sql.type.OperandTypes;
-import org.apache.calcite.sql.type.ReturnTypes;
+import org.apache.calcite.sql.type.SqlReturnTypeInference;
 import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
 
 /**
  * The <code>TIMESTAMPDIFF</code> function, which calculates the difference
@@ -35,8 +40,8 @@ import org.apache.calcite.sql.type.SqlTypeFamily;
  * </blockquote>
  *
  * <p>The interval time unit can one of the following literals:<ul>
- * <li>MICROSECOND (and synonyms SQL_TSI_MICROSECOND, FRAC_SECOND,
- *     SQL_TSI_FRAC_SECOND)
+ * <li>NANOSECOND (and synonym SQL_TSI_FRAC_SECOND)
+ * <li>MICROSECOND (and synonyms SQL_TSI_MICROSECOND, FRAC_SECOND)
  * <li>SECOND (and synonym SQL_TSI_SECOND)
  * <li>MINUTE (and synonym  SQL_TSI_MINUTE)
  * <li>HOUR (and synonym  SQL_TSI_HOUR)
@@ -52,9 +57,24 @@ import org.apache.calcite.sql.type.SqlTypeFamily;
  */
 class SqlTimestampDiffFunction extends SqlFunction {
   /** Creates a SqlTimestampDiffFunction. */
+  private static final SqlReturnTypeInference RETURN_TYPE_INFERENCE =
+      new SqlReturnTypeInference() {
+        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
+          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+          SqlTypeName sqlTypeName =
+              opBinding.getOperandLiteralValue(0, TimeUnit.class) == TimeUnit.NANOSECOND
+                  ? SqlTypeName.BIGINT
+                  : SqlTypeName.INTEGER;
+          return typeFactory.createTypeWithNullability(
+              typeFactory.createSqlType(sqlTypeName),
+              opBinding.getOperandType(1).isNullable()
+              || opBinding.getOperandType(2).isNullable());
+        }
+      };
+
   SqlTimestampDiffFunction() {
     super("TIMESTAMPDIFF", SqlKind.TIMESTAMP_DIFF,
-        ReturnTypes.INTEGER_NULLABLE, null,
+        RETURN_TYPE_INFERENCE, null,
         OperandTypes.family(SqlTypeFamily.ANY, SqlTypeFamily.DATETIME,
             SqlTypeFamily.DATETIME),
         SqlFunctionCategory.TIMEDATE);

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java b/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
index 5714806..e9b7cf6 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
@@ -60,7 +60,6 @@ import org.apache.calcite.sql.fun.SqlOverlapsOperator;
 import org.apache.calcite.sql.fun.SqlRowOperator;
 import org.apache.calcite.sql.fun.SqlSequenceValueOperator;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
-import org.apache.calcite.sql.fun.SqlTimestampAddFunction;
 import org.apache.calcite.sql.fun.SqlTrimFunction;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.sql.type.SqlOperandTypeChecker;
@@ -1286,18 +1285,27 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
       final RexBuilder rexBuilder = cx.getRexBuilder();
       final SqlLiteral unitLiteral = call.operand(0);
       final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
-      final RexNode operand1 = cx.convertExpression(call.operand(1));
-      final RexNode operand2 = cx.convertExpression(call.operand(2));
-      final RelDataType type =
-          SqlTimestampAddFunction.deduceType(cx.getTypeFactory(), unit,
-              operand1.getType(), operand2.getType());
-      final RexNode operand2b = rexBuilder.makeCast(type, operand2, true);
+      RexNode interval2Add;
+      SqlIntervalQualifier qualifier =
+          new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
+      RexNode op1 = cx.convertExpression(call.operand(1));
+      switch (unit) {
+      case MICROSECOND:
+      case NANOSECOND:
+        interval2Add =
+            divide(rexBuilder,
+                multiply(rexBuilder,
+                    rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
+                BigDecimal.ONE.divide(unit.multiplier,
+                    RoundingMode.UNNECESSARY));
+        break;
+      default:
+        interval2Add = multiply(rexBuilder,
+            rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
+      }
+
       return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
-          operand2b,
-          multiply(rexBuilder,
-              rexBuilder.makeIntervalLiteral(unit.multiplier,
-                  new SqlIntervalQualifier(unit, null,
-                      unitLiteral.getParserPosition())), operand1));
+          cx.convertExpression(call.operand(2)), interval2Add);
     }
   }
 
@@ -1311,9 +1319,13 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
       TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
       BigDecimal multiplier = BigDecimal.ONE;
       BigDecimal divider = BigDecimal.ONE;
+      SqlTypeName sqlTypeName = unit == TimeUnit.NANOSECOND
+          ? SqlTypeName.BIGINT
+          : SqlTypeName.INTEGER;
       switch (unit) {
       case MICROSECOND:
       case MILLISECOND:
+      case NANOSECOND:
       case WEEK:
         multiplier = BigDecimal.valueOf(DateTimeUtils.MILLIS_PER_SECOND);
         divider = unit.multiplier;
@@ -1337,7 +1349,7 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
           ImmutableList.of(op2, op1));
       final RelDataType intType =
           cx.getTypeFactory().createTypeWithNullability(
-              cx.getTypeFactory().createSqlType(SqlTypeName.INTEGER),
+              cx.getTypeFactory().createSqlType(sqlTypeName),
               SqlTypeUtil.containsNullable(rexCall.getType()));
       RexNode e = rexBuilder.makeCast(intType, rexCall);
       return rexBuilder.multiplyDivide(e, multiplier, divider);

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java b/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
index 822c136..c3459f0 100644
--- a/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
@@ -6915,8 +6915,8 @@ public class SqlParserTest {
   @Test public void testTimestampAddAndDiff() {
     Map<String, List<String>> tsi = ImmutableMap.<String, List<String>>builder()
         .put("MICROSECOND",
-            Arrays.asList("FRAC_SECOND", "MICROSECOND",
-                "SQL_TSI_FRAC_SECOND", "SQL_TSI_MICROSECOND"))
+            Arrays.asList("FRAC_SECOND", "MICROSECOND", "SQL_TSI_MICROSECOND"))
+        .put("NANOSECOND", Arrays.asList("NANOSECOND", "SQL_TSI_FRAC_SECOND"))
         .put("SECOND", Arrays.asList("SECOND", "SQL_TSI_SECOND"))
         .put("MINUTE", Arrays.asList("MINUTE", "SQL_TSI_MINUTE"))
         .put("HOUR", Arrays.asList("HOUR", "SQL_TSI_HOUR"))

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java b/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
index e8b163a..f2681f3 100644
--- a/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
@@ -6486,10 +6486,22 @@ public abstract class SqlOperatorBaseTest {
   @Test public void testTimestampAdd() {
     tester.setFor(SqlStdOperatorTable.TIMESTAMP_ADD);
     tester.checkScalar(
+        "timestampadd(MICROSECOND, 2000000, timestamp '2016-02-24 12:42:25')",
+        "2016-02-24 12:42:27",
+        "TIMESTAMP(3) NOT NULL");
+    tester.checkScalar(
         "timestampadd(SQL_TSI_SECOND, 2, timestamp '2016-02-24 12:42:25')",
         "2016-02-24 12:42:27",
         "TIMESTAMP(0) NOT NULL");
     tester.checkScalar(
+        "timestampadd(NANOSECOND, 3000000000, timestamp '2016-02-24 12:42:25')",
+        "2016-02-24 12:42:28",
+        "TIMESTAMP(0) NOT NULL");
+    tester.checkScalar(
+        "timestampadd(SQL_TSI_FRAC_SECOND, 2000000000, timestamp '2016-02-24 12:42:25')",
+        "2016-02-24 12:42:27",
+        "TIMESTAMP(0) NOT NULL");
+    tester.checkScalar(
         "timestampadd(MINUTE, 2, timestamp '2016-02-24 12:42:25')",
         "2016-02-24 12:44:25",
         "TIMESTAMP(0) NOT NULL");
@@ -6565,7 +6577,11 @@ public abstract class SqlOperatorBaseTest {
     tester.checkScalar("timestampdiff(SQL_TSI_FRAC_SECOND, "
         + "timestamp '2016-02-24 12:42:25', "
         + "timestamp '2016-02-24 12:42:20')",
-        "-5000000", "INTEGER NOT NULL");
+        "-5000000000", "BIGINT NOT NULL");
+    tester.checkScalar("timestampdiff(NANOSECOND, "
+        + "timestamp '2016-02-24 12:42:25', "
+        + "timestamp '2016-02-24 12:42:20')",
+        "-5000000000", "BIGINT NOT NULL");
     tester.checkScalar("timestampdiff(YEAR, "
         + "timestamp '2014-02-24 12:42:25', "
         + "timestamp '2016-02-24 12:42:25')",

http://git-wip-us.apache.org/repos/asf/calcite/blob/3fa29455/site/_docs/reference.md
----------------------------------------------------------------------
diff --git a/site/_docs/reference.md b/site/_docs/reference.md
index 3d1433f..b8bde09 100644
--- a/site/_docs/reference.md
+++ b/site/_docs/reference.md
@@ -614,6 +614,7 @@ MORE,
 MUMPS,
 NAME,
 NAMES,
+NANOSECOND,
 **NATIONAL**,
 **NATURAL**,
 **NCHAR**,


[04/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstantExpression.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstantExpression.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstantExpression.java
index 3437a42..129ecaf 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstantExpression.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstantExpression.java
@@ -16,9 +16,6 @@
  */
 package org.apache.calcite.linq4j.tree;
 
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
-
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Type;
@@ -28,6 +25,7 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.stream.Collectors;
 
 /**
  * Represents an expression that has a constant value.
@@ -154,14 +152,14 @@ public class ConstantExpression extends Expression {
         }
         return writer.append(")");
       } catch (ArithmeticException e) {
-        return writer.append("new java.math.BigDecimal(\"").append(
-            bigDecimal.toString()).append("\")");
+        return writer.append("new java.math.BigDecimal(\"")
+            .append(bigDecimal.toString()).append("\")");
       }
     }
     if (value instanceof BigInteger) {
       BigInteger bigInteger = (BigInteger) value;
-      return writer.append("new java.math.BigInteger(\"").append(
-          bigInteger.toString()).append("\")");
+      return writer.append("new java.math.BigInteger(\"")
+          .append(bigInteger.toString()).append("\")");
     }
     if (value instanceof Class) {
       Class clazz = (Class) value;
@@ -191,16 +189,15 @@ public class ConstantExpression extends Expression {
     if (constructor != null) {
       writer.append("new ").append(value.getClass());
       list(writer,
-          Lists.transform(Arrays.asList(value.getClass().getFields()),
-              new Function<Field, Object>() {
-                public Object apply(Field field) {
-                  try {
-                    return field.get(value);
-                  } catch (IllegalAccessException e) {
-                    throw new RuntimeException(e);
-                  }
+          Arrays.stream(value.getClass().getFields())
+              .map(field -> {
+                try {
+                  return field.get(value);
+                } catch (IllegalAccessException e) {
+                  throw new RuntimeException(e);
                 }
-              }),
+              })
+              .collect(Collectors.toList()),
           "(\n", ",\n", ")");
       return writer;
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstructorDeclaration.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstructorDeclaration.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstructorDeclaration.java
index 1aa28b4..a4775be 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstructorDeclaration.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ConstructorDeclaration.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.linq4j.tree;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.lang.reflect.Modifier;
@@ -68,16 +67,13 @@ public class ConstructorDeclaration extends MemberDeclaration {
     writer
         .append(resultType)
         .list("(", ", ", ")",
-            Lists.transform(parameters,
-                new Function<ParameterExpression, String>() {
-                  public String apply(ParameterExpression parameter) {
-                    final String modifiers =
-                        Modifier.toString(parameter.modifier);
-                    return modifiers + (modifiers.isEmpty() ? "" : " ")
-                        + Types.className(parameter.getType()) + " "
-                        + parameter.name;
-                  }
-                }))
+            Lists.transform(parameters, parameter -> {
+              final String modifiers1 =
+                  Modifier.toString(parameter.modifier);
+              return modifiers1 + (modifiers1.isEmpty() ? "" : " ")
+                  + Types.className(parameter.getType()) + " "
+                  + parameter.name;
+            }))
         .append(' ').append(body);
     writer.newlineAndIndent();
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/DeterministicCodeOptimizer.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/DeterministicCodeOptimizer.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/DeterministicCodeOptimizer.java
index 6407383..38f2057 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/DeterministicCodeOptimizer.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/DeterministicCodeOptimizer.java
@@ -69,7 +69,7 @@ public class DeterministicCodeOptimizer extends ClassDeclarationFinder {
       Pattern.compile(Pattern.quote(FIELD_PREFIX));
 
   private static final Set<Class> DETERMINISTIC_CLASSES =
-      ImmutableSet.<Class>of(Byte.class, Boolean.class, Short.class,
+      ImmutableSet.of(Byte.class, Boolean.class, Short.class,
           Integer.class, Long.class, BigInteger.class, BigDecimal.class,
           String.class, Math.class);
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java
index 5d7f83d..bf6ef79 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java
@@ -24,6 +24,8 @@ import org.apache.calcite.linq4j.function.Function2;
 import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.linq4j.function.Predicate2;
 
+import com.google.common.collect.ImmutableList;
+
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Member;
@@ -524,7 +526,7 @@ public abstract class Expressions {
    */
   public static ConditionalExpression condition(Expression test,
       Expression ifTrue, Expression ifFalse, Type type) {
-    return new ConditionalExpression(Arrays.<Node>asList(test, ifFalse, ifTrue),
+    return new ConditionalExpression(Arrays.asList(test, ifFalse, ifTrue),
         type);
   }
 
@@ -962,7 +964,7 @@ public abstract class Expressions {
    * block with an if statement.
    */
   public static ConditionalStatement ifThen(Expression test, Node ifTrue) {
-    return new ConditionalStatement(Arrays.<Node>asList(test, ifTrue));
+    return new ConditionalStatement(Arrays.asList(test, ifTrue));
   }
 
   /**
@@ -971,7 +973,7 @@ public abstract class Expressions {
    */
   public static ConditionalStatement ifThenElse(Expression test, Node ifTrue,
       Node ifFalse) {
-    return new ConditionalStatement(Arrays.<Node>asList(test, ifTrue, ifFalse));
+    return new ConditionalStatement(Arrays.asList(test, ifTrue, ifFalse));
   }
 
   /**
@@ -1914,8 +1916,7 @@ public abstract class Expressions {
    * constructor that takes no arguments.
    */
   public static NewExpression new_(Constructor constructor) {
-    return new_(
-        constructor.getDeclaringClass(), Collections.<Expression>emptyList());
+    return new_(constructor.getDeclaringClass(), ImmutableList.of());
   }
 
   /**
@@ -1923,7 +1924,7 @@ public abstract class Expressions {
    * parameterless constructor of the specified type.
    */
   public static NewExpression new_(Type type) {
-    return new_(type, Collections.<Expression>emptyList());
+    return new_(type, ImmutableList.of());
   }
 
   /**
@@ -2837,8 +2838,7 @@ public abstract class Expressions {
    * finally block and no catch statements.
    */
   public static TryStatement tryFinally(Statement body, Statement finally_) {
-    return new TryStatement(body, Collections.<CatchBlock>emptyList(),
-        finally_);
+    return new TryStatement(body, ImmutableList.of(), finally_);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/FunctionExpression.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/FunctionExpression.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/FunctionExpression.java
index 3bbe26a..a5f04cb 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/FunctionExpression.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/FunctionExpression.java
@@ -19,13 +19,14 @@ package org.apache.calcite.linq4j.tree;
 import org.apache.calcite.linq4j.function.Function;
 import org.apache.calcite.linq4j.function.Functions;
 
-import java.lang.reflect.InvocationHandler;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.Type;
 import java.lang.reflect.TypeVariable;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
 
@@ -59,8 +60,7 @@ public final class FunctionExpression<F extends Function<?>>
   }
 
   public FunctionExpression(F function) {
-    this((Class) function.getClass(), function, null,
-        Collections.<ParameterExpression>emptyList());
+    this((Class) function.getClass(), function, null, ImmutableList.of());
   }
 
   public FunctionExpression(Class<F> type, BlockStatement body,
@@ -79,14 +79,12 @@ public final class FunctionExpression<F extends Function<?>>
   }
 
   public Invokable compile() {
-    return new Invokable() {
-      public Object dynamicInvoke(Object... args) {
-        final Evaluator evaluator = new Evaluator();
-        for (int i = 0; i < args.length; i++) {
-          evaluator.push(parameterList.get(i), args[i]);
-        }
-        return evaluator.evaluate(body);
+    return args -> {
+      final Evaluator evaluator = new Evaluator();
+      for (int i = 0; i < args.length; i++) {
+        evaluator.push(parameterList.get(i), args[i]);
       }
+      return evaluator.evaluate(body);
     };
   }
 
@@ -99,13 +97,7 @@ public final class FunctionExpression<F extends Function<?>>
 
       //noinspection unchecked
       dynamicFunction = (F) Proxy.newProxyInstance(getClass().getClassLoader(),
-          new Class[]{Types.toClass(type)},
-          new InvocationHandler() {
-            public Object invoke(Object proxy, Method method, Object[] args)
-                throws Throwable {
-              return x.dynamicInvoke(args);
-            }
-          });
+          new Class[]{Types.toClass(type)}, (proxy, method, args) -> x.dynamicInvoke(args));
     }
     return dynamicFunction;
   }
@@ -223,9 +215,13 @@ public final class FunctionExpression<F extends Function<?>>
 
   private Method getAbstractMethod() {
     if (type instanceof Class
-        && ((Class) type).isInterface()
-        && ((Class) type).getDeclaredMethods().length == 1) {
-      return ((Class) type).getDeclaredMethods()[0];
+        && ((Class) type).isInterface()) {
+      final List<Method> declaredMethods =
+          Lists.newArrayList(((Class) type).getDeclaredMethods());
+      declaredMethods.removeIf(m -> (m.getModifiers() & 0x00001000) != 0);
+      if (declaredMethods.size() == 1) {
+        return declaredMethods.get(0);
+      }
     }
     return null;
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/MethodDeclaration.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/MethodDeclaration.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/MethodDeclaration.java
index 800f387..6449594 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/MethodDeclaration.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/MethodDeclaration.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.linq4j.tree;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.lang.reflect.Modifier;
@@ -69,12 +68,7 @@ public class MethodDeclaration extends MemberDeclaration {
         .append(' ')
         .append(name)
         .list("(", ", ", ")",
-            Lists.transform(parameters,
-                new Function<ParameterExpression, String>() {
-                  public String apply(ParameterExpression a0) {
-                    return a0.declString();
-                  }
-                }))
+            Lists.transform(parameters, ParameterExpression::declString))
         .append(' ')
         .append(body);
     writer.newlineAndIndent();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/TryStatement.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/TryStatement.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/TryStatement.java
index 9313011..6b6c072 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/TryStatement.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/TryStatement.java
@@ -16,8 +16,6 @@
  */
 package org.apache.calcite.linq4j.tree;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
 import java.util.Objects;
 
@@ -32,8 +30,8 @@ public class TryStatement extends Statement {
   public TryStatement(Statement body, List<CatchBlock> catchBlocks,
       Statement fynally) {
     super(ExpressionType.Try, body.getType());
-    this.body = Preconditions.checkNotNull(body);
-    this.catchBlocks = Preconditions.checkNotNull(catchBlocks);
+    this.body = Objects.requireNonNull(body);
+    this.catchBlocks = Objects.requireNonNull(catchBlocks);
     this.fynally = fynally;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Types.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Types.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Types.java
index b4f233a..442b927 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Types.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Types.java
@@ -153,7 +153,7 @@ public abstract class Types {
     for (Type type : types) {
       classes.add(toClass(type));
     }
-    return classes.toArray(new Class[classes.size()]);
+    return classes.toArray(new Class[0]);
   }
 
   static Class[] toClassArray(Iterable<? extends Expression> arguments) {
@@ -161,7 +161,7 @@ public abstract class Types {
     for (Expression argument : arguments) {
       classes.add(toClass(argument.getType()));
     }
-    return classes.toArray(new Class[classes.size()]);
+    return classes.toArray(new Class[0]);
   }
 
   /**
@@ -562,7 +562,7 @@ public abstract class Types {
     }
 
     public Type[] getActualTypeArguments() {
-      return typeArguments.toArray(new Type[typeArguments.size()]);
+      return typeArguments.toArray(new Type[0]);
     }
 
     public Type getRawType() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/test/java/com/example/Linq4jExample.java
----------------------------------------------------------------------
diff --git a/linq4j/src/test/java/com/example/Linq4jExample.java b/linq4j/src/test/java/com/example/Linq4jExample.java
index 80413bf..994b836 100644
--- a/linq4j/src/test/java/com/example/Linq4jExample.java
+++ b/linq4j/src/test/java/com/example/Linq4jExample.java
@@ -19,7 +19,6 @@ package com.example;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.function.Function0;
 import org.apache.calcite.linq4j.function.Function1;
-import org.apache.calcite.linq4j.function.Function2;
 import org.apache.calcite.linq4j.function.Functions;
 
 /**
@@ -53,32 +52,16 @@ public class Linq4jExample {
   };
 
   public static final Function1<Employee, Integer> EMP_DEPTNO_SELECTOR =
-      new Function1<Employee, Integer>() {
-        public Integer apply(Employee employee) {
-          return employee.deptno;
-        }
-      };
+      employee -> employee.deptno;
 
   public static void main(String[] args) {
     String s = Linq4j.asEnumerable(EMPS)
         .groupBy(
             EMP_DEPTNO_SELECTOR,
-            new Function0<String>() {
-              public String apply() {
-                return null;
-              }
-            },
-            new Function2<String, Employee, String>() {
-              public String apply(String v1, Employee e0) {
-                return v1 == null ? e0.name : (v1 + "+" + e0.name);
-              }
-            },
-            new Function2<Integer, String, String>() {
-              public String apply(Integer v1, String v2) {
-                return v1 + ": " + v2;
-              }
-            })
-        .orderBy(Functions.<String>identitySelector())
+            (Function0<String>) () -> null,
+            (v1, e0) -> v1 == null ? e0.name : (v1 + "+" + e0.name),
+            (v1, v2) -> v1 + ": " + v2)
+        .orderBy(Functions.identitySelector())
         .toList()
         .toString();
     assert s.equals("[10: Fred+Eric+Janet, 30: Bill]");

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/test/java/org/apache/calcite/linq4j/function/FunctionTest.java
----------------------------------------------------------------------
diff --git a/linq4j/src/test/java/org/apache/calcite/linq4j/function/FunctionTest.java b/linq4j/src/test/java/org/apache/calcite/linq4j/function/FunctionTest.java
index 998aed3..9eac08c 100644
--- a/linq4j/src/test/java/org/apache/calcite/linq4j/function/FunctionTest.java
+++ b/linq4j/src/test/java/org/apache/calcite/linq4j/function/FunctionTest.java
@@ -32,32 +32,17 @@ public class FunctionTest {
     final List<String> abc = Arrays.asList("A", "B", "C", "D");
     // a miss, then a hit
     Assert.assertEquals("[A, C, D]",
-        Functions.filter(abc,
-            new Predicate1<String>() {
-              public boolean apply(String v1) {
-                return !v1.equals("B");
-              }
-            }).toString());
+        Functions.filter(abc, v1 -> !v1.equals("B")).toString());
     // a hit, then all misses
     Assert.assertEquals("[A]",
-        Functions.filter(abc,
-            new Predicate1<String>() {
-              public boolean apply(String v1) {
-                return v1.equals("A");
-              }
-            }).toString());
+        Functions.filter(abc, v1 -> v1.equals("A")).toString());
     // two hits, then a miss
     Assert.assertEquals("[A, B, D]",
-        Functions.filter(abc,
-            new Predicate1<String>() {
-              public boolean apply(String v1) {
-                return !v1.equals("C");
-              }
-            }).toString());
+        Functions.filter(abc, v1 -> !v1.equals("C")).toString());
     Assert.assertSame(Collections.emptyList(),
-        Functions.filter(abc, Functions.<String>falsePredicate1()));
+        Functions.filter(abc, Functions.falsePredicate1()));
     Assert.assertSame(abc,
-        Functions.filter(abc, Functions.<String>truePredicate1()));
+        Functions.filter(abc, Functions.truePredicate1()));
   }
 
   /** Unit test for {@link Functions#exists}. */
@@ -65,16 +50,11 @@ public class FunctionTest {
     final List<Integer> ints = Arrays.asList(1, 10, 2);
     final List<Integer> empty = Collections.emptyList();
     Assert.assertFalse(
-        Functions.exists(ints,
-            new Predicate1<Integer>() {
-              public boolean apply(Integer v1) {
-                return v1 > 20;
-              }
-            }));
+        Functions.exists(ints, v1 -> v1 > 20));
     Assert.assertFalse(
-        Functions.exists(empty, Functions.<Integer>falsePredicate1()));
+        Functions.exists(empty, Functions.falsePredicate1()));
     Assert.assertFalse(
-        Functions.exists(empty, Functions.<Integer>truePredicate1()));
+        Functions.exists(empty, Functions.truePredicate1()));
   }
 
   /** Unit test for {@link Functions#all}. */
@@ -82,30 +62,15 @@ public class FunctionTest {
     final List<Integer> ints = Arrays.asList(1, 10, 2);
     final List<Integer> empty = Collections.emptyList();
     Assert.assertFalse(
-        Functions.all(ints,
-            new Predicate1<Integer>() {
-              public boolean apply(Integer v1) {
-                return v1 > 20;
-              }
-            }));
+        Functions.all(ints, v1 -> v1 > 20));
     Assert.assertTrue(
-        Functions.all(ints,
-            new Predicate1<Integer>() {
-              public boolean apply(Integer v1) {
-                return v1 < 20;
-              }
-            }));
+        Functions.all(ints, v1 -> v1 < 20));
     Assert.assertFalse(
-        Functions.all(ints,
-            new Predicate1<Integer>() {
-              public boolean apply(Integer v1) {
-                return v1 < 10;
-              }
-            }));
+        Functions.all(ints, v1 -> v1 < 10));
     Assert.assertTrue(
-        Functions.all(empty, Functions.<Integer>falsePredicate1()));
+        Functions.all(empty, Functions.falsePredicate1()));
     Assert.assertTrue(
-        Functions.all(empty, Functions.<Integer>truePredicate1()));
+        Functions.all(empty, Functions.truePredicate1()));
   }
 
   /** Unit test for {@link Functions#generate}. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/test/java/org/apache/calcite/linq4j/test/CorrelateJoinTest.java
----------------------------------------------------------------------
diff --git a/linq4j/src/test/java/org/apache/calcite/linq4j/test/CorrelateJoinTest.java b/linq4j/src/test/java/org/apache/calcite/linq4j/test/CorrelateJoinTest.java
index 10e4663..ab69c3c 100644
--- a/linq4j/src/test/java/org/apache/calcite/linq4j/test/CorrelateJoinTest.java
+++ b/linq4j/src/test/java/org/apache/calcite/linq4j/test/CorrelateJoinTest.java
@@ -20,14 +20,13 @@ import org.apache.calcite.linq4j.CorrelateJoinType;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Enumerator;
 import org.apache.calcite.linq4j.Linq4j;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.linq4j.function.Function2;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import static org.junit.Assert.assertArrayEquals;
@@ -37,11 +36,7 @@ import static org.junit.Assert.assertArrayEquals;
  */
 public class CorrelateJoinTest {
   static final Function2<Integer, Integer, Integer[]> SELECT_BOTH =
-      new Function2<Integer, Integer, Integer[]>() {
-        public Integer[] apply(Integer v0, Integer v1) {
-          return new Integer[]{v0, v1};
-        }
-      };
+      (v0, v1) -> new Integer[]{v0, v1};
 
   @Test public void testInner() {
     testJoin(CorrelateJoinType.INNER, new Integer[][]{
@@ -82,23 +77,20 @@ public class CorrelateJoinTest {
   public void testJoin(CorrelateJoinType joinType, Integer[][] expected) {
     Enumerable<Integer[]> join =
         Linq4j.asEnumerable(ImmutableList.of(1, 2, 3, 10, 20, 30))
-            .correlateJoin(joinType,
-                new Function1<Integer, Enumerable<Integer>>() {
-                  public Enumerable<Integer> apply(Integer a0) {
-                    if (a0 == 1 || a0 == 10) {
-                      return Linq4j.emptyEnumerable();
-                    }
-                    if (a0 == 2 || a0 == 20) {
-                      return Linq4j.singletonEnumerable(a0 * 10);
-                    }
-                    if (a0 == 3 || a0 == 30) {
-                      return Linq4j.asEnumerable(
-                          ImmutableList.of(-a0 * 10, -a0 * 20));
-                    }
-                    throw new IllegalArgumentException(
-                        "Unexpected input " + a0);
-                  }
-                }, SELECT_BOTH);
+            .correlateJoin(joinType, a0 -> {
+              if (a0 == 1 || a0 == 10) {
+                return Linq4j.emptyEnumerable();
+              }
+              if (a0 == 2 || a0 == 20) {
+                return Linq4j.singletonEnumerable(a0 * 10);
+              }
+              if (a0 == 3 || a0 == 30) {
+                return Linq4j.asEnumerable(
+                    ImmutableList.of(-a0 * 10, -a0 * 20));
+              }
+              throw new IllegalArgumentException(
+                  "Unexpected input " + a0);
+            }, SELECT_BOTH);
     for (int i = 0; i < 2; i++) {
       Enumerator<Integer[]> e = join.enumerator();
       checkResults(e, expected);
@@ -107,7 +99,7 @@ public class CorrelateJoinTest {
   }
 
   private void checkResults(Enumerator<Integer[]> e, Integer[][] expected) {
-    List<Integer[]> res = Lists.newArrayList();
+    List<Integer[]> res = new ArrayList<>();
     while (e.moveNext()) {
       res.add(e.current());
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/test/java/org/apache/calcite/linq4j/test/DeterministicTest.java
----------------------------------------------------------------------
diff --git a/linq4j/src/test/java/org/apache/calcite/linq4j/test/DeterministicTest.java b/linq4j/src/test/java/org/apache/calcite/linq4j/test/DeterministicTest.java
index 9194613..7d73e85 100644
--- a/linq4j/src/test/java/org/apache/calcite/linq4j/test/DeterministicTest.java
+++ b/linq4j/src/test/java/org/apache/calcite/linq4j/test/DeterministicTest.java
@@ -23,7 +23,6 @@ import org.apache.calcite.linq4j.tree.ClassDeclarationFinder;
 import org.apache.calcite.linq4j.tree.DeterministicCodeOptimizer;
 import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
-import org.apache.calcite.linq4j.tree.ParameterExpression;
 import org.apache.calcite.linq4j.tree.Types;
 
 import org.junit.Test;
@@ -134,12 +133,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(Expressions.add(ONE, TWO))))),
         equalTo("{\n"
             + "  return new Runnable(){\n"
@@ -157,11 +156,11 @@ public class DeterministicTest {
         optimize(
             optimizeExpression(
                 Expressions.new_(Runnable.class,
-                    Collections.<Expression>emptyList(),
+                    Collections.emptyList(),
                     Expressions.methodDecl(0,
                         int.class,
                         "test",
-                        Collections.<ParameterExpression>emptyList(),
+                        Collections.emptyList(),
                         Blocks.toFunctionBlock(Expressions.add(ONE, TWO)))))),
         equalTo("{\n"
             + "  return new Runnable(){\n"
@@ -179,12 +178,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.multiply(Expressions.add(ONE, TWO),
                             Expressions.subtract(ONE, TWO)))))),
@@ -206,12 +205,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.multiply(Expressions.add(ONE, TWO),
                             THREE))))),
@@ -232,31 +231,31 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.add(
                             Expressions.add(ONE, FOUR),
                             Expressions.call(
                                 Expressions.new_(
                                     Callable.class,
-                                    Collections.<Expression>emptyList(),
+                                    Collections.emptyList(),
                                     Expressions.methodDecl(
                                         0,
                                         Object.class,
                                         "call",
                                         Collections
-                                            .<ParameterExpression>emptyList(),
+                                            .emptyList(),
                                         Blocks.toFunctionBlock(
                                             Expressions.multiply(
                                                 Expressions.add(ONE, TWO),
                                                 THREE)))),
                                 "call",
-                                Collections.<Expression>emptyList())))))),
+                                Collections.emptyList())))))),
         equalTo("{\n"
             + "  return new Runnable(){\n"
             + "      int test() {\n"
@@ -280,10 +279,10 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0, int.class, "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.new_(BigInteger.class,
                             Expressions.constant("42")))))),
@@ -306,10 +305,10 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0, int.class, "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.typeIs(ONE, Boolean.class))))),
         equalTo("{\n"
@@ -327,9 +326,9 @@ public class DeterministicTest {
     assertThat(
         optimize(
             Expressions.new_(Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(0, int.class, "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.orElse(
                             Expressions.typeIs(ONE, Boolean.class),
@@ -352,9 +351,9 @@ public class DeterministicTest {
     assertThat(
         optimize(
             Expressions.new_(Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(0, int.class, "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(
                             getMethod(Integer.class, "valueOf", int.class),
@@ -375,9 +374,9 @@ public class DeterministicTest {
     assertThat(
         optimize(
             Expressions.new_(Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(0, int.class, "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(
                             Expressions.field(null, BigInteger.class, "ONE"),
@@ -407,9 +406,9 @@ public class DeterministicTest {
     assertThat(
         optimize(
             Expressions.new_(Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(0, int.class, "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(
                             Expressions.call(null,
@@ -442,12 +441,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(null,
                             Types.lookupMethod(TestClass.class,
@@ -469,12 +468,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(null,
                             Types.lookupMethod(TestClass.class,
@@ -495,12 +494,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(null,
                             Types.lookupMethod(TestDeterministicClass.class,
@@ -522,12 +521,12 @@ public class DeterministicTest {
         optimize(
             Expressions.new_(
                 Runnable.class,
-                Collections.<Expression>emptyList(),
+                Collections.emptyList(),
                 Expressions.methodDecl(
                     0,
                     int.class,
                     "test",
-                    Collections.<ParameterExpression>emptyList(),
+                    Collections.emptyList(),
                     Blocks.toFunctionBlock(
                         Expressions.call(null,
                             Types.lookupMethod(TestDeterministicClass.class,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/test/java/org/apache/calcite/linq4j/test/ExpressionTest.java
----------------------------------------------------------------------
diff --git a/linq4j/src/test/java/org/apache/calcite/linq4j/test/ExpressionTest.java b/linq4j/src/test/java/org/apache/calcite/linq4j/test/ExpressionTest.java
index 8f1756d..f457906 100644
--- a/linq4j/src/test/java/org/apache/calcite/linq4j/test/ExpressionTest.java
+++ b/linq4j/src/test/java/org/apache/calcite/linq4j/test/ExpressionTest.java
@@ -26,7 +26,6 @@ import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.FieldDeclaration;
 import org.apache.calcite.linq4j.tree.FunctionExpression;
-import org.apache.calcite.linq4j.tree.MemberDeclaration;
 import org.apache.calcite.linq4j.tree.MethodCallExpression;
 import org.apache.calcite.linq4j.tree.NewExpression;
 import org.apache.calcite.linq4j.tree.Node;
@@ -34,6 +33,7 @@ import org.apache.calcite.linq4j.tree.ParameterExpression;
 import org.apache.calcite.linq4j.tree.Shuttle;
 import org.apache.calcite.linq4j.tree.Types;
 
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
 import org.junit.Test;
@@ -195,7 +195,7 @@ public class ExpressionTest {
             Expressions.foldOr(list1)));
 
     final List<Expression> list2 =
-        Collections.<Expression>singletonList(
+        Collections.singletonList(
             Expressions.constant(true));
     assertEquals(
         "true",
@@ -355,7 +355,7 @@ public class ExpressionTest {
             Expressions.lambda(
                 Function1.class,
                 Expressions.call(
-                    paramX, "length", Collections.<Expression>emptyList()),
+                    paramX, "length", Collections.emptyList()),
                 Arrays.asList(paramX))));
 
     // 1-dimensional array with initializer
@@ -421,7 +421,7 @@ public class ExpressionTest {
                             Object.class),
                         String.class),
                     "length",
-                    Collections.<Expression>emptyList()),
+                    Collections.emptyList()),
                 Integer.TYPE)));
 
     // resolving a static method
@@ -635,8 +635,8 @@ public class ExpressionTest {
             Expressions.statement(
                 Expressions.new_(
                     Types.of(AbstractList.class, String.class),
-                    Collections.<Expression>emptyList(),
-                    Arrays.<MemberDeclaration>asList(
+                    Collections.emptyList(),
+                    Arrays.asList(
                         Expressions.fieldDecl(
                             Modifier.PUBLIC | Modifier.FINAL,
                             Expressions.parameter(
@@ -647,12 +647,12 @@ public class ExpressionTest {
                             Modifier.PUBLIC,
                             Integer.TYPE,
                             "size",
-                            Collections.<ParameterExpression>emptyList(),
+                            Collections.emptyList(),
                             Blocks.toFunctionBlock(
                                 Expressions.call(
                                     bazParameter,
                                     "size",
-                                    Collections.<Expression>emptyList()))),
+                                    Collections.emptyList()))),
                         Expressions.methodDecl(
                             Modifier.PUBLIC,
                             String.class,
@@ -668,8 +668,7 @@ public class ExpressionTest {
                                                 indexParameter)),
                                         String.class),
                                     "toUpperCase",
-                                    Collections
-                                        .<Expression>emptyList())))))));
+                                    ImmutableList.of())))))));
     assertEquals(
         "{\n"
             + "  final java.util.List<String> baz = java.util.Arrays.asList(\"foo\", \"bar\");\n"
@@ -1049,8 +1048,8 @@ public class ExpressionTest {
     final NewExpression newExpression =
         Expressions.new_(
             Object.class,
-            Collections.<Expression>emptyList(),
-            Arrays.<MemberDeclaration>asList(
+            ImmutableList.of(),
+            Arrays.asList(
                 Expressions.fieldDecl(
                     Modifier.PUBLIC | Modifier.FINAL,
                     Expressions.parameter(String.class, "foo"),
@@ -1059,8 +1058,8 @@ public class ExpressionTest {
                     Modifier.PUBLIC | Modifier.STATIC,
                     "MyClass",
                     null,
-                    Collections.<Type>emptyList(),
-                    Arrays.<MemberDeclaration>asList(
+                    ImmutableList.of(),
+                    Arrays.asList(
                         new FieldDeclaration(
                             0,
                             Expressions.parameter(int.class, "x"),


[20/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptMaterialization.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptMaterialization.java b/core/src/main/java/org/apache/calcite/plan/RelOptMaterialization.java
index 6e1af24..e89c3f0 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptMaterialization.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptMaterialization.java
@@ -43,11 +43,11 @@ import org.apache.calcite.tools.Programs;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Records that a particular query is materialized by a particular table.
@@ -158,7 +158,7 @@ public class RelOptMaterialization {
               final RelNode project = RelOptUtil.createProject(
                   LogicalTableScan.create(cluster, leftRelOptTable),
                   Mappings.asList(mapping.inverse()));
-              final List<RexNode> conditions = Lists.newArrayList();
+              final List<RexNode> conditions = new ArrayList<>();
               if (left.condition != null) {
                 conditions.add(left.condition);
               }
@@ -182,7 +182,7 @@ public class RelOptMaterialization {
               final RelNode project = RelOptUtil.createProject(
                   LogicalTableScan.create(cluster, rightRelOptTable),
                   Mappings.asList(mapping.inverse()));
-              final List<RexNode> conditions = Lists.newArrayList();
+              final List<RexNode> conditions = new ArrayList<>();
               if (left.condition != null) {
                 conditions.add(
                     RexUtil.apply(mapping,
@@ -208,8 +208,8 @@ public class RelOptMaterialization {
         false,
         DefaultRelMetadataProvider.INSTANCE);
     return program.run(null, rel2, null,
-        ImmutableList.<RelOptMaterialization>of(),
-        ImmutableList.<RelOptLattice>of());
+        ImmutableList.of(),
+        ImmutableList.of());
   }
 
   /** A table scan and optional project mapping and filter condition. */
@@ -222,7 +222,7 @@ public class RelOptMaterialization {
         Mappings.TargetMapping mapping, TableScan scan) {
       this.condition = condition;
       this.mapping = mapping;
-      this.scan = Preconditions.checkNotNull(scan);
+      this.scan = Objects.requireNonNull(scan);
     }
 
     static ProjectFilterTable of(RelNode node) {
@@ -285,8 +285,8 @@ public class RelOptMaterialization {
               SqlExplainLevel.DIGEST_ATTRIBUTES));
     }
     final RelNode rel2 = program.run(null, rel, null,
-        ImmutableList.<RelOptMaterialization>of(),
-        ImmutableList.<RelOptLattice>of());
+        ImmutableList.of(),
+        ImmutableList.of());
     if (CalcitePrepareImpl.DEBUG) {
       System.out.println(
           RelOptUtil.dumpPlan("after", rel2, SqlExplainFormat.TEXT,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptMaterializations.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptMaterializations.java b/core/src/main/java/org/apache/calcite/plan/RelOptMaterializations.java
index 3c0362c..c4553fb 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptMaterializations.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptMaterializations.java
@@ -31,12 +31,9 @@ import org.apache.calcite.util.graph.DirectedGraph;
 import org.apache.calcite.util.graph.Graphs;
 import org.apache.calcite.util.graph.TopologicalOrderIterator;
 
-import com.google.common.base.Function;
-import com.google.common.base.Supplier;
 import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
 import java.util.ArrayList;
@@ -44,6 +41,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Supplier;
 
 /**
  * Utility methods for using
@@ -66,9 +64,7 @@ public abstract class RelOptMaterializations {
         getApplicableMaterializations(rel, materializations);
     final List<Pair<RelNode, List<RelOptMaterialization>>> applied =
         new ArrayList<>();
-    applied.add(
-        Pair.<RelNode, List<RelOptMaterialization>>of(
-            rel, ImmutableList.<RelOptMaterialization>of()));
+    applied.add(Pair.of(rel, ImmutableList.of()));
     for (RelOptMaterialization m : applicableMaterializations) {
       int count = applied.size();
       for (int i = 0; i < count; i++) {
@@ -102,16 +98,13 @@ public abstract class RelOptMaterializations {
     final Set<RelOptTable> queryTables = RelOptUtil.findTables(rel);
     // Use a lattice if the query uses at least the central (fact) table of the
     // lattice.
-    final List<Pair<RelNode, RelOptLattice>> latticeUses = Lists.newArrayList();
+    final List<Pair<RelNode, RelOptLattice>> latticeUses = new ArrayList<>();
     final Set<List<String>> queryTableNames =
-        Sets.newHashSet(Iterables.transform(queryTables, GET_QUALIFIED_NAME));
+        Sets.newHashSet(
+            Iterables.transform(queryTables, RelOptTable::getQualifiedName));
     // Remember leaf-join form of root so we convert at most once.
-    final Supplier<RelNode> leafJoinRoot = Suppliers.memoize(
-        new Supplier<RelNode>() {
-          public RelNode get() {
-            return RelOptMaterialization.toLeafJoinForm(rel);
-          }
-        });
+    final Supplier<RelNode> leafJoinRoot =
+        Suppliers.memoize(() -> RelOptMaterialization.toLeafJoinForm(rel))::get;
     for (RelOptLattice lattice : lattices) {
       if (queryTableNames.contains(lattice.rootTable().getQualifiedName())) {
         RelNode rel2 = lattice.rewrite(leafJoinRoot.get());
@@ -163,7 +156,8 @@ public abstract class RelOptMaterializations {
     final Graphs.FrozenGraph<List<String>, DefaultEdge> frozenGraph =
         Graphs.makeImmutable(usesGraph);
     final Set<RelOptTable> queryTablesUsed = RelOptUtil.findTables(rel);
-    final List<RelOptMaterialization> applicableMaterializations = Lists.newArrayList();
+    final List<RelOptMaterialization> applicableMaterializations =
+        new ArrayList<>();
     for (List<String> qname : TopologicalOrderIterator.of(usesGraph)) {
       RelOptMaterialization materialization = qnameMap.get(qname);
       if (materialization != null
@@ -174,13 +168,6 @@ public abstract class RelOptMaterializations {
     return applicableMaterializations;
   }
 
-  private static final Function<RelOptTable, List<String>> GET_QUALIFIED_NAME =
-      new Function<RelOptTable, List<String>>() {
-        public List<String> apply(RelOptTable relOptTable) {
-          return relOptTable.getQualifiedName();
-        }
-      };
-
   private static List<RelNode> substitute(
       RelNode root, RelOptMaterialization materialization) {
     // First, if the materialization is in terms of a star table, rewrite

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptPredicateList.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptPredicateList.java b/core/src/main/java/org/apache/calcite/plan/RelOptPredicateList.java
index d163905..5523cfc 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptPredicateList.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptPredicateList.java
@@ -20,10 +20,11 @@ import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexUtil;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
+import java.util.Objects;
+
 /**
  * Predicates that are known to hold in the output of a particular relational
  * expression.
@@ -67,7 +68,7 @@ public class RelOptPredicateList {
   private static final ImmutableList<RexNode> EMPTY_LIST = ImmutableList.of();
   public static final RelOptPredicateList EMPTY =
       new RelOptPredicateList(EMPTY_LIST, EMPTY_LIST, EMPTY_LIST,
-          ImmutableMap.<RexNode, RexNode>of());
+          ImmutableMap.of());
 
   /** Predicates that can be pulled up from the relational expression and its
    * inputs. */
@@ -89,12 +90,12 @@ public class RelOptPredicateList {
       ImmutableList<RexNode> leftInferredPredicates,
       ImmutableList<RexNode> rightInferredPredicates,
       ImmutableMap<RexNode, RexNode> constantMap) {
-    this.pulledUpPredicates = Preconditions.checkNotNull(pulledUpPredicates);
+    this.pulledUpPredicates = Objects.requireNonNull(pulledUpPredicates);
     this.leftInferredPredicates =
-        Preconditions.checkNotNull(leftInferredPredicates);
+        Objects.requireNonNull(leftInferredPredicates);
     this.rightInferredPredicates =
-        Preconditions.checkNotNull(rightInferredPredicates);
-    this.constantMap = Preconditions.checkNotNull(constantMap);
+        Objects.requireNonNull(rightInferredPredicates);
+    this.constantMap = Objects.requireNonNull(constantMap);
   }
 
   /** Creates a RelOptPredicateList with only pulled-up predicates, no inferred

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptRule.java b/core/src/main/java/org/apache/calcite/plan/RelOptRule.java
index c5af926..1f23bc2 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptRule.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptRule.java
@@ -22,15 +22,13 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
+import java.util.function.Predicate;
 
 /**
  * A <code>RelOptRule</code> transforms an expression into another. It has a
@@ -97,8 +95,8 @@ public abstract class RelOptRule {
    */
   public RelOptRule(RelOptRuleOperand operand,
       RelBuilderFactory relBuilderFactory, String description) {
-    this.operand = Preconditions.checkNotNull(operand);
-    this.relBuilderFactory = Preconditions.checkNotNull(relBuilderFactory);
+    this.operand = Objects.requireNonNull(operand);
+    this.relBuilderFactory = Objects.requireNonNull(relBuilderFactory);
     if (description == null) {
       description = guessDescription(getClass().getName());
     }
@@ -126,7 +124,7 @@ public abstract class RelOptRule {
   public static <R extends RelNode> RelOptRuleOperand operand(
       Class<R> clazz,
       RelOptRuleOperandChildren operandList) {
-    return new RelOptRuleOperand(clazz, null, Predicates.<R>alwaysTrue(),
+    return new RelOptRuleOperand(clazz, null, r -> true,
         operandList.policy, operandList.operands);
   }
 
@@ -145,7 +143,7 @@ public abstract class RelOptRule {
       Class<R> clazz,
       RelTrait trait,
       RelOptRuleOperandChildren operandList) {
-    return new RelOptRuleOperand(clazz, trait, Predicates.<R>alwaysTrue(),
+    return new RelOptRuleOperand(clazz, trait, r -> true,
         operandList.policy, operandList.operands);
   }
 
@@ -161,7 +159,7 @@ public abstract class RelOptRule {
    * @return Operand that matches a relational expression that has a
    *   particular trait and predicate
    */
-  public static <R extends RelNode> RelOptRuleOperand operand(
+  public static <R extends RelNode> RelOptRuleOperand operandJ(
       Class<R> clazz,
       RelTrait trait,
       Predicate<? super R> predicate,
@@ -170,6 +168,18 @@ public abstract class RelOptRule {
         operandList.operands);
   }
 
+  /** @deprecated Use {@link #operandJ} */
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static <R extends RelNode> RelOptRuleOperand operand(
+      Class<R> clazz,
+      RelTrait trait,
+      com.google.common.base.Predicate<? super R> predicate,
+      RelOptRuleOperandChildren operandList) {
+    return operandJ(clazz, trait, (Predicate<? super R>) predicate::apply,
+        operandList);
+  }
+
   /**
    * Creates an operand that matches a relational expression that has no
    * children.
@@ -182,13 +192,25 @@ public abstract class RelOptRule {
    * @param <R> Class of relational expression to match
    * @return Operand
    */
-  public static <R extends RelNode> RelOptRuleOperand operand(
+  public static <R extends RelNode> RelOptRuleOperand operandJ(
       Class<R> clazz,
       RelTrait trait,
       Predicate<? super R> predicate,
       RelOptRuleOperand first,
       RelOptRuleOperand... rest) {
-    return operand(clazz, trait, predicate, some(first, rest));
+    return operandJ(clazz, trait, predicate, some(first, rest));
+  }
+
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static <R extends RelNode> RelOptRuleOperand operand(
+      Class<R> clazz,
+      RelTrait trait,
+      com.google.common.base.Predicate<? super R> predicate,
+      RelOptRuleOperand first,
+      RelOptRuleOperand... rest) {
+    return operandJ(clazz, trait, (Predicate<? super R>) predicate::apply,
+        first, rest);
   }
 
   /**
@@ -230,6 +252,16 @@ public abstract class RelOptRule {
     return new ConverterRelOptRuleOperand(clazz, trait, predicate);
   }
 
+  /** @deprecated Use {@link #convertOperand(Class, Predicate, RelTrait)}. */
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  protected static <R extends RelNode> ConverterRelOptRuleOperand
+      convertOperand(Class<R> clazz,
+      com.google.common.base.Predicate<? super R> predicate,
+      RelTrait trait) {
+    return new ConverterRelOptRuleOperand(clazz, trait, predicate::apply);
+  }
+
   //~ Methods for creating lists of child operands ---------------------------
 
   /**
@@ -572,11 +604,7 @@ public abstract class RelOptRule {
   protected static List<RelNode> convertList(List<RelNode> rels,
       final RelTrait trait) {
     return Lists.transform(rels,
-        new Function<RelNode, RelNode>() {
-          public RelNode apply(RelNode rel) {
-            return convert(rel, rel.getTraitSet().replace(trait));
-          }
-        });
+        rel -> convert(rel, rel.getTraitSet().replace(trait)));
   }
 
   /**
@@ -619,7 +647,7 @@ public abstract class RelOptRule {
     <R extends RelNode> ConverterRelOptRuleOperand(Class<R> clazz, RelTrait in,
         Predicate<? super R> predicate) {
       super(clazz, in, predicate, RelOptRuleOperandChildPolicy.ANY,
-          ImmutableList.<RelOptRuleOperand>of());
+          ImmutableList.of());
     }
 
     public boolean matches(RelNode rel) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptRuleCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptRuleCall.java b/core/src/main/java/org/apache/calcite/plan/RelOptRuleCall.java
index d753b66..2654b54 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptRuleCall.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptRuleCall.java
@@ -231,7 +231,7 @@ public abstract class RelOptRuleCall {
    *            expression of the rule call, {@code call.rels(0)}
    */
   public final void transformTo(RelNode rel) {
-    transformTo(rel, ImmutableMap.<RelNode, RelNode>of());
+    transformTo(rel, ImmutableMap.of());
   }
 
   /** Creates a {@link org.apache.calcite.tools.RelBuilder} to be used by

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperand.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperand.java b/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperand.java
index d3c5f2f..7506010 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperand.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperand.java
@@ -18,12 +18,11 @@ package org.apache.calcite.plan;
 
 import org.apache.calcite.rel.RelNode;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
 import java.util.Objects;
+import java.util.function.Predicate;
 
 /**
  * Operand that determines whether a {@link RelOptRule}
@@ -118,10 +117,10 @@ public class RelOptRuleOperand {
       assert children.size() > 0;
     }
     this.childPolicy = childPolicy;
-    this.clazz = Preconditions.checkNotNull(clazz);
+    this.clazz = Objects.requireNonNull(clazz);
     this.trait = trait;
     //noinspection unchecked
-    this.predicate = Preconditions.checkNotNull((Predicate) predicate);
+    this.predicate = Objects.requireNonNull((Predicate) predicate);
     this.children = children;
     for (RelOptRuleOperand child : this.children) {
       assert child.parent == null : "cannot re-use operands";
@@ -212,7 +211,7 @@ public class RelOptRuleOperand {
     if ((trait != null) && !rel.getTraitSet().contains(trait)) {
       return false;
     }
-    return predicate.apply(rel);
+    return predicate.test(rel);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperandChildren.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperandChildren.java b/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperandChildren.java
index 9d7dc18..3dfab3e 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperandChildren.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptRuleOperandChildren.java
@@ -34,12 +34,12 @@ public class RelOptRuleOperandChildren {
   static final RelOptRuleOperandChildren ANY_CHILDREN =
       new RelOptRuleOperandChildren(
           RelOptRuleOperandChildPolicy.ANY,
-          ImmutableList.<RelOptRuleOperand>of());
+          ImmutableList.of());
 
   static final RelOptRuleOperandChildren LEAF_CHILDREN =
       new RelOptRuleOperandChildren(
           RelOptRuleOperandChildPolicy.LEAF,
-          ImmutableList.<RelOptRuleOperand>of());
+          ImmutableList.of());
 
   final RelOptRuleOperandChildPolicy policy;
   final ImmutableList<RelOptRuleOperand> operands;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptUtil.java b/core/src/main/java/org/apache/calcite/plan/RelOptUtil.java
index b4d666b..38912ca 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptUtil.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptUtil.java
@@ -80,7 +80,6 @@ import org.apache.calcite.rex.RexToSqlNodeConverterImpl;
 import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.runtime.CalciteContextException;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.ModifiableView;
 import org.apache.calcite.sql.SqlExplainFormat;
 import org.apache.calcite.sql.SqlExplainLevel;
@@ -102,14 +101,10 @@ import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.MappingType;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.LinkedHashMultimap;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
 
 import java.io.PrintWriter;
@@ -118,6 +113,7 @@ import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.Collection;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -126,6 +122,7 @@ import java.util.Map.Entry;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
+import java.util.function.Supplier;
 
 /**
  * <code>RelOptUtil</code> defines static utility methods for use in optimizing
@@ -134,49 +131,26 @@ import java.util.TreeSet;
 public abstract class RelOptUtil {
   //~ Static fields/initializers ---------------------------------------------
 
-  public static final double EPSILON = 1.0e-5;
-
-  /** Predicate for whether a filter contains multisets or windowed
-   * aggregates. */
-  public static final Predicate<Filter> FILTER_PREDICATE =
-      new PredicateImpl<Filter>() {
-        public boolean test(Filter filter) {
-          return !(B
-              && RexMultisetUtil.containsMultiset(filter.getCondition(), true)
-              || RexOver.containsOver(filter.getCondition()));
-        }
-      };
+  static final boolean B = false;
 
-  /** Predicate for whether a project contains multisets or windowed
-   * aggregates. */
-  public static final Predicate<Project> PROJECT_PREDICATE =
-      new PredicateImpl<Project>() {
-        public boolean test(Project project) {
-          return !(B
-              && RexMultisetUtil.containsMultiset(project.getProjects(), true)
-              || RexOver.containsOver(project.getProjects(), null));
-        }
-      };
+  public static final double EPSILON = 1.0e-5;
 
-  /** Predicate for whether a calc contains multisets or windowed
-   * aggregates. */
-  public static final Predicate<Calc> CALC_PREDICATE =
-      new PredicateImpl<Calc>() {
-        public boolean test(Calc calc) {
-          return !(B
-              && RexMultisetUtil.containsMultiset(calc.getProgram())
-              || calc.getProgram().containsAggs());
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<Filter>
+      FILTER_PREDICATE =
+      RelOptUtil::containsMultisetOrWindowedAgg;
 
-  static final boolean B = false;
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<Project>
+      PROJECT_PREDICATE =
+      RelOptUtil::containsMultisetOrWindowedAgg;
 
-  private static final Function<RelDataTypeField, RelDataType> GET_TYPE =
-      new Function<RelDataTypeField, RelDataType>() {
-        public RelDataType apply(RelDataTypeField field) {
-          return field.getType();
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<Calc> CALC_PREDICATE =
+      RelOptUtil::containsMultisetOrWindowedAgg;
 
   //~ Methods ----------------------------------------------------------------
 
@@ -244,11 +218,7 @@ public abstract class RelOptUtil {
    */
   public static List<String> findAllTableQualifiedNames(RelNode rel) {
     return Lists.transform(findAllTables(rel),
-        new Function<RelOptTable, String>() {
-          @Override public String apply(RelOptTable arg0) {
-            return arg0.getQualifiedName().toString();
-          }
-        });
+        table -> table.getQualifiedName().toString());
   }
 
   /**
@@ -347,7 +317,7 @@ public abstract class RelOptUtil {
    * @see org.apache.calcite.rel.type.RelDataType#getFieldNames()
    */
   public static List<RelDataType> getFieldTypeList(final RelDataType type) {
-    return Lists.transform(type.getFieldList(), GET_TYPE);
+    return Lists.transform(type.getFieldList(), RelDataTypeField::getType);
   }
 
   public static boolean areRowTypesEqual(
@@ -574,7 +544,7 @@ public abstract class RelOptUtil {
     if (!outerJoin) {
       final LogicalAggregate aggregate =
           LogicalAggregate.create(ret, ImmutableBitSet.range(keyCount), null,
-              ImmutableList.<AggregateCall>of());
+              ImmutableList.of());
       return new Exists(aggregate, false, false);
     }
 
@@ -635,7 +605,7 @@ public abstract class RelOptUtil {
       assert inputField.getType().equals(outputField.getType());
       final RexBuilder rexBuilder = rel.getCluster().getRexBuilder();
       renames.add(
-          Pair.<RexNode, String>of(
+          Pair.of(
               rexBuilder.makeInputRef(inputField.getType(),
                   inputField.getIndex()),
               outputField.getName()));
@@ -814,7 +784,7 @@ public abstract class RelOptUtil {
   public static RelNode createDistinctRel(RelNode rel) {
     return LogicalAggregate.create(rel,
         ImmutableBitSet.range(rel.getRowType().getFieldCount()), null,
-        ImmutableList.<AggregateCall>of());
+        ImmutableList.of());
   }
 
   @Deprecated // to be removed before 2.0
@@ -1720,7 +1690,7 @@ public abstract class RelOptUtil {
       for (int fieldIndex : outputProj) {
         final RelDataTypeField field = joinOutputFields.get(fieldIndex);
         newProjects.add(
-            Pair.<RexNode, String>of(
+            Pair.of(
                 rexBuilder.makeInputRef(field.getType(), fieldIndex),
                 field.getName()));
       }
@@ -2287,7 +2257,7 @@ public abstract class RelOptUtil {
     final RexBuilder rexBuilder = new RexBuilder(typeFactory);
     final RexNode constraint =
         modifiableViewTable.getConstraint(rexBuilder, targetRowType);
-    final Map<Integer, RexNode> projectMap = Maps.newHashMap();
+    final Map<Integer, RexNode> projectMap = new HashMap<>();
     final List<RexNode> filters = new ArrayList<>();
     RelOptUtil.inferViewPredicates(projectMap, filters, constraint);
     assert filters.isEmpty();
@@ -2430,7 +2400,7 @@ public abstract class RelOptUtil {
     ImmutableBitSet rightBitmap =
         ImmutableBitSet.range(nSysFields + nFieldsLeft, nTotalFields);
 
-    final List<RexNode> filtersToRemove = Lists.newArrayList();
+    final List<RexNode> filtersToRemove = new ArrayList<>();
     for (RexNode filter : filters) {
       final InputFinder inputFinder = InputFinder.analyze(filter);
       final ImmutableBitSet inputBits = inputFinder.inputBitSet.build();
@@ -2691,7 +2661,7 @@ public abstract class RelOptUtil {
 
     // create new copies of the bitmaps
     List<RelNode> multiJoinInputs = multiJoin.getInputs();
-    List<BitSet> newProjFields = Lists.newArrayList();
+    List<BitSet> newProjFields = new ArrayList<>();
     for (RelNode multiJoinInput : multiJoinInputs) {
       newProjFields.add(
           new BitSet(multiJoinInput.getRowType().getFieldCount()));
@@ -2722,7 +2692,7 @@ public abstract class RelOptUtil {
         multiJoin.isFullOuterJoin(),
         multiJoin.getOuterJoinConditions(),
         multiJoin.getJoinTypes(),
-        Lists.transform(newProjFields, ImmutableBitSet.FROM_BIT_SET),
+        Lists.transform(newProjFields, ImmutableBitSet::fromBitSet),
         multiJoin.getJoinFieldRefCountsMap(),
         multiJoin.getPostJoinFilter());
   }
@@ -3093,8 +3063,8 @@ public abstract class RelOptUtil {
     if (mapping.isIdentity()) {
       return rel;
     }
-    final List<String> outputNameList = Lists.newArrayList();
-    final List<RexNode> exprList = Lists.newArrayList();
+    final List<String> outputNameList = new ArrayList<>();
+    final List<RexNode> exprList = new ArrayList<>();
     final List<RelDataTypeField> fields = rel.getRowType().getFieldList();
     final RexBuilder rexBuilder = rel.getCluster().getRexBuilder();
     for (int i = 0; i < mapping.getTargetCount(); i++) {
@@ -3110,6 +3080,30 @@ public abstract class RelOptUtil {
     return projectFactory.createProject(rel, exprList, outputNameList);
   }
 
+  /** Predicate for whether a {@link Calc} contains multisets or windowed
+   * aggregates. */
+  public static boolean containsMultisetOrWindowedAgg(Calc calc) {
+    return !(B
+        && RexMultisetUtil.containsMultiset(calc.getProgram())
+        || calc.getProgram().containsAggs());
+  }
+
+  /** Predicate for whether a {@link Filter} contains multisets or windowed
+   * aggregates. */
+  public static boolean containsMultisetOrWindowedAgg(Filter filter) {
+    return !(B
+        && RexMultisetUtil.containsMultiset(filter.getCondition(), true)
+        || RexOver.containsOver(filter.getCondition()));
+  }
+
+  /** Predicate for whether a {@link Project} contains multisets or windowed
+   * aggregates. */
+  public static boolean containsMultisetOrWindowedAgg(Project project) {
+    return !(B
+        && RexMultisetUtil.containsMultiset(project.getProjects(), true)
+        || RexOver.containsOver(project.getProjects(), null));
+  }
+
   /** Policies for handling two- and three-valued boolean logic. */
   public enum Logic {
     /** Three-valued boolean logic. */
@@ -3221,7 +3215,7 @@ public abstract class RelOptUtil {
             public Pair<RexNode, String> get(int index) {
               if (index < leftCount) {
                 RelDataTypeField field = fields.get(index);
-                return Pair.<RexNode, String>of(
+                return Pair.of(
                     new RexInputRef(index, field.getType()), field.getName());
               } else {
                 return Pair.of(extraLeftExprs.get(index - leftCount), null);
@@ -3245,7 +3239,7 @@ public abstract class RelOptUtil {
             public Pair<RexNode, String> get(int index) {
               if (index < rightCount) {
                 RelDataTypeField field = fields.get(index);
-                return Pair.<RexNode, String>of(
+                return Pair.of(
                     new RexInputRef(index, field.getType()),
                     field.getName());
               } else {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelTraitDef.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelTraitDef.java b/core/src/main/java/org/apache/calcite/plan/RelTraitDef.java
index 809dd21..1f0bdf8 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelTraitDef.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelTraitDef.java
@@ -59,12 +59,7 @@ public abstract class RelTraitDef<T extends RelTrait> {
   private final LoadingCache<T, T> canonicalMap =
       CacheBuilder.newBuilder()
           .softValues()
-          .build(
-              new CacheLoader<T, T>() {
-                @Override public T load(@Nonnull T key) throws Exception {
-                  return key;
-                }
-              });
+          .build(CacheLoader.from(key -> key));
 
   /** Cache of composite traits.
    *

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelTraitSet.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelTraitSet.java b/core/src/main/java/org/apache/calcite/plan/RelTraitSet.java
index 5499bdb..717ef07 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelTraitSet.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelTraitSet.java
@@ -19,7 +19,6 @@ package org.apache.calcite.plan;
 import org.apache.calcite.runtime.FlatLists;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.util.AbstractList;
@@ -27,6 +26,7 @@ import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Supplier;
 
 /**
  * RelTraitSet represents an ordered set of {@link RelTrait}s.
@@ -551,7 +551,7 @@ public final class RelTraitSet extends AbstractList<RelTrait> {
         return traitSet1;
       }
       final RelTraitSet traitSet =
-          new RelTraitSet(this, traits.toArray(new RelTrait[traits.size()]));
+          new RelTraitSet(this, traits.toArray(new RelTrait[0]));
       map.put(traits, traitSet);
       return traitSet;
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RexImplicationChecker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RexImplicationChecker.java b/core/src/main/java/org/apache/calcite/plan/RexImplicationChecker.java
index f7cd9e1..f2b32f2 100644
--- a/core/src/main/java/org/apache/calcite/plan/RexImplicationChecker.java
+++ b/core/src/main/java/org/apache/calcite/plan/RexImplicationChecker.java
@@ -32,7 +32,6 @@ import org.apache.calcite.sql.fun.SqlCastFunction;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.trace.CalciteLogger;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
@@ -43,6 +42,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -70,9 +70,9 @@ public class RexImplicationChecker {
       RexBuilder builder,
       RexExecutorImpl executor,
       RelDataType rowType) {
-    this.builder = Preconditions.checkNotNull(builder);
-    this.executor = Preconditions.checkNotNull(executor);
-    this.rowType = Preconditions.checkNotNull(rowType);
+    this.builder = Objects.requireNonNull(builder);
+    this.executor = Objects.requireNonNull(executor);
+    this.rowType = Objects.requireNonNull(rowType);
   }
 
   /**
@@ -196,8 +196,8 @@ public class RexImplicationChecker {
     final InputUsageFinder firstUsageFinder = new InputUsageFinder();
     final InputUsageFinder secondUsageFinder = new InputUsageFinder();
 
-    RexUtil.apply(firstUsageFinder, ImmutableList.<RexNode>of(), first);
-    RexUtil.apply(secondUsageFinder, ImmutableList.<RexNode>of(), second);
+    RexUtil.apply(firstUsageFinder, ImmutableList.of(), first);
+    RexUtil.apply(secondUsageFinder, ImmutableList.of(), second);
 
     // Check Support
     if (!checkSupport(firstUsageFinder, secondUsageFinder)) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/Strong.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/Strong.java b/core/src/main/java/org/apache/calcite/plan/Strong.java
index e631d90..39a4515 100644
--- a/core/src/main/java/org/apache/calcite/plan/Strong.java
+++ b/core/src/main/java/org/apache/calcite/plan/Strong.java
@@ -24,7 +24,6 @@ import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
@@ -32,6 +31,7 @@ import java.util.ArrayList;
 import java.util.EnumMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /** Utilities for strong predicates.
  *
@@ -87,7 +87,7 @@ public class Strong {
   /** Returns how to deduce whether a particular kind of expression is null,
    * given whether its arguments are null. */
   public static Policy policy(SqlKind kind) {
-    return Preconditions.checkNotNull(MAP.get(kind), kind);
+    return Objects.requireNonNull(MAP.get(kind), kind.toString());
   }
 
   /** Returns whether an expression is definitely not true. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java b/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java
index 0625bff..c8f92c7 100644
--- a/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java
+++ b/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java
@@ -44,7 +44,6 @@ import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexShuttle;
 import org.apache.calcite.rex.RexSimplify;
 import org.apache.calcite.rex.RexUtil;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.tools.RelBuilder;
@@ -60,13 +59,9 @@ import org.apache.calcite.util.mapping.Mappings;
 import org.apache.calcite.util.trace.CalciteTrace;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.LinkedHashMultimap;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Sets;
 
@@ -78,6 +73,7 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
@@ -122,7 +118,7 @@ public class SubstitutionVisitor {
   private static final Logger LOGGER = CalciteTrace.getPlannerTracer();
 
   protected static final ImmutableList<UnifyRule> DEFAULT_RULES =
-      ImmutableList.<UnifyRule>of(
+      ImmutableList.of(
           TrivialRule.INSTANCE,
           ScanToProjectUnifyRule.INSTANCE,
           ProjectToProjectUnifyRule.INSTANCE,
@@ -472,7 +468,7 @@ public class SubstitutionVisitor {
     if (matches.isEmpty()) {
       return ImmutableList.of();
     }
-    List<RelNode> sub = Lists.newArrayList();
+    List<RelNode> sub = new ArrayList<>();
     sub.add(MutableRels.fromMutable(query.getInput(), relBuilder));
     reverseSubstitute(relBuilder, query, matches, sub, 0, matches.size());
     return sub;
@@ -493,7 +489,7 @@ public class SubstitutionVisitor {
 
     // Populate "equivalents" with (q, t) for each query descendant q and
     // target descendant t that are equal.
-    final Map<MutableRel, MutableRel> map = Maps.newHashMap();
+    final Map<MutableRel, MutableRel> map = new HashMap<>();
     for (MutableRel queryDescendant : queryDescendants) {
       map.put(queryDescendant, queryDescendant);
     }
@@ -506,8 +502,8 @@ public class SubstitutionVisitor {
     }
     map.clear();
 
-    final List<Replacement> attempted = Lists.newArrayList();
-    List<List<Replacement>> substitutions = Lists.newArrayList();
+    final List<Replacement> attempted = new ArrayList<>();
+    List<List<Replacement>> substitutions = new ArrayList<>();
 
     for (;;) {
       int count = 0;
@@ -863,10 +859,10 @@ public class SubstitutionVisitor {
 
     public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target,
         ImmutableList<MutableRel> slots) {
-      this.rule = Preconditions.checkNotNull(rule);
-      this.query = Preconditions.checkNotNull(query);
-      this.target = Preconditions.checkNotNull(target);
-      this.slots = Preconditions.checkNotNull(slots);
+      this.rule = Objects.requireNonNull(rule);
+      this.query = Objects.requireNonNull(query);
+      this.target = Objects.requireNonNull(target);
+      this.slots = Objects.requireNonNull(slots);
     }
 
     public UnifyResult result(MutableRel result) {
@@ -1257,12 +1253,8 @@ public class SubstitutionVisitor {
   private static List<AggregateCall> apply(final Mapping mapping,
       List<AggregateCall> aggCallList) {
     return Lists.transform(aggCallList,
-        new Function<AggregateCall, AggregateCall>() {
-          public AggregateCall apply(AggregateCall call) {
-            return call.copy(Mappings.apply2(mapping, call.getArgList()),
-                Mappings.apply(mapping, call.filterArg));
-          }
-        });
+        call -> call.copy(Mappings.apply2(mapping, call.getArgList()),
+            Mappings.apply(mapping, call.filterArg)));
   }
 
   public static MutableRel unifyAggregates(MutableAggregate query,
@@ -1274,7 +1266,7 @@ public class SubstitutionVisitor {
     MutableRel result;
     if (query.groupSet.equals(target.groupSet)) {
       // Same level of aggregation. Generate a project.
-      final List<Integer> projects = Lists.newArrayList();
+      final List<Integer> projects = new ArrayList<>();
       final int groupCount = query.groupSet.cardinality();
       for (int i = 0; i < groupCount; i++) {
         projects.add(i);
@@ -1298,7 +1290,7 @@ public class SubstitutionVisitor {
         }
         groupSet.set(c2);
       }
-      final List<AggregateCall> aggregateCalls = Lists.newArrayList();
+      final List<AggregateCall> aggregateCalls = new ArrayList<>();
       for (AggregateCall aggregateCall : query.aggCalls) {
         if (aggregateCall.isDistinct()) {
           return null;
@@ -1582,13 +1574,6 @@ public class SubstitutionVisitor {
    * trivial filter (on a boolean column).
    */
   public static class FilterOnProjectRule extends RelOptRule {
-    private static final Predicate<LogicalFilter> PREDICATE =
-        new PredicateImpl<LogicalFilter>() {
-          public boolean test(LogicalFilter input) {
-            return input.getCondition() instanceof RexInputRef;
-          }
-        };
-
     public static final FilterOnProjectRule INSTANCE =
         new FilterOnProjectRule(RelFactories.LOGICAL_BUILDER);
 
@@ -1599,7 +1584,8 @@ public class SubstitutionVisitor {
      */
     public FilterOnProjectRule(RelBuilderFactory relBuilderFactory) {
       super(
-          operand(LogicalFilter.class, null, PREDICATE,
+          operandJ(LogicalFilter.class, null,
+              filter -> filter.getCondition() instanceof RexInputRef,
               some(operand(LogicalProject.class, any()))),
           relBuilderFactory, null);
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/hep/HepPlanner.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/hep/HepPlanner.java b/core/src/main/java/org/apache/calcite/plan/hep/HepPlanner.java
index c022d8b..3f7f73e 100644
--- a/core/src/main/java/org/apache/calcite/plan/hep/HepPlanner.java
+++ b/core/src/main/java/org/apache/calcite/plan/hep/HepPlanner.java
@@ -133,7 +133,7 @@ public class HepPlanner extends AbstractRelOptPlanner {
     super(costFactory, context);
     this.mainProgram = program;
     this.onCopyHook =
-        Util.first(onCopyHook, Functions.<RelNode, RelNode, Void>ignore2());
+        Util.first(onCopyHook, Functions.ignore2());
     mapDigestToVertex = new HashMap<>();
     graph = DefaultDirectedGraph.create();
 
@@ -544,7 +544,7 @@ public class HepPlanner extends AbstractRelOptPlanner {
         new HepRuleCall(
             this,
             rule.getOperand(),
-            bindings.toArray(new RelNode[bindings.size()]),
+            bindings.toArray(new RelNode[0]),
             nodeChildren,
             parents);
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/hep/HepRelMetadataProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/hep/HepRelMetadataProvider.java b/core/src/main/java/org/apache/calcite/plan/hep/HepRelMetadataProvider.java
index 48681eb..103018b 100644
--- a/core/src/main/java/org/apache/calcite/plan/hep/HepRelMetadataProvider.java
+++ b/core/src/main/java/org/apache/calcite/plan/hep/HepRelMetadataProvider.java
@@ -21,7 +21,6 @@ import org.apache.calcite.rel.metadata.Metadata;
 import org.apache.calcite.rel.metadata.MetadataDef;
 import org.apache.calcite.rel.metadata.MetadataHandler;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
-import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.metadata.UnboundMetadata;
 
 import com.google.common.collect.ImmutableMultimap;
@@ -47,18 +46,16 @@ class HepRelMetadataProvider implements RelMetadataProvider {
   public <M extends Metadata> UnboundMetadata<M> apply(
       Class<? extends RelNode> relClass,
       final Class<? extends M> metadataClass) {
-    return new UnboundMetadata<M>() {
-      public M bind(RelNode rel, RelMetadataQuery mq) {
-        if (!(rel instanceof HepRelVertex)) {
-          return null;
-        }
-        HepRelVertex vertex = (HepRelVertex) rel;
-        final RelNode rel2 = vertex.getCurrentRel();
-        UnboundMetadata<M> function =
-            rel.getCluster().getMetadataProvider().apply(rel2.getClass(),
-                metadataClass);
-        return function.bind(rel2, mq);
+    return (rel, mq) -> {
+      if (!(rel instanceof HepRelVertex)) {
+        return null;
       }
+      HepRelVertex vertex = (HepRelVertex) rel;
+      final RelNode rel2 = vertex.getCurrentRel();
+      UnboundMetadata<M> function =
+          rel.getCluster().getMetadataProvider().apply(rel2.getClass(),
+              metadataClass);
+      return function.bind(rel2, mq);
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/volcano/RelSubset.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/volcano/RelSubset.java b/core/src/main/java/org/apache/calcite/plan/volcano/RelSubset.java
index 60f4a07..8352ffe 100644
--- a/core/src/main/java/org/apache/calcite/plan/volcano/RelSubset.java
+++ b/core/src/main/java/org/apache/calcite/plan/volcano/RelSubset.java
@@ -17,7 +17,6 @@
 package org.apache.calcite.plan.volcano;
 
 import org.apache.calcite.linq4j.Linq4j;
-import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptCost;
 import org.apache.calcite.plan.RelOptListener;
@@ -41,7 +40,6 @@ import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
@@ -387,18 +385,9 @@ public class RelSubset extends AbstractRelNode {
    * @return all the rels in the subset
    */
   public Iterable<RelNode> getRels() {
-    return new Iterable<RelNode>() {
-      public Iterator<RelNode> iterator() {
-        return Linq4j.asEnumerable(set.rels)
-            .where(
-                new Predicate1<RelNode>() {
-                  public boolean apply(RelNode v1) {
-                    return v1.getTraitSet().satisfies(traitSet);
-                  }
-                })
-            .iterator();
-      }
-    };
+    return () -> Linq4j.asEnumerable(set.rels)
+        .where(v1 -> v1.getTraitSet().satisfies(traitSet))
+        .iterator();
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/volcano/RuleQueue.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/volcano/RuleQueue.java b/core/src/main/java/org/apache/calcite/plan/volcano/RuleQueue.java
index 1e2713f..10b9553 100644
--- a/core/src/main/java/org/apache/calcite/plan/volcano/RuleQueue.java
+++ b/core/src/main/java/org/apache/calcite/plan/volcano/RuleQueue.java
@@ -37,7 +37,6 @@ import java.io.StringWriter;
 import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.Deque;
 import java.util.EnumMap;
@@ -235,32 +234,30 @@ class RuleQueue {
       }
     }
 
-    Collections.sort(
-        boostRemovals,
-        new Comparator<RelSubset>() {
-          public int compare(RelSubset o1, RelSubset o2) {
-            int o1children = countChildren(o1);
-            int o2children = countChildren(o2);
-            int c = compare(o1children, o2children);
-            if (c == 0) {
-              // for determinism
-              c = compare(o1.getId(), o2.getId());
-            }
-            return c;
-          }
+    boostRemovals.sort(new Comparator<RelSubset>() {
+      public int compare(RelSubset o1, RelSubset o2) {
+        int o1children = countChildren(o1);
+        int o2children = countChildren(o2);
+        int c = compare(o1children, o2children);
+        if (c == 0) {
+          // for determinism
+          c = compare(o1.getId(), o2.getId());
+        }
+        return c;
+      }
 
-          private int compare(int i1, int i2) {
-            return (i1 < i2) ? -1 : ((i1 == i2) ? 0 : 1);
-          }
+      private int compare(int i1, int i2) {
+        return (i1 < i2) ? -1 : ((i1 == i2) ? 0 : 1);
+      }
 
-          private int countChildren(RelSubset subset) {
-            int count = 0;
-            for (RelNode rel : subset.getRels()) {
-              count += rel.getInputs().size();
-            }
-            return count;
-          }
-        });
+      private int countChildren(RelSubset subset) {
+        int count = 0;
+        for (RelNode rel : subset.getRels()) {
+          count += rel.getInputs().size();
+        }
+        return count;
+      }
+    });
 
     for (RelSubset subset : boostRemovals) {
       subset.propagateBoostRemoval(planner);
@@ -452,7 +449,7 @@ class RuleQueue {
         return null;
       }
       if (LOGGER.isTraceEnabled()) {
-        Collections.sort(matchList, MATCH_COMPARATOR);
+        matchList.sort(MATCH_COMPARATOR);
         match = matchList.remove(0);
 
         StringBuilder b = new StringBuilder();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoPlanner.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoPlanner.java b/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoPlanner.java
index 281e472..231de4d 100644
--- a/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoPlanner.java
+++ b/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoPlanner.java
@@ -69,12 +69,9 @@ import org.apache.calcite.util.Util;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.LinkedHashMultimap;
 import com.google.common.collect.LinkedListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Ordering;
 import com.google.common.collect.SetMultimap;
-import com.google.common.collect.Sets;
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
@@ -82,12 +79,12 @@ import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.Deque;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.IdentityHashMap;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -230,11 +227,13 @@ public class VolcanoPlanner extends AbstractRelOptPlanner {
   private boolean locked;
 
   private final List<RelOptMaterialization> materializations =
-      Lists.newArrayList();
+      new ArrayList<>();
 
-  /** Map of lattices by the qualified name of their star table. */
+  /**
+   * Map of lattices by the qualified name of their star table.
+   */
   private final Map<List<String>, RelOptLattice> latticeByName =
-      Maps.newLinkedHashMap();
+      new LinkedHashMap<>();
 
   final Map<RelNode, Provenance> provenanceMap = new HashMap<>();
 
@@ -283,14 +282,11 @@ public class VolcanoPlanner extends AbstractRelOptPlanner {
 
   protected VolcanoPlannerPhaseRuleMappingInitializer
       getPhaseRuleMappingInitializer() {
-    return new VolcanoPlannerPhaseRuleMappingInitializer() {
-      public void initialize(
-          Map<VolcanoPlannerPhase, Set<String>> phaseRuleMap) {
-        // Disable all phases except OPTIMIZE by adding one useless rule name.
-        phaseRuleMap.get(VolcanoPlannerPhase.PRE_PROCESS_MDR).add("xxx");
-        phaseRuleMap.get(VolcanoPlannerPhase.PRE_PROCESS).add("xxx");
-        phaseRuleMap.get(VolcanoPlannerPhase.CLEANUP).add("xxx");
-      }
+    return phaseRuleMap -> {
+      // Disable all phases except OPTIMIZE by adding one useless rule name.
+      phaseRuleMap.get(VolcanoPlannerPhase.PRE_PROCESS_MDR).add("xxx");
+      phaseRuleMap.get(VolcanoPlannerPhase.PRE_PROCESS).add("xxx");
+      phaseRuleMap.get(VolcanoPlannerPhase.CLEANUP).add("xxx");
     };
   }
 
@@ -689,7 +685,7 @@ public class VolcanoPlanner extends AbstractRelOptPlanner {
    * will be asking for the result in a particular convention, but the root has
    * no consumers. */
   void ensureRootConverters() {
-    final Set<RelSubset> subsets = Sets.newHashSet();
+    final Set<RelSubset> subsets = new HashSet<>();
     for (RelNode rel : root.getRels()) {
       if (rel instanceof AbstractConverter) {
         subsets.add((RelSubset) ((AbstractConverter) rel).getInput());
@@ -1172,14 +1168,7 @@ public class VolcanoPlanner extends AbstractRelOptPlanner {
     pw.println("Original rel:");
     pw.println(originalRootString);
     pw.println("Sets:");
-    Ordering<RelSet> ordering = Ordering.from(
-        new Comparator<RelSet>() {
-          public int compare(
-              RelSet o1,
-              RelSet o2) {
-            return o1.id - o2.id;
-          }
-        });
+    Ordering<RelSet> ordering = Ordering.from((o1, o2) -> o1.id - o2.id);
     for (RelSet set : ordering.immutableSortedCopy(allSets)) {
       pw.println("Set#" + set.id
           + ", type: " + set.subsets.get(0).getRowType());

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRelMetadataProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRelMetadataProvider.java b/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRelMetadataProvider.java
index 17f28f7..9d96fef 100644
--- a/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRelMetadataProvider.java
+++ b/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRelMetadataProvider.java
@@ -21,7 +21,6 @@ import org.apache.calcite.rel.metadata.Metadata;
 import org.apache.calcite.rel.metadata.MetadataDef;
 import org.apache.calcite.rel.metadata.MetadataHandler;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
-import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.metadata.UnboundMetadata;
 
 import com.google.common.collect.ImmutableMultimap;
@@ -52,66 +51,64 @@ public class VolcanoRelMetadataProvider implements RelMetadataProvider {
       return null;
     }
 
-    return new UnboundMetadata<M>() {
-      public M bind(RelNode rel, RelMetadataQuery mq) {
-        final RelSubset subset = (RelSubset) rel;
-        final RelMetadataProvider provider =
-            rel.getCluster().getMetadataProvider();
-
-        // REVIEW jvs 29-Mar-2006: I'm not sure what the correct precedence
-        // should be here.  Letting the current best plan take the first shot is
-        // probably the right thing to do for physical estimates such as row
-        // count.  Dunno about others, and whether we need a way to
-        // discriminate.
-
-        // First, try current best implementation.  If it knows how to answer
-        // this query, treat it as the most reliable.
-        if (subset.best != null) {
-          final UnboundMetadata<M> function =
-              provider.apply(subset.best.getClass(), metadataClass);
-          if (function != null) {
-            final M metadata = function.bind(subset.best, mq);
-            if (metadata != null) {
-              return metadata;
-            }
+    return (rel, mq) -> {
+      final RelSubset subset = (RelSubset) rel;
+      final RelMetadataProvider provider =
+          rel.getCluster().getMetadataProvider();
+
+      // REVIEW jvs 29-Mar-2006: I'm not sure what the correct precedence
+      // should be here.  Letting the current best plan take the first shot is
+      // probably the right thing to do for physical estimates such as row
+      // count.  Dunno about others, and whether we need a way to
+      // discriminate.
+
+      // First, try current best implementation.  If it knows how to answer
+      // this query, treat it as the most reliable.
+      if (subset.best != null) {
+        final UnboundMetadata<M> function =
+            provider.apply(subset.best.getClass(), metadataClass);
+        if (function != null) {
+          final M metadata = function.bind(subset.best, mq);
+          if (metadata != null) {
+            return metadata;
           }
         }
+      }
 
-        // Otherwise, try rels in same logical equivalence class to see if any
-        // of them have a good answer.  We use the full logical equivalence
-        // class rather than just the subset because many metadata providers
-        // only know about logical metadata.
-
-        // Equivalence classes can get tangled up in interesting ways, so avoid
-        // an infinite loop.  REVIEW: There's a chance this will cause us to
-        // fail on metadata queries which invoke other queries, e.g.
-        // PercentageOriginalRows -> Selectivity.  If we implement caching at
-        // this level, we could probably kill two birds with one stone (use
-        // presence of pending cache entry to detect re-entrancy at the correct
-        // granularity).
-        if (subset.set.inMetadataQuery) {
-          return null;
-        }
+      // Otherwise, try rels in same logical equivalence class to see if any
+      // of them have a good answer.  We use the full logical equivalence
+      // class rather than just the subset because many metadata providers
+      // only know about logical metadata.
+
+      // Equivalence classes can get tangled up in interesting ways, so avoid
+      // an infinite loop.  REVIEW: There's a chance this will cause us to
+      // fail on metadata queries which invoke other queries, e.g.
+      // PercentageOriginalRows -> Selectivity.  If we implement caching at
+      // this level, we could probably kill two birds with one stone (use
+      // presence of pending cache entry to detect re-entrancy at the correct
+      // granularity).
+      if (subset.set.inMetadataQuery) {
+        return null;
+      }
 
-        subset.set.inMetadataQuery = true;
-        try {
-          for (RelNode relCandidate : subset.set.rels) {
-            final UnboundMetadata<M> function =
-                provider.apply(relCandidate.getClass(), metadataClass);
-            if (function != null) {
-              final M result = function.bind(relCandidate, mq);
-              if (result != null) {
-                return result;
-              }
+      subset.set.inMetadataQuery = true;
+      try {
+        for (RelNode relCandidate : subset.set.rels) {
+          final UnboundMetadata<M> function =
+              provider.apply(relCandidate.getClass(), metadataClass);
+          if (function != null) {
+            final M result = function.bind(relCandidate, mq);
+            if (result != null) {
+              return result;
             }
           }
-        } finally {
-          subset.set.inMetadataQuery = false;
         }
-
-        // Give up.
-        return null;
+      } finally {
+        subset.set.inMetadataQuery = false;
       }
+
+      // Give up.
+      return null;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRuleCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRuleCall.java b/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRuleCall.java
index 392581d..ac883f0 100644
--- a/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRuleCall.java
+++ b/core/src/main/java/org/apache/calcite/plan/volcano/VolcanoRuleCall.java
@@ -80,7 +80,7 @@ public class VolcanoRuleCall extends RelOptRuleCall {
         planner,
         operand,
         new RelNode[operand.getRule().operands.size()],
-        ImmutableMap.<RelNode, List<RelNode>>of());
+        ImmutableMap.of());
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/CalciteCatalogReader.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/CalciteCatalogReader.java b/core/src/main/java/org/apache/calcite/prepare/CalciteCatalogReader.java
index c49a9cb..cbfd145 100644
--- a/core/src/main/java/org/apache/calcite/prepare/CalciteCatalogReader.java
+++ b/core/src/main/java/org/apache/calcite/prepare/CalciteCatalogReader.java
@@ -26,7 +26,6 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeFactoryImpl;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rel.type.RelDataTypeSystem;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.AggregateFunction;
 import org.apache.calcite.schema.Function;
 import org.apache.calcite.schema.FunctionParameter;
@@ -39,7 +38,6 @@ import org.apache.calcite.schema.impl.ScalarFunctionImpl;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.SqlOperator;
-import org.apache.calcite.sql.SqlOperatorBinding;
 import org.apache.calcite.sql.SqlOperatorTable;
 import org.apache.calcite.sql.SqlSyntax;
 import org.apache.calcite.sql.parser.SqlParserPos;
@@ -64,10 +62,6 @@ import org.apache.calcite.sql.validate.SqlUserDefinedTableMacro;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
@@ -78,6 +72,8 @@ import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.NavigableSet;
+import java.util.Objects;
+import java.util.function.Predicate;
 
 /**
  * Implementation of {@link org.apache.calcite.prepare.Prepare.CatalogReader}
@@ -94,15 +90,15 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
   public CalciteCatalogReader(CalciteSchema rootSchema,
       List<String> defaultSchema, RelDataTypeFactory typeFactory, CalciteConnectionConfig config) {
     this(rootSchema, SqlNameMatchers.withCaseSensitive(config != null && config.caseSensitive()),
-        ImmutableList.of(Preconditions.checkNotNull(defaultSchema),
-            ImmutableList.<String>of()),
+        ImmutableList.of(Objects.requireNonNull(defaultSchema),
+            ImmutableList.of()),
         typeFactory, config);
   }
 
   protected CalciteCatalogReader(CalciteSchema rootSchema,
       SqlNameMatcher nameMatcher, List<List<String>> schemaPaths,
       RelDataTypeFactory typeFactory, CalciteConnectionConfig config) {
-    this.rootSchema = Preconditions.checkNotNull(rootSchema);
+    this.rootSchema = Objects.requireNonNull(rootSchema);
     this.nameMatcher = nameMatcher;
     this.schemaPaths =
         Util.immutableCopy(Util.isDistinct(schemaPaths)
@@ -114,7 +110,7 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
 
   public CalciteCatalogReader withSchemaPath(List<String> schemaPath) {
     return new CalciteCatalogReader(rootSchema, nameMatcher,
-        ImmutableList.of(schemaPath, ImmutableList.<String>of()), typeFactory, config);
+        ImmutableList.of(schemaPath, ImmutableList.of()), typeFactory, config);
   }
 
   public Prepare.PreparingTable getTable(final List<String> names) {
@@ -141,7 +137,7 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
   }
 
   private Collection<Function> getFunctionsFrom(List<String> names) {
-    final List<Function> functions2 = Lists.newArrayList();
+    final List<Function> functions2 = new ArrayList<>();
     final List<List<String>> schemaNameList = new ArrayList<>();
     if (names.size() > 1) {
       // Name qualified: ignore path. But we do look in "/catalog" and "/",
@@ -256,34 +252,21 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
 
     final Predicate<Function> predicate;
     if (category == null) {
-      predicate = Predicates.alwaysTrue();
+      predicate = function -> true;
     } else if (category.isTableFunction()) {
-      predicate = new PredicateImpl<Function>() {
-        public boolean test(Function function) {
-          return function instanceof TableMacro
+      predicate = function ->
+          function instanceof TableMacro
               || function instanceof TableFunction;
-        }
-      };
     } else {
-      predicate = new PredicateImpl<Function>() {
-        public boolean test(Function function) {
-          return !(function instanceof TableMacro
+      predicate = function ->
+          !(function instanceof TableMacro
               || function instanceof TableFunction);
-        }
-      };
-    }
-    final Collection<Function> functions =
-        Collections2.filter(getFunctionsFrom(opName.names), predicate);
-    if (functions.isEmpty()) {
-      return;
     }
-    operatorList.addAll(
-        Collections2.transform(functions,
-            new com.google.common.base.Function<Function, SqlOperator>() {
-              public SqlOperator apply(Function function) {
-                return toOp(opName, function);
-              }
-            }));
+    getFunctionsFrom(opName.names)
+        .stream()
+        .filter(predicate)
+        .map(function -> toOp(opName, function))
+        .forEachOrdered(operatorList::add);
   }
 
   /** Creates an operator table that contains functions in the given class.
@@ -293,7 +276,7 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
     // Dummy schema to collect the functions
     final CalciteSchema schema =
         CalciteSchema.createRootSchema(false, false);
-    ModelHandler.addFunctions(schema.plus(), null, ImmutableList.<String>of(),
+    ModelHandler.addFunctions(schema.plus(), null, ImmutableList.of(),
         className, "*", true);
 
     // The following is technical debt; see [CALCITE-2082] Remove
@@ -331,14 +314,9 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
       typeFamilies.add(
           Util.first(type.getSqlTypeName().getFamily(), SqlTypeFamily.ANY));
     }
-    final Predicate<Integer> optional =
-        new PredicateImpl<Integer>() {
-          public boolean test(Integer input) {
-            return function.getParameters().get(input).isOptional();
-          }
-        };
     final FamilyOperandTypeChecker typeChecker =
-        OperandTypes.family(typeFamilies, optional);
+        OperandTypes.family(typeFamilies, i ->
+            function.getParameters().get(i).isOptional());
     final List<RelDataType> paramTypes = toSql(typeFactory, argTypes);
     if (function instanceof ScalarFunction) {
       return new SqlUserDefinedFunction(name, infer((ScalarFunction) function),
@@ -361,40 +339,31 @@ public class CalciteCatalogReader implements Prepare.CatalogReader {
   }
 
   private static SqlReturnTypeInference infer(final ScalarFunction function) {
-    return new SqlReturnTypeInference() {
-      public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-        final RelDataType type;
-        if (function instanceof ScalarFunctionImpl) {
-          type = ((ScalarFunctionImpl) function).getReturnType(typeFactory,
-              opBinding);
-        } else {
-          type = function.getReturnType(typeFactory);
-        }
-        return toSql(typeFactory, type);
+    return opBinding -> {
+      final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+      final RelDataType type;
+      if (function instanceof ScalarFunctionImpl) {
+        type = ((ScalarFunctionImpl) function).getReturnType(typeFactory,
+            opBinding);
+      } else {
+        type = function.getReturnType(typeFactory);
       }
+      return toSql(typeFactory, type);
     };
   }
 
   private static SqlReturnTypeInference infer(
       final AggregateFunction function) {
-    return new SqlReturnTypeInference() {
-      public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-        final RelDataType type = function.getReturnType(typeFactory);
-        return toSql(typeFactory, type);
-      }
+    return opBinding -> {
+      final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+      final RelDataType type = function.getReturnType(typeFactory);
+      return toSql(typeFactory, type);
     };
   }
 
   private static List<RelDataType> toSql(
       final RelDataTypeFactory typeFactory, List<RelDataType> types) {
-    return Lists.transform(types,
-        new com.google.common.base.Function<RelDataType, RelDataType>() {
-          public RelDataType apply(RelDataType type) {
-            return toSql(typeFactory, type);
-          }
-        });
+    return Lists.transform(types, type -> toSql(typeFactory, type));
   }
 
   private static RelDataType toSql(RelDataTypeFactory typeFactory,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/CalciteMaterializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/CalciteMaterializer.java b/core/src/main/java/org/apache/calcite/prepare/CalciteMaterializer.java
index 92cb104..45c4850 100644
--- a/core/src/main/java/org/apache/calcite/prepare/CalciteMaterializer.java
+++ b/core/src/main/java/org/apache/calcite/prepare/CalciteMaterializer.java
@@ -50,8 +50,8 @@ import org.apache.calcite.sql2rel.SqlRexConvertletTable;
 import org.apache.calcite.sql2rel.SqlToRelConverter;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -126,7 +126,7 @@ class CalciteMaterializer extends CalcitePrepareImpl.CalcitePreparingStmt {
       // Don't waste effort converting to leaf-join form.
       return ImmutableList.of();
     }
-    final List<Callback> list = Lists.newArrayList();
+    final List<Callback> list = new ArrayList<>();
     final RelNode rel2 =
         RelOptMaterialization.toLeafJoinForm(queryRel);
     for (CalciteSchema.TableEntry starTable : starTables) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/CalcitePrepareImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/CalcitePrepareImpl.java b/core/src/main/java/org/apache/calcite/prepare/CalcitePrepareImpl.java
index 9b772be..5a6d521 100644
--- a/core/src/main/java/org/apache/calcite/prepare/CalcitePrepareImpl.java
+++ b/core/src/main/java/org/apache/calcite/prepare/CalcitePrepareImpl.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.prepare;
 
-import org.apache.calcite.DataContext;
 import org.apache.calcite.adapter.enumerable.EnumerableBindable;
 import org.apache.calcite.adapter.enumerable.EnumerableCalc;
 import org.apache.calcite.adapter.enumerable.EnumerableConvention;
@@ -36,7 +35,6 @@ import org.apache.calcite.interpreter.Interpreters;
 import org.apache.calcite.jdbc.CalcitePrepare;
 import org.apache.calcite.jdbc.CalciteSchema;
 import org.apache.calcite.jdbc.CalciteSchema.LatticeEntry;
-import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.Ord;
 import org.apache.calcite.linq4j.Queryable;
@@ -142,7 +140,6 @@ import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
 
 import java.lang.reflect.Type;
 import java.math.BigDecimal;
@@ -151,6 +148,7 @@ import java.sql.Types;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -501,12 +499,8 @@ public class CalcitePrepareImpl implements CalcitePrepare {
    * {@link #createPlanner(org.apache.calcite.jdbc.CalcitePrepare.Context)}.</p>
    */
   protected List<Function1<Context, RelOptPlanner>> createPlannerFactories() {
-    return Collections.<Function1<Context, RelOptPlanner>>singletonList(
-        new Function1<Context, RelOptPlanner>() {
-          public RelOptPlanner apply(Context context) {
-            return createPlanner(context, null, null);
-          }
-        });
+    return Collections.singletonList(
+        context -> createPlanner(context, null, null));
   }
 
   /** Creates a query planner and initializes it with a default set of
@@ -667,19 +661,14 @@ public class CalcitePrepareImpl implements CalcitePrepare {
         Meta.CursorFactory.deduce(columns, null);
     return new CalciteSignature<>(
         sql,
-        ImmutableList.<AvaticaParameter>of(),
-        ImmutableMap.<String, Object>of(),
+        ImmutableList.of(),
+        ImmutableMap.of(),
         x,
         columns,
         cursorFactory,
         context.getRootSchema(),
-        ImmutableList.<RelCollation>of(),
-        -1,
-        new Bindable<T>() {
-          public Enumerable<T> bind(DataContext dataContext) {
-            return Linq4j.asEnumerable(list);
-          }
-        },
+        ImmutableList.of(),
+        -1, dataContext -> Linq4j.asEnumerable(list),
         Meta.StatementType.SELECT);
   }
 
@@ -768,10 +757,10 @@ public class CalcitePrepareImpl implements CalcitePrepare {
         executeDdl(context, sqlNode);
 
         return new CalciteSignature<>(query.sql,
-            ImmutableList.<AvaticaParameter>of(),
-            ImmutableMap.<String, Object>of(), null,
-            ImmutableList.<ColumnMetaData>of(), Meta.CursorFactory.OBJECT,
-            null, ImmutableList.<RelCollation>of(), -1, null,
+            ImmutableList.of(),
+            ImmutableMap.of(), null,
+            ImmutableList.of(), Meta.CursorFactory.OBJECT,
+            null, ImmutableList.of(), -1, null,
             Meta.StatementType.OTHER_DDL);
       }
 
@@ -844,7 +833,7 @@ public class CalcitePrepareImpl implements CalcitePrepare {
         context.getRootSchema(),
         preparedResult instanceof Prepare.PreparedResultImpl
             ? ((Prepare.PreparedResultImpl) preparedResult).collations
-            : ImmutableList.<RelCollation>of(),
+            : ImmutableList.of(),
         maxRowCount,
         bindable,
         statementType);
@@ -1066,7 +1055,7 @@ public class CalcitePrepareImpl implements CalcitePrepare {
     protected final SqlRexConvertletTable convertletTable;
     private final EnumerableRel.Prefer prefer;
     private final Map<String, Object> internalParameters =
-        Maps.newLinkedHashMap();
+        new LinkedHashMap<>();
     private int expansionDepth;
     private SqlValidator sqlValidator;
 
@@ -1095,24 +1084,16 @@ public class CalcitePrepareImpl implements CalcitePrepare {
     public PreparedResult prepareQueryable(
         final Queryable queryable,
         RelDataType resultType) {
-      return prepare_(
-          new Supplier<RelNode>() {
-            public RelNode get() {
-              final RelOptCluster cluster =
-                  prepare.createCluster(planner, rexBuilder);
-              return new LixToRelTranslator(cluster, CalcitePreparingStmt.this)
-                  .translate(queryable);
-            }
-          }, resultType);
+      return prepare_(() -> {
+        final RelOptCluster cluster =
+            prepare.createCluster(planner, rexBuilder);
+        return new LixToRelTranslator(cluster, CalcitePreparingStmt.this)
+            .translate(queryable);
+      }, resultType);
     }
 
     public PreparedResult prepareRel(final RelNode rel) {
-      return prepare_(
-          new Supplier<RelNode>() {
-            public RelNode get() {
-              return rel;
-            }
-          }, rel.getRowType());
+      return prepare_(() -> rel, rel.getRowType());
     }
 
     private PreparedResult prepare_(Supplier<RelNode> fn,
@@ -1273,7 +1254,7 @@ public class CalcitePrepareImpl implements CalcitePrepare {
           parameterRowType,
           fieldOrigins,
           root.collation.getFieldCollations().isEmpty()
-              ? ImmutableList.<RelCollation>of()
+              ? ImmutableList.of()
               : ImmutableList.of(root.collation),
           root.rel,
           mapTableModOp(isDml, root.kind),
@@ -1296,7 +1277,7 @@ public class CalcitePrepareImpl implements CalcitePrepare {
       final List<Prepare.Materialization> materializations =
           context.config().materializationsEnabled()
               ? MaterializationService.instance().query(schema)
-              : ImmutableList.<Prepare.Materialization>of();
+              : ImmutableList.of();
       for (Prepare.Materialization materialization : materializations) {
         prepare.populateMaterializations(context, planner, materialization);
       }
@@ -1321,15 +1302,13 @@ public class CalcitePrepareImpl implements CalcitePrepare {
 
     public Bindable getBindable(final Meta.CursorFactory cursorFactory) {
       final String explanation = getCode();
-      return new Bindable() {
-        public Enumerable bind(DataContext dataContext) {
-          switch (cursorFactory.style) {
-          case ARRAY:
-            return Linq4j.singletonEnumerable(new String[] {explanation});
-          case OBJECT:
-          default:
-            return Linq4j.singletonEnumerable(explanation);
-          }
+      return dataContext -> {
+        switch (cursorFactory.style) {
+        case ARRAY:
+          return Linq4j.singletonEnumerable(new String[] {explanation});
+        case OBJECT:
+        default:
+          return Linq4j.singletonEnumerable(explanation);
         }
       };
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/LixToRelTranslator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/LixToRelTranslator.java b/core/src/main/java/org/apache/calcite/prepare/LixToRelTranslator.java
index 3a52ba5..460e2ca 100644
--- a/core/src/main/java/org/apache/calcite/prepare/LixToRelTranslator.java
+++ b/core/src/main/java/org/apache/calcite/prepare/LixToRelTranslator.java
@@ -102,7 +102,7 @@ class LixToRelTranslator implements RelOptTable.ToRelContext {
                 typeFactory.createJavaType(
                     Types.toClass(
                         Types.getElementType(call.targetExpression.getType()))),
-                ImmutableList.<String>of(),
+                ImmutableList.of(),
                 call.targetExpression));
 
       case SCHEMA_GET_TABLE:
@@ -110,7 +110,7 @@ class LixToRelTranslator implements RelOptTable.ToRelContext {
             RelOptTableImpl.create(null,
                 typeFactory.createJavaType((Class)
                     ((ConstantExpression) call.expressions.get(1)).value),
-                ImmutableList.<String>of(),
+                ImmutableList.of(),
                 call.targetExpression));
 
       default:

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/PlannerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/PlannerImpl.java b/core/src/main/java/org/apache/calcite/prepare/PlannerImpl.java
index e5f2ae0..cb27ea2 100644
--- a/core/src/main/java/org/apache/calcite/prepare/PlannerImpl.java
+++ b/core/src/main/java/org/apache/calcite/prepare/PlannerImpl.java
@@ -23,10 +23,7 @@ import org.apache.calcite.config.CalciteConnectionProperty;
 import org.apache.calcite.jdbc.CalciteSchema;
 import org.apache.calcite.plan.Context;
 import org.apache.calcite.plan.RelOptCluster;
-import org.apache.calcite.plan.RelOptLattice;
-import org.apache.calcite.plan.RelOptMaterialization;
 import org.apache.calcite.plan.RelOptPlanner;
-import org.apache.calcite.plan.RelOptSchema;
 import org.apache.calcite.plan.RelOptTable.ViewExpander;
 import org.apache.calcite.plan.RelTraitDef;
 import org.apache.calcite.plan.RelTraitSet;
@@ -144,15 +141,12 @@ public class PlannerImpl implements Planner {
     }
     ensure(State.STATE_1_RESET);
     Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Void>() {
-          public Void apply(RelOptCluster cluster, RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            Util.discard(rootSchema); // use our own defaultSchema
-            typeFactory = (JavaTypeFactory) cluster.getTypeFactory();
-            planner = cluster.getPlanner();
-            planner.setExecutor(executor);
-            return null;
-          }
+        (cluster, relOptSchema, rootSchema) -> {
+          Util.discard(rootSchema); // use our own defaultSchema
+          typeFactory = (JavaTypeFactory) cluster.getTypeFactory();
+          planner = cluster.getPlanner();
+          planner.setExecutor(executor);
+          return null;
         },
         config);
 
@@ -340,9 +334,8 @@ public class PlannerImpl implements Planner {
             rel.getCluster().getMetadataProvider(),
             rel.getCluster().getPlanner()));
     Program program = programs.get(ruleSetIndex);
-    return program.run(planner, rel, requiredOutputTraits,
-        ImmutableList.<RelOptMaterialization>of(),
-        ImmutableList.<RelOptLattice>of());
+    return program.run(planner, rel, requiredOutputTraits, ImmutableList.of(),
+        ImmutableList.of());
   }
 
   /** Stage of a statement in the query-preparation lifecycle. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/Prepare.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/Prepare.java b/core/src/main/java/org/apache/calcite/prepare/Prepare.java
index 95758e5..8d1a55b 100644
--- a/core/src/main/java/org/apache/calcite/prepare/Prepare.java
+++ b/core/src/main/java/org/apache/calcite/prepare/Prepare.java
@@ -69,7 +69,6 @@ import org.apache.calcite.util.TryThreadLocal;
 import org.apache.calcite.util.trace.CalciteTimingTracer;
 import org.apache.calcite.util.trace.CalciteTrace;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import org.slf4j.Logger;
@@ -78,6 +77,7 @@ import java.lang.reflect.Type;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Abstract base for classes that implement
@@ -532,7 +532,7 @@ public abstract class Prepare {
 
     public List<List<String>> getFieldOrigins() {
       return Collections.singletonList(
-          Collections.<String>nCopies(4, null));
+          Collections.nCopies(4, null));
     }
   }
 
@@ -599,11 +599,11 @@ public abstract class Prepare {
         RelNode rootRel,
         LogicalTableModify.Operation tableModOp,
         boolean isDml) {
-      this.rowType = Preconditions.checkNotNull(rowType);
-      this.parameterRowType = Preconditions.checkNotNull(parameterRowType);
-      this.fieldOrigins = Preconditions.checkNotNull(fieldOrigins);
+      this.rowType = Objects.requireNonNull(rowType);
+      this.parameterRowType = Objects.requireNonNull(parameterRowType);
+      this.fieldOrigins = Objects.requireNonNull(fieldOrigins);
       this.collations = ImmutableList.copyOf(collations);
-      this.rootRel = Preconditions.checkNotNull(rootRel);
+      this.rootRel = Objects.requireNonNull(rootRel);
       this.tableModOp = tableModOp;
       this.isDml = isDml;
     }


[19/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/prepare/RelOptTableImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/prepare/RelOptTableImpl.java b/core/src/main/java/org/apache/calcite/prepare/RelOptTableImpl.java
index 81d84ad..aeeca3d 100644
--- a/core/src/main/java/org/apache/calcite/prepare/RelOptTableImpl.java
+++ b/core/src/main/java/org/apache/calcite/prepare/RelOptTableImpl.java
@@ -60,15 +60,14 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.AbstractList;
 import java.util.Collection;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
+import java.util.function.Function;
 
 /**
  * Implementation of {@link org.apache.calcite.plan.RelOptTable}.
@@ -97,7 +96,7 @@ public class RelOptTableImpl extends Prepare.AbstractPreparingTable {
       Function<Class, Expression> expressionFunction,
       Double rowCount) {
     this.schema = schema;
-    this.rowType = Preconditions.checkNotNull(rowType);
+    this.rowType = Objects.requireNonNull(rowType);
     this.names = ImmutableList.copyOf(names);
     this.table = table; // may be null
     this.expressionFunction = expressionFunction; // may be null
@@ -109,29 +108,23 @@ public class RelOptTableImpl extends Prepare.AbstractPreparingTable {
       RelDataType rowType,
       List<String> names,
       Expression expression) {
-    //noinspection unchecked
-    final Function<Class, Expression> expressionFunction =
-        (Function) Functions.constant(expression);
     return new RelOptTableImpl(schema, rowType, names, null,
-        expressionFunction, null);
+        c -> expression, null);
   }
 
   public static RelOptTableImpl create(RelOptSchema schema, RelDataType rowType,
       Table table, Path path) {
     final SchemaPlus schemaPlus = MySchemaPlus.create(path);
-    Function<Class, Expression> expressionFunction =
-        getClassExpressionFunction(schemaPlus, Util.last(path).left, table);
     return new RelOptTableImpl(schema, rowType, Pair.left(path), table,
-        expressionFunction, table.getStatistic().getRowCount());
+        getClassExpressionFunction(schemaPlus, Util.last(path).left, table),
+        table.getStatistic().getRowCount());
   }
 
   public static RelOptTableImpl create(RelOptSchema schema, RelDataType rowType,
       final CalciteSchema.TableEntry tableEntry, Double rowCount) {
     final Table table = tableEntry.getTable();
-    Function<Class, Expression> expressionFunction =
-        getClassExpressionFunction(tableEntry, table);
     return new RelOptTableImpl(schema, rowType, tableEntry.path(),
-        table, expressionFunction, rowCount);
+        table, getClassExpressionFunction(tableEntry, table), rowCount);
   }
 
   /**
@@ -152,28 +145,18 @@ public class RelOptTableImpl extends Prepare.AbstractPreparingTable {
       final SchemaPlus schema, final String tableName, final Table table) {
     if (table instanceof QueryableTable) {
       final QueryableTable queryableTable = (QueryableTable) table;
-      return new Function<Class, Expression>() {
-        public Expression apply(Class clazz) {
-          return queryableTable.getExpression(schema, tableName, clazz);
-        }
-      };
+      return clazz -> queryableTable.getExpression(schema, tableName, clazz);
     } else if (table instanceof ScannableTable
         || table instanceof FilterableTable
         || table instanceof ProjectableFilterableTable) {
-      return new Function<Class, Expression>() {
-        public Expression apply(Class clazz) {
-          return Schemas.tableExpression(schema, Object[].class, tableName,
-              table.getClass());
-        }
-      };
+      return clazz -> Schemas.tableExpression(schema, Object[].class, tableName,
+          table.getClass());
     } else if (table instanceof StreamableTable) {
       return getClassExpressionFunction(schema, tableName,
           ((StreamableTable) table).stream());
     } else {
-      return new Function<Class, Expression>() {
-        public Expression apply(Class input) {
-          throw new UnsupportedOperationException();
-        }
+      return input -> {
+        throw new UnsupportedOperationException();
       };
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/profile/ProfilerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/profile/ProfilerImpl.java b/core/src/main/java/org/apache/calcite/profile/ProfilerImpl.java
index 139f13d..2dd8af9 100644
--- a/core/src/main/java/org/apache/calcite/profile/ProfilerImpl.java
+++ b/core/src/main/java/org/apache/calcite/profile/ProfilerImpl.java
@@ -22,16 +22,12 @@ import org.apache.calcite.materialize.Lattice;
 import org.apache.calcite.prepare.CalcitePrepareImpl;
 import org.apache.calcite.rel.metadata.NullSentinel;
 import org.apache.calcite.runtime.FlatLists;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.PartiallyOrderedSet;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSortedSet;
 import com.google.common.collect.Iterables;
@@ -46,7 +42,6 @@ import java.util.Arrays;
 import java.util.BitSet;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.Deque;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -57,6 +52,7 @@ import java.util.Queue;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
+import java.util.function.Predicate;
 
 import static org.apache.calcite.profile.ProfilerImpl.CompositeCollector.OF;
 
@@ -119,20 +115,17 @@ public class ProfilerImpl implements Profiler {
      * not yet been computed. We may add some of those successors to
      * {@link #spaceQueue}. */
     final Queue<Space> doneQueue =
-        new PriorityQueue<>(100,
-          new Comparator<Space>() {
-            public int compare(Space s0, Space s1) {
-              // The space with 0 columns is more interesting than
-              // any space with 1 column, and so forth.
-              // For spaces with 2 or more columns we compare "surprise":
-              // how many fewer values did it have than expected?
-              int c = Integer.compare(s0.columns.size(), s1.columns.size());
-              if (c == 0) {
-                c = Double.compare(s0.surprise(), s1.surprise());
-              }
-              return c;
-            }
-          });
+        new PriorityQueue<>(100, (s0, s1) -> {
+          // The space with 0 columns is more interesting than
+          // any space with 1 column, and so forth.
+          // For spaces with 2 or more columns we compare "surprise":
+          // how many fewer values did it have than expected?
+          int c = Integer.compare(s0.columns.size(), s1.columns.size());
+          if (c == 0) {
+            c = Double.compare(s0.surprise(), s1.surprise());
+          }
+          return c;
+        });
     final SurpriseQueue surprises;
 
     /** Combinations of columns that we will compute next pass. */
@@ -143,20 +136,11 @@ public class ProfilerImpl implements Profiler {
      * Ensures that we do not calculate the same combination more than once,
      * even though we generate a column set from multiple parents. */
     final Set<ImmutableBitSet> resultSet = new HashSet<>();
-    final PartiallyOrderedSet<Space> results = new PartiallyOrderedSet<>(
-        new PartiallyOrderedSet.Ordering<Space>() {
-          public boolean lessThan(Space e1, Space e2) {
-            return e2.columnOrdinals.contains(e1.columnOrdinals);
-          }
-        });
+    final PartiallyOrderedSet<Space> results =
+        new PartiallyOrderedSet<>((e1, e2) ->
+            e2.columnOrdinals.contains(e1.columnOrdinals));
     private final List<ImmutableBitSet> keyOrdinalLists =
         new ArrayList<>();
-    final Function<Integer, Column> get =
-        new Function<Integer, Column>() {
-          public Column apply(Integer input) {
-            return columns.get(input);
-          }
-        };
     private int rowCount;
 
     /**
@@ -262,7 +246,7 @@ public class ProfilerImpl implements Profiler {
                     || doneSpace.columnOrdinals.cardinality() == 0
                     || !containsKey(
                         doneSpace.columnOrdinals.set(column.ordinal))
-                    && predicate.apply(Pair.of(doneSpace, column))) {
+                    && predicate.test(Pair.of(doneSpace, column))) {
                   final ImmutableBitSet nextOrdinals =
                       doneSpace.columnOrdinals.set(column.ordinal);
                   if (resultSet.add(nextOrdinals)) {
@@ -448,7 +432,8 @@ public class ProfilerImpl implements Profiler {
 
 
     private ImmutableSortedSet<Column> toColumns(Iterable<Integer> ordinals) {
-      return ImmutableSortedSet.copyOf(Iterables.transform(ordinals, get));
+      return ImmutableSortedSet.copyOf(
+          Iterables.transform(ordinals, columns::get));
     }
   }
 
@@ -500,7 +485,7 @@ public class ProfilerImpl implements Profiler {
   /** Builds a {@link org.apache.calcite.profile.ProfilerImpl}. */
   public static class Builder {
     int combinationsPerPass = 100;
-    Predicate<Pair<Space, Column>> predicate = Predicates.alwaysTrue();
+    Predicate<Pair<Space, Column>> predicate = p -> true;
 
     public ProfilerImpl build() {
       return new ProfilerImpl(combinationsPerPass, 200, predicate);
@@ -513,11 +498,9 @@ public class ProfilerImpl implements Profiler {
 
     public Builder withMinimumSurprise(double v) {
       predicate =
-          new PredicateImpl<Pair<Space, Column>>() {
-            public boolean test(Pair<Space, Column> spaceColumnPair) {
-              final Space space = spaceColumnPair.left;
-              return false;
-            }
+          spaceColumnPair -> {
+            final Space space = spaceColumnPair.left;
+            return false;
           };
       return this;
     }
@@ -624,7 +607,7 @@ public class ProfilerImpl implements Profiler {
             new ArrayList<>(
                 Collections.nCopies(columnOrdinals[columnOrdinals.length - 1]
                         + 1,
-                    (Comparable) null));
+                    null));
         for (FlatLists.ComparableList value : this.values) {
           for (int i = 0; i < value.size(); i++) {
             Comparable c = (Comparable) value.get(i);
@@ -759,7 +742,7 @@ public class ProfilerImpl implements Profiler {
     int count = 0;
     final Deque<Double> deque = new ArrayDeque<>();
     final PriorityQueue<Double> priorityQueue =
-        new PriorityQueue<>(11, Ordering.<Double>natural());
+        new PriorityQueue<>(11, Ordering.natural());
 
     SurpriseQueue(int warmUpCount, int size) {
       this.warmUpCount = warmUpCount;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/profile/SimpleProfiler.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/profile/SimpleProfiler.java b/core/src/main/java/org/apache/calcite/profile/SimpleProfiler.java
index c9b00d0..f1c7ee4 100644
--- a/core/src/main/java/org/apache/calcite/profile/SimpleProfiler.java
+++ b/core/src/main/java/org/apache/calcite/profile/SimpleProfiler.java
@@ -24,7 +24,6 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.PartiallyOrderedSet;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableSortedSet;
 import com.google.common.collect.Iterables;
 
@@ -45,12 +44,6 @@ import javax.annotation.Nonnull;
  * Basic implementation of {@link Profiler}.
  */
 public class SimpleProfiler implements Profiler {
-  private static final Function<List<Comparable>, Comparable> ONLY =
-      new Function<List<Comparable>, Comparable>() {
-        public Comparable apply(List<Comparable> input) {
-          return Iterables.getOnlyElement(input);
-        }
-      };
 
   public Profile profile(Iterable<List<Comparable>> rows,
       final List<Column> columns, Collection<ImmutableBitSet> initialGroups) {
@@ -97,23 +90,13 @@ public class SimpleProfiler implements Profiler {
     final List<Space> singletonSpaces;
     final List<Statistic> statistics = new ArrayList<>();
     final PartiallyOrderedSet.Ordering<Space> ordering =
-        new PartiallyOrderedSet.Ordering<Space>() {
-          public boolean lessThan(Space e1, Space e2) {
-            return e2.columnOrdinals.contains(e1.columnOrdinals);
-          }
-        };
+        (e1, e2) -> e2.columnOrdinals.contains(e1.columnOrdinals);
     final PartiallyOrderedSet<Space> results =
         new PartiallyOrderedSet<>(ordering);
     final PartiallyOrderedSet<Space> keyResults =
         new PartiallyOrderedSet<>(ordering);
     private final List<ImmutableBitSet> keyOrdinalLists =
         new ArrayList<>();
-    final Function<Integer, Column> get =
-        new Function<Integer, Column>() {
-          public Column apply(Integer input) {
-            return columns.get(input);
-          }
-        };
 
     Run(final List<Column> columns) {
       for (Ord<Column> column : Ord.zip(columns)) {
@@ -123,7 +106,7 @@ public class SimpleProfiler implements Profiler {
       }
       this.columns = columns;
       this.singletonSpaces =
-          new ArrayList<>(Collections.nCopies(columns.size(), (Space) null));
+          new ArrayList<>(Collections.nCopies(columns.size(), null));
       for (ImmutableBitSet ordinals
           : ImmutableBitSet.range(columns.size()).powerSet()) {
         final Space space = new Space(ordinals, toColumns(ordinals));
@@ -217,7 +200,7 @@ public class SimpleProfiler implements Profiler {
         if (space.columns.size() == 1) {
           nullCount = space.nullCount;
           valueSet = ImmutableSortedSet.copyOf(
-              Iterables.transform(space.values, ONLY));
+              Iterables.transform(space.values, Iterables::getOnlyElement));
         } else {
           nullCount = -1;
           valueSet = null;
@@ -295,7 +278,8 @@ public class SimpleProfiler implements Profiler {
     }
 
     private ImmutableSortedSet<Column> toColumns(Iterable<Integer> ordinals) {
-      return ImmutableSortedSet.copyOf(Iterables.transform(ordinals, get));
+      return ImmutableSortedSet.copyOf(
+          Iterables.transform(ordinals, columns::get));
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/RelCollations.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/RelCollations.java b/core/src/main/java/org/apache/calcite/rel/RelCollations.java
index fecf514..c3b16c6 100644
--- a/core/src/main/java/org/apache/calcite/rel/RelCollations.java
+++ b/core/src/main/java/org/apache/calcite/rel/RelCollations.java
@@ -20,7 +20,6 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
@@ -40,7 +39,7 @@ public class RelCollations {
    */
   public static final RelCollation EMPTY =
       RelCollationTraitDef.INSTANCE.canonize(
-          new RelCollationImpl(ImmutableList.<RelFieldCollation>of()));
+          new RelCollationImpl(ImmutableList.of()));
 
   /**
    * A collation that cannot be replicated by applying a sort. The only
@@ -131,12 +130,7 @@ public class RelCollations {
   /** Returns the indexes of the fields in a list of field collations. */
   public static List<Integer> ordinals(
       List<RelFieldCollation> fieldCollations) {
-    return Lists.transform(fieldCollations,
-        new Function<RelFieldCollation, Integer>() {
-          public Integer apply(RelFieldCollation input) {
-            return input.getFieldIndex();
-          }
-        });
+    return Lists.transform(fieldCollations, RelFieldCollation::getFieldIndex);
   }
 
   /** Returns whether a collation indicates that the collection is sorted on

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/RelDistributions.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/RelDistributions.java b/core/src/main/java/org/apache/calcite/rel/RelDistributions.java
index 3c5dc4a..9da83fe 100644
--- a/core/src/main/java/org/apache/calcite/rel/RelDistributions.java
+++ b/core/src/main/java/org/apache/calcite/rel/RelDistributions.java
@@ -24,7 +24,6 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Ordering;
 
 import java.util.Collection;
@@ -89,7 +88,7 @@ public class RelDistributions {
     private final ImmutableIntList keys;
 
     private RelDistributionImpl(Type type, ImmutableIntList keys) {
-      this.type = Preconditions.checkNotNull(type);
+      this.type = Objects.requireNonNull(type);
       this.keys = ImmutableIntList.copyOf(keys);
       assert type != Type.HASH_DISTRIBUTED
           || keys.size() < 2

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/RelFieldCollation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/RelFieldCollation.java b/core/src/main/java/org/apache/calcite/rel/RelFieldCollation.java
index 660b3cd..64f3484 100644
--- a/core/src/main/java/org/apache/calcite/rel/RelFieldCollation.java
+++ b/core/src/main/java/org/apache/calcite/rel/RelFieldCollation.java
@@ -18,8 +18,6 @@ package org.apache.calcite.rel;
 
 import org.apache.calcite.sql.validate.SqlMonotonicity;
 
-import com.google.common.base.Preconditions;
-
 import java.util.Objects;
 
 /**
@@ -209,8 +207,8 @@ public class RelFieldCollation {
       Direction direction,
       NullDirection nullDirection) {
     this.fieldIndex = fieldIndex;
-    this.direction = Preconditions.checkNotNull(direction);
-    this.nullDirection = Preconditions.checkNotNull(nullDirection);
+    this.direction = Objects.requireNonNull(direction);
+    this.nullDirection = Objects.requireNonNull(nullDirection);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/RelRoot.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/RelRoot.java b/core/src/main/java/org/apache/calcite/rel/RelRoot.java
index a2fa71a..c744492 100644
--- a/core/src/main/java/org/apache/calcite/rel/RelRoot.java
+++ b/core/src/main/java/org/apache/calcite/rel/RelRoot.java
@@ -25,11 +25,11 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Root of a tree of {@link RelNode}.
@@ -92,7 +92,7 @@ public class RelRoot {
     this.validatedRowType = validatedRowType;
     this.kind = kind;
     this.fields = ImmutableList.copyOf(fields);
-    this.collation = Preconditions.checkNotNull(collation);
+    this.collation = Objects.requireNonNull(collation);
   }
 
   /** Creates a simple RelRoot. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/convert/ConverterRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/convert/ConverterRule.java b/core/src/main/java/org/apache/calcite/rel/convert/ConverterRule.java
index 149ea1e..84094fc 100644
--- a/core/src/main/java/org/apache/calcite/rel/convert/ConverterRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/convert/ConverterRule.java
@@ -25,9 +25,8 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
+import java.util.Objects;
+import java.util.function.Predicate;
 
 /**
  * Abstract base class for a rule which converts from one calling convention to
@@ -51,14 +50,15 @@ public abstract class ConverterRule extends RelOptRule {
    */
   public ConverterRule(Class<? extends RelNode> clazz, RelTrait in,
       RelTrait out, String description) {
-    this(clazz, Predicates.<RelNode>alwaysTrue(), in, out,
+    this(clazz, (Predicate<RelNode>) r -> true, in, out,
         RelFactories.LOGICAL_BUILDER, description);
   }
 
+  @SuppressWarnings("Guava")
   @Deprecated // to be removed before 2.0
   public <R extends RelNode> ConverterRule(Class<R> clazz,
-      Predicate<? super R> predicate, RelTrait in, RelTrait out,
-      String description) {
+      com.google.common.base.Predicate<? super R> predicate,
+      RelTrait in, RelTrait out, String description) {
     this(clazz, predicate, in, out, RelFactories.LOGICAL_BUILDER, description);
   }
 
@@ -80,13 +80,22 @@ public abstract class ConverterRule extends RelOptRule {
         description == null
             ? "ConverterRule<in=" + in + ",out=" + out + ">"
             : description);
-    this.inTrait = Preconditions.checkNotNull(in);
-    this.outTrait = Preconditions.checkNotNull(out);
+    this.inTrait = Objects.requireNonNull(in);
+    this.outTrait = Objects.requireNonNull(out);
 
     // Source and target traits must have same type
     assert in.getTraitDef() == out.getTraitDef();
   }
 
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public <R extends RelNode> ConverterRule(Class<R> clazz,
+      com.google.common.base.Predicate<? super R> predicate, RelTrait in,
+      RelTrait out, RelBuilderFactory relBuilderFactory, String description) {
+    this(clazz, (Predicate<? super R>) predicate::apply, in, out,
+        relBuilderFactory, description);
+  }
+
   //~ Methods ----------------------------------------------------------------
 
   public Convention getOutConvention() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Aggregate.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Aggregate.java b/core/src/main/java/org/apache/calcite/rel/core/Aggregate.java
index 93f9948..5d699ea 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Aggregate.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Aggregate.java
@@ -31,7 +31,6 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.runtime.CalciteException;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.runtime.Resources;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlOperatorBinding;
@@ -45,12 +44,12 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
 import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
 import com.google.common.math.IntMath;
 
+import java.util.HashSet;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -73,26 +72,24 @@ public abstract class Aggregate extends SingleRel {
   /**
    * @see org.apache.calcite.util.Bug#CALCITE_461_FIXED
    */
-  public static final Predicate<Aggregate> IS_SIMPLE =
-      new PredicateImpl<Aggregate>() {
-        public boolean test(Aggregate input) {
-          return input.getGroupType() == Group.SIMPLE;
-        }
-      };
+  public static boolean isSimple(Aggregate aggregate) {
+    return aggregate.getGroupType() == Group.SIMPLE;
+  }
 
-  public static final Predicate<Aggregate> NO_INDICATOR =
-      new PredicateImpl<Aggregate>() {
-        public boolean test(Aggregate input) {
-          return !input.indicator;
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be converted to Java Predicate before 2.0
+  public static final com.google.common.base.Predicate<Aggregate> IS_SIMPLE =
+      Aggregate::isSimple;
 
-  public static final Predicate<Aggregate> IS_NOT_GRAND_TOTAL =
-      new PredicateImpl<Aggregate>() {
-        public boolean test(Aggregate input) {
-          return input.getGroupCount() > 0;
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be converted to Java Predicate before 2.0
+  public static final com.google.common.base.Predicate<Aggregate> NO_INDICATOR =
+      Aggregate::noIndicator;
+
+  @SuppressWarnings("Guava")
+  @Deprecated // to be converted to Java Predicate before 2.0
+  public static final com.google.common.base.Predicate<Aggregate>
+      IS_NOT_GRAND_TOTAL = Aggregate::isNotGrandTotal;
 
   //~ Instance fields --------------------------------------------------------
 
@@ -146,7 +143,7 @@ public abstract class Aggregate extends SingleRel {
     super(cluster, traits, child);
     this.indicator = indicator; // true is allowed, but discouraged
     this.aggCalls = ImmutableList.copyOf(aggCalls);
-    this.groupSet = Preconditions.checkNotNull(groupSet);
+    this.groupSet = Objects.requireNonNull(groupSet);
     if (groupSets == null) {
       this.groupSets = ImmutableList.of(groupSet);
     } else {
@@ -165,6 +162,14 @@ public abstract class Aggregate extends SingleRel {
     }
   }
 
+  public static boolean isNotGrandTotal(Aggregate aggregate) {
+    return aggregate.getGroupCount() > 0;
+  }
+
+  public static boolean noIndicator(Aggregate aggregate) {
+    return !aggregate.indicator;
+  }
+
   private boolean isPredicate(RelNode input, int index) {
     final RelDataType type =
         input.getRowType().getFieldList().get(index).getType();
@@ -352,7 +357,7 @@ public abstract class Aggregate extends SingleRel {
     assert groupList.size() == groupSet.cardinality();
     final RelDataTypeFactory.Builder builder = typeFactory.builder();
     final List<RelDataTypeField> fieldList = inputRowType.getFieldList();
-    final Set<String> containedNames = Sets.newHashSet();
+    final Set<String> containedNames = new HashSet<>();
     for (int groupKey : groupList) {
       final RelDataTypeField field = fieldList.get(groupKey);
       containedNames.add(field.getName());

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java b/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java
index f7194f4..5df2a51 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/AggregateCall.java
@@ -24,7 +24,6 @@ import org.apache.calcite.sql.type.SqlTypeUtil;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
@@ -89,9 +88,9 @@ public class AggregateCall {
       int filterArg,
       RelDataType type,
       String name) {
-    this.type = Preconditions.checkNotNull(type);
+    this.type = Objects.requireNonNull(type);
     this.name = name;
-    this.aggFunction = Preconditions.checkNotNull(aggFunction);
+    this.aggFunction = Objects.requireNonNull(aggFunction);
     this.argList = ImmutableList.copyOf(argList);
     this.filterArg = filterArg;
     this.distinct = distinct;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Correlate.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Correlate.java b/core/src/main/java/org/apache/calcite/rel/core/Correlate.java
index 6f218b1..ee7e607 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Correlate.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Correlate.java
@@ -27,7 +27,6 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.RelWriter;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.sql.SemiJoinType;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.ImmutableBitSet;
@@ -144,7 +143,7 @@ public abstract class Correlate extends BiRel {
       return SqlValidatorUtil.deriveJoinRowType(left.getRowType(),
           right.getRowType(), joinType.toJoinType(),
           getCluster().getTypeFactory(), null,
-          ImmutableList.<RelDataTypeField>of());
+          ImmutableList.of());
     case ANTI:
     case SEMI:
       return left.getRowType();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/EquiJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/EquiJoin.java b/core/src/main/java/org/apache/calcite/rel/core/EquiJoin.java
index a45a854..ca5b59d 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/EquiJoin.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/EquiJoin.java
@@ -22,8 +22,7 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.util.ImmutableIntList;
 
-import com.google.common.base.Preconditions;
-
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -39,8 +38,8 @@ public abstract class EquiJoin extends Join {
       ImmutableIntList rightKeys, Set<CorrelationId> variablesSet,
       JoinRelType joinType) {
     super(cluster, traits, left, right, condition, variablesSet, joinType);
-    this.leftKeys = Preconditions.checkNotNull(leftKeys);
-    this.rightKeys = Preconditions.checkNotNull(rightKeys);
+    this.leftKeys = Objects.requireNonNull(leftKeys);
+    this.rightKeys = Objects.requireNonNull(rightKeys);
   }
 
   @Deprecated // to be removed before 2.0

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Exchange.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Exchange.java b/core/src/main/java/org/apache/calcite/rel/core/Exchange.java
index 060fa1c..221740b 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Exchange.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Exchange.java
@@ -30,9 +30,8 @@ import org.apache.calcite.rel.SingleRel;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Relational expression that imposes a particular distribution on its input
@@ -58,7 +57,7 @@ public abstract class Exchange extends SingleRel {
   protected Exchange(RelOptCluster cluster, RelTraitSet traitSet, RelNode input,
       RelDistribution distribution) {
     super(cluster, traitSet, input);
-    this.distribution = Preconditions.checkNotNull(distribution);
+    this.distribution = Objects.requireNonNull(distribution);
 
     assert traitSet.containsIfApplicable(distribution)
         : "traits=" + traitSet + ", distribution" + distribution;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Join.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Join.java b/core/src/main/java/org/apache/calcite/rel/core/Join.java
index a9e0441..d20d55e 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Join.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Join.java
@@ -36,12 +36,12 @@ import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -101,9 +101,9 @@ public abstract class Join extends BiRel {
       Set<CorrelationId> variablesSet,
       JoinRelType joinType) {
     super(cluster, traitSet, left, right);
-    this.condition = Preconditions.checkNotNull(condition);
+    this.condition = Objects.requireNonNull(condition);
     this.variablesSet = ImmutableSet.copyOf(variablesSet);
-    this.joinType = Preconditions.checkNotNull(joinType);
+    this.joinType = Objects.requireNonNull(joinType);
   }
 
   @Deprecated // to be removed before 2.0

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/JoinInfo.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/JoinInfo.java b/core/src/main/java/org/apache/calcite/rel/core/JoinInfo.java
index e044913..973734c 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/JoinInfo.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/JoinInfo.java
@@ -25,10 +25,9 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.mapping.IntPair;
 
-import com.google.common.base.Preconditions;
-
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /** An analyzed join condition.
  *
@@ -47,8 +46,8 @@ public abstract class JoinInfo {
 
   /** Creates a JoinInfo. */
   protected JoinInfo(ImmutableIntList leftKeys, ImmutableIntList rightKeys) {
-    this.leftKeys = Preconditions.checkNotNull(leftKeys);
-    this.rightKeys = Preconditions.checkNotNull(rightKeys);
+    this.leftKeys = Objects.requireNonNull(leftKeys);
+    this.rightKeys = Objects.requireNonNull(rightKeys);
     assert leftKeys.size() == rightKeys.size();
   }
 
@@ -126,7 +125,7 @@ public abstract class JoinInfo {
     protected NonEquiJoinInfo(ImmutableIntList leftKeys,
         ImmutableIntList rightKeys, RexNode remaining) {
       super(leftKeys, rightKeys);
-      this.remaining = Preconditions.checkNotNull(remaining);
+      this.remaining = Objects.requireNonNull(remaining);
       assert !remaining.isAlwaysTrue();
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Match.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Match.java b/core/src/main/java/org/apache/calcite/rel/core/Match.java
index 2ebafec..7d47bec 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Match.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Match.java
@@ -42,6 +42,7 @@ import com.google.common.collect.ImmutableSortedSet;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeMap;
@@ -98,18 +99,18 @@ public abstract class Match extends SingleRel {
       boolean allRows, List<RexNode> partitionKeys, RelCollation orderKeys,
       RexNode interval) {
     super(cluster, traitSet, input);
-    this.rowType = Preconditions.checkNotNull(rowType);
-    this.pattern = Preconditions.checkNotNull(pattern);
+    this.rowType = Objects.requireNonNull(rowType);
+    this.pattern = Objects.requireNonNull(pattern);
     Preconditions.checkArgument(patternDefinitions.size() > 0);
     this.strictStart = strictStart;
     this.strictEnd = strictEnd;
     this.patternDefinitions = ImmutableMap.copyOf(patternDefinitions);
     this.measures = ImmutableMap.copyOf(measures);
-    this.after = Preconditions.checkNotNull(after);
+    this.after = Objects.requireNonNull(after);
     this.subsets = copyMap(subsets);
     this.allRows = allRows;
     this.partitionKeys = ImmutableList.copyOf(partitionKeys);
-    this.orderKeys = Preconditions.checkNotNull(orderKeys);
+    this.orderKeys = Objects.requireNonNull(orderKeys);
     this.interval = interval;
 
     final AggregateFinder aggregateFinder = new AggregateFinder();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Project.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Project.java b/core/src/main/java/org/apache/calcite/rel/core/Project.java
index 3119959..b484bf3 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Project.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Project.java
@@ -41,7 +41,6 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.MappingType;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
@@ -194,13 +193,7 @@ public abstract class Project extends SingleRel {
       return litmus.fail("field names not distinct: {}", rowType);
     }
     //CHECKSTYLE: IGNORE 1
-    if (false && !Util.isDistinct(
-        Lists.transform(exps,
-            new Function<RexNode, Object>() {
-              public Object apply(RexNode a0) {
-                return a0.toString();
-              }
-            }))) {
+    if (false && !Util.isDistinct(Lists.transform(exps, RexNode::toString))) {
       // Projecting the same expression twice is usually a bad idea,
       // because it may create expressions downstream which are equivalent
       // but which look different. We can't ban duplicate projects,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/RelFactories.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/RelFactories.java b/core/src/main/java/org/apache/calcite/rel/core/RelFactories.java
index b4ebbca..5870f34 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/RelFactories.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/RelFactories.java
@@ -35,7 +35,6 @@ import org.apache.calcite.rel.logical.LogicalTableScan;
 import org.apache.calcite.rel.logical.LogicalUnion;
 import org.apache.calcite.rel.logical.LogicalValues;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.sql.SemiJoinType;
@@ -272,7 +271,7 @@ public class RelFactories {
         RexNode condition, Set<CorrelationId> variablesSet,
         JoinRelType joinType, boolean semiJoinDone) {
       return LogicalJoin.create(left, right, condition, variablesSet, joinType,
-          semiJoinDone, ImmutableList.<RelDataTypeField>of());
+          semiJoinDone, ImmutableList.of());
     }
 
     public RelNode createJoin(RelNode left, RelNode right, RexNode condition,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/SemiJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/SemiJoin.java b/core/src/main/java/org/apache/calcite/rel/core/SemiJoin.java
index 433ee5d..774424f 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/SemiJoin.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/SemiJoin.java
@@ -25,7 +25,6 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.ImmutableIntList;
@@ -73,7 +72,7 @@ public class SemiJoin extends EquiJoin {
         condition,
         leftKeys,
         rightKeys,
-        ImmutableSet.<CorrelationId>of(),
+        ImmutableSet.of(),
         JoinRelType.INNER);
   }
 
@@ -121,7 +120,7 @@ public class SemiJoin extends EquiJoin {
         JoinRelType.INNER,
         getCluster().getTypeFactory(),
         null,
-        ImmutableList.<RelDataTypeField>of());
+        ImmutableList.of());
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/SetOp.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/SetOp.java b/core/src/main/java/org/apache/calcite/rel/core/SetOp.java
index 930f23f..eef57c3 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/SetOp.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/SetOp.java
@@ -28,7 +28,6 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
@@ -102,12 +101,8 @@ public abstract class SetOp extends AbstractRelNode {
   }
 
   @Override protected RelDataType deriveRowType() {
-    final List<RelDataType> inputRowTypes = Lists.transform(inputs,
-        new Function<RelNode, RelDataType>() {
-          public RelDataType apply(RelNode input) {
-            return input.getRowType();
-          }
-        });
+    final List<RelDataType> inputRowTypes =
+        Lists.transform(inputs, RelNode::getRowType);
     final RelDataType rowType =
         getCluster().getTypeFactory().leastRestrictive(inputRowTypes);
     if (rowType == null) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/SortExchange.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/SortExchange.java b/core/src/main/java/org/apache/calcite/rel/core/SortExchange.java
index b6c277a..1854674 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/SortExchange.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/SortExchange.java
@@ -26,7 +26,7 @@ import org.apache.calcite.rel.RelInput;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.RelWriter;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /**
  * Relational expression that performs {@link Exchange} and {@link Sort}
@@ -57,7 +57,7 @@ public abstract class SortExchange extends Exchange {
   protected SortExchange(RelOptCluster cluster, RelTraitSet traitSet,
       RelNode input, RelDistribution distribution, RelCollation collation) {
     super(cluster, traitSet, input, distribution);
-    this.collation = Preconditions.checkNotNull(collation);
+    this.collation = Objects.requireNonNull(collation);
 
     assert traitSet.containsIfApplicable(collation)
         : "traits=" + traitSet + ", collation=" + collation;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/TableFunctionScan.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/TableFunctionScan.java b/core/src/main/java/org/apache/calcite/rel/core/TableFunctionScan.java
index 7482c39..cdedbd0 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/TableFunctionScan.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/TableFunctionScan.java
@@ -95,7 +95,7 @@ public abstract class TableFunctionScan extends AbstractRelNode {
         input.getCluster(), input.getTraitSet(), input.getInputs(),
         input.getExpression("invocation"), (Type) input.get("elementType"),
         input.getRowType("rowType"),
-        ImmutableSet.<RelColumnMapping>of());
+        ImmutableSet.of());
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/TableModify.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/TableModify.java b/core/src/main/java/org/apache/calcite/rel/core/TableModify.java
index 9dfed22..1fc56e6 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/TableModify.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/TableModify.java
@@ -36,6 +36,7 @@ import org.apache.calcite.sql.type.SqlTypeUtil;
 import com.google.common.base.Preconditions;
 
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Relational expression that modifies a table.
@@ -116,8 +117,8 @@ public abstract class TableModify extends SingleRel {
     this.updateColumnList = updateColumnList;
     this.sourceExpressionList = sourceExpressionList;
     if (operation == Operation.UPDATE) {
-      Preconditions.checkNotNull(updateColumnList);
-      Preconditions.checkNotNull(sourceExpressionList);
+      Objects.requireNonNull(updateColumnList);
+      Objects.requireNonNull(sourceExpressionList);
       Preconditions.checkArgument(sourceExpressionList.size()
           == updateColumnList.size());
     } else {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/core/Values.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/core/Values.java b/core/src/main/java/org/apache/calcite/rel/core/Values.java
index 30d366d..91c6323 100644
--- a/core/src/main/java/org/apache/calcite/rel/core/Values.java
+++ b/core/src/main/java/org/apache/calcite/rel/core/Values.java
@@ -28,63 +28,33 @@ import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexLiteral;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SqlExplainLevel;
 import org.apache.calcite.sql.type.SqlTypeUtil;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
 import java.util.List;
+import java.util.function.Predicate;
 
 /**
  * Relational expression whose value is a sequence of zero or more literal row
  * values.
  */
 public abstract class Values extends AbstractRelNode {
-  /**
-   * Lambda that helps render tuples as strings.
-   */
-  private static final Function<ImmutableList<RexLiteral>, Object> F =
-      new Function<ImmutableList<RexLiteral>, Object>() {
-        public Object apply(ImmutableList<RexLiteral> tuple) {
-          String s = tuple.toString();
-          assert s.startsWith("[");
-          assert s.endsWith("]");
-          return "{ " + s.substring(1, s.length() - 1) + " }";
-        }
-      };
 
-  /** Predicate, to be used when defining an operand of a {@link RelOptRule},
-   * that returns true if a Values contains zero tuples.
-   *
-   * <p>This is the conventional way to represent an empty relational
-   * expression. There are several rules that recognize empty relational
-   * expressions and prune away that section of the tree.
-   */
-  public static final Predicate<? super Values> IS_EMPTY =
-      new PredicateImpl<Values>() {
-        public boolean test(Values values) {
-          return values.getTuples().isEmpty();
-        }
-      };
+  public static final Predicate<? super Values> IS_EMPTY_J = Values::isEmpty;
 
-  /** Predicate, to be used when defining an operand of a {@link RelOptRule},
-   * that returns true if a Values contains one or more tuples.
-   *
-   * <p>This is the conventional way to represent an empty relational
-   * expression. There are several rules that recognize empty relational
-   * expressions and prune away that section of the tree.
-   */
-  public static final Predicate<? super Values> IS_NOT_EMPTY =
-      new PredicateImpl<Values>() {
-        public boolean test(Values values) {
-          return !values.getTuples().isEmpty();
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<? super Values>
+      IS_EMPTY = Values::isEmpty;
+
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<? super Values>
+      IS_NOT_EMPTY = Values::isNotEmpty;
 
   //~ Instance fields --------------------------------------------------------
 
@@ -124,8 +94,40 @@ public abstract class Values extends AbstractRelNode {
         input.getTuples("tuples"), input.getTraitSet());
   }
 
+  /**
+   * Helps render tuples as strings.
+   */
+  private static Object apply(ImmutableList<RexLiteral> tuple) {
+    String s = tuple.toString();
+    assert s.startsWith("[");
+    assert s.endsWith("]");
+    return "{ " + s.substring(1, s.length() - 1) + " }";
+  }
+
   //~ Methods ----------------------------------------------------------------
 
+  /** Predicate, to be used when defining an operand of a {@link RelOptRule},
+   * that returns true if a Values contains zero tuples.
+   *
+   * <p>This is the conventional way to represent an empty relational
+   * expression. There are several rules that recognize empty relational
+   * expressions and prune away that section of the tree.
+   */
+  public static boolean isEmpty(Values values) {
+    return values.getTuples().isEmpty();
+  }
+
+  /** Predicate, to be used when defining an operand of a {@link RelOptRule},
+   * that returns true if a Values contains one or more tuples.
+   *
+   * <p>This is the conventional way to represent an empty relational
+   * expression. There are several rules that recognize empty relational
+   * expressions and prune away that section of the tree.
+   */
+  public static boolean isNotEmpty(Values values) {
+    return !isEmpty(values);
+  }
+
   public ImmutableList<ImmutableList<RexLiteral>> getTuples(RelInput input) {
     return input.getTuples("tuples");
   }
@@ -188,7 +190,7 @@ public abstract class Values extends AbstractRelNode {
         .itemIf("type", rowType,
             pw.getDetailLevel() == SqlExplainLevel.DIGEST_ATTRIBUTES)
         .itemIf("type", rowType.getFieldList(), pw.nest())
-        .itemIf("tuples", Lists.transform(tuples, F), !pw.nest())
+        .itemIf("tuples", Lists.transform(tuples, Values::apply), !pw.nest())
         .itemIf("tuples", tuples, pw.nest());
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalCalc.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalCalc.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalCalc.java
index 0d37710..263010e 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalCalc.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalCalc.java
@@ -22,7 +22,6 @@ import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.plan.RelTraitSet;
 import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
-import org.apache.calcite.rel.RelDistribution;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Calc;
@@ -36,8 +35,6 @@ import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexProgram;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Supplier;
-
 import java.util.List;
 import java.util.Set;
 
@@ -95,17 +92,9 @@ public final class LogicalCalc extends Calc {
     final RelTraitSet traitSet = cluster.traitSet()
         .replace(Convention.NONE)
         .replaceIfs(RelCollationTraitDef.INSTANCE,
-            new Supplier<List<RelCollation>>() {
-              public List<RelCollation> get() {
-                return RelMdCollation.calc(mq, input, program);
-              }
-            })
+            () -> RelMdCollation.calc(mq, input, program))
         .replaceIf(RelDistributionTraitDef.INSTANCE,
-            new Supplier<RelDistribution>() {
-              public RelDistribution get() {
-                return RelMdDistribution.calc(mq, input, program);
-              }
-            });
+            () -> RelMdDistribution.calc(mq, input, program));
     return new LogicalCalc(cluster, traitSet, input, program);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalFilter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalFilter.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalFilter.java
index fce9136..3b5febf 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalFilter.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalFilter.java
@@ -19,9 +19,7 @@ package org.apache.calcite.rel.logical;
 import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
-import org.apache.calcite.rel.RelDistribution;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelInput;
 import org.apache.calcite.rel.RelNode;
@@ -34,11 +32,9 @@ import org.apache.calcite.rel.metadata.RelMdDistribution;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexNode;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableSet;
 
-import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -69,7 +65,7 @@ public final class LogicalFilter extends Filter {
       RexNode condition,
       ImmutableSet<CorrelationId> variablesSet) {
     super(cluster, traitSet, child, condition);
-    this.variablesSet = Preconditions.checkNotNull(variablesSet);
+    this.variablesSet = Objects.requireNonNull(variablesSet);
   }
 
   @Deprecated // to be removed before 2.0
@@ -78,7 +74,7 @@ public final class LogicalFilter extends Filter {
       RelTraitSet traitSet,
       RelNode child,
       RexNode condition) {
-    this(cluster, traitSet, child, condition, ImmutableSet.<CorrelationId>of());
+    this(cluster, traitSet, child, condition, ImmutableSet.of());
   }
 
   @Deprecated // to be removed before 2.0
@@ -87,7 +83,7 @@ public final class LogicalFilter extends Filter {
       RelNode child,
       RexNode condition) {
     this(cluster, cluster.traitSetOf(Convention.NONE), child, condition,
-        ImmutableSet.<CorrelationId>of());
+        ImmutableSet.of());
   }
 
   /**
@@ -100,7 +96,7 @@ public final class LogicalFilter extends Filter {
 
   /** Creates a LogicalFilter. */
   public static LogicalFilter create(final RelNode input, RexNode condition) {
-    return create(input, condition, ImmutableSet.<CorrelationId>of());
+    return create(input, condition, ImmutableSet.of());
   }
 
   /** Creates a LogicalFilter. */
@@ -110,17 +106,9 @@ public final class LogicalFilter extends Filter {
     final RelMetadataQuery mq = cluster.getMetadataQuery();
     final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE)
         .replaceIfs(RelCollationTraitDef.INSTANCE,
-            new Supplier<List<RelCollation>>() {
-              public List<RelCollation> get() {
-                return RelMdCollation.filter(mq, input);
-              }
-            })
+            () -> RelMdCollation.filter(mq, input))
         .replaceIf(RelDistributionTraitDef.INSTANCE,
-            new Supplier<RelDistribution>() {
-              public RelDistribution get() {
-                return RelMdDistribution.filter(mq, input);
-              }
-            });
+            () -> RelMdDistribution.filter(mq, input));
     return new LogicalFilter(cluster, traitSet, input, condition, variablesSet);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalJoin.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalJoin.java
index aacd72a..696d0b6 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalJoin.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalJoin.java
@@ -29,11 +29,11 @@ import org.apache.calcite.rel.core.JoinRelType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexNode;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -97,7 +97,7 @@ public final class LogicalJoin extends Join {
       ImmutableList<RelDataTypeField> systemFieldList) {
     super(cluster, traitSet, left, right, condition, variablesSet, joinType);
     this.semiJoinDone = semiJoinDone;
-    this.systemFieldList = Preconditions.checkNotNull(systemFieldList);
+    this.systemFieldList = Objects.requireNonNull(systemFieldList);
   }
 
   @Deprecated // to be removed before 2.0
@@ -115,7 +115,7 @@ public final class LogicalJoin extends Join {
       RexNode condition, JoinRelType joinType, Set<String> variablesStopped) {
     this(cluster, cluster.traitSetOf(Convention.NONE), left, right, condition,
         CorrelationId.setOf(variablesStopped), joinType, false,
-        ImmutableList.<RelDataTypeField>of());
+        ImmutableList.of());
   }
 
   @Deprecated // to be removed before 2.0
@@ -133,9 +133,9 @@ public final class LogicalJoin extends Join {
   public LogicalJoin(RelInput input) {
     this(input.getCluster(), input.getCluster().traitSetOf(Convention.NONE),
         input.getInputs().get(0), input.getInputs().get(1),
-        input.getExpression("condition"), ImmutableSet.<CorrelationId>of(),
+        input.getExpression("condition"), ImmutableSet.of(),
         input.getEnum("joinType", JoinRelType.class), false,
-        ImmutableList.<RelDataTypeField>of());
+        ImmutableList.of());
   }
 
   /** Creates a LogicalJoin, flagged with whether it has been translated to a
@@ -161,14 +161,14 @@ public final class LogicalJoin extends Join {
   public static LogicalJoin create(RelNode left, RelNode right,
       RexNode condition, Set<CorrelationId> variablesSet, JoinRelType joinType) {
     return create(left, right, condition, variablesSet, joinType, false,
-        ImmutableList.<RelDataTypeField>of());
+        ImmutableList.of());
   }
 
   @Deprecated // to be removed before 2.0
   public static LogicalJoin create(RelNode left, RelNode right,
       RexNode condition, JoinRelType joinType, Set<String> variablesStopped) {
     return create(left, right, condition, CorrelationId.setOf(variablesStopped),
-        joinType, false, ImmutableList.<RelDataTypeField>of());
+        joinType, false, ImmutableList.of());
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalProject.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalProject.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalProject.java
index 9eec20b..c5bbd4e 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalProject.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalProject.java
@@ -19,7 +19,6 @@ package org.apache.calcite.rel.logical;
 import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
 import org.apache.calcite.rel.RelCollations;
 import org.apache.calcite.rel.RelInput;
@@ -34,8 +33,6 @@ import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Supplier;
-
 import java.util.List;
 
 /**
@@ -110,13 +107,8 @@ public final class LogicalProject extends Project {
     final RelMetadataQuery mq = cluster.getMetadataQuery();
     final RelTraitSet traitSet =
         cluster.traitSet().replace(Convention.NONE)
-            .replaceIfs(
-                RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    return RelMdCollation.project(mq, input, projects);
-                  }
-                });
+            .replaceIfs(RelCollationTraitDef.INSTANCE,
+                () -> RelMdCollation.project(mq, input, projects));
     return new LogicalProject(cluster, traitSet, input, projects, rowType);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalTableScan.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalTableScan.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalTableScan.java
index abad97d..6b6b74a 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalTableScan.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalTableScan.java
@@ -20,14 +20,12 @@ import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
 import org.apache.calcite.rel.RelInput;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.TableScan;
 import org.apache.calcite.schema.Table;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
@@ -99,15 +97,12 @@ public final class LogicalTableScan extends TableScan {
     final Table table = relOptTable.unwrap(Table.class);
     final RelTraitSet traitSet =
         cluster.traitSetOf(Convention.NONE)
-            .replaceIfs(RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    if (table != null) {
-                      return table.getStatistic().getCollations();
-                    }
-                    return ImmutableList.of();
-                  }
-                });
+            .replaceIfs(RelCollationTraitDef.INSTANCE, () -> {
+              if (table != null) {
+                return table.getStatistic().getCollations();
+              }
+              return ImmutableList.of();
+            });
     return new LogicalTableScan(cluster, traitSet, relOptTable);
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalValues.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalValues.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalValues.java
index b2934f5..5fc9548 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalValues.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalValues.java
@@ -19,7 +19,6 @@ package org.apache.calcite.rel.logical;
 import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
 import org.apache.calcite.rel.RelInput;
 import org.apache.calcite.rel.RelNode;
@@ -31,7 +30,6 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.sql.type.SqlTypeName;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.math.BigDecimal;
@@ -84,12 +82,8 @@ public class LogicalValues extends Values {
       final ImmutableList<ImmutableList<RexLiteral>> tuples) {
     final RelMetadataQuery mq = cluster.getMetadataQuery();
     final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE)
-        .replaceIfs(
-            RelCollationTraitDef.INSTANCE, new Supplier<List<RelCollation>>() {
-              public List<RelCollation> get() {
-                return RelMdCollation.values(mq, rowType, tuples);
-              }
-            });
+        .replaceIfs(RelCollationTraitDef.INSTANCE,
+            () -> RelMdCollation.values(mq, rowType, tuples));
     return new LogicalValues(cluster, traitSet, rowType, tuples);
   }
 
@@ -103,7 +97,7 @@ public class LogicalValues extends Values {
   public static LogicalValues createEmpty(RelOptCluster cluster,
       RelDataType rowType) {
     return create(cluster, rowType,
-        ImmutableList.<ImmutableList<RexLiteral>>of());
+        ImmutableList.of());
   }
 
   /** Creates a LogicalValues that outputs one row and one column. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/logical/LogicalWindow.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/logical/LogicalWindow.java b/core/src/main/java/org/apache/calcite/rel/logical/LogicalWindow.java
index 987bf5f..f03cc2f 100644
--- a/core/src/main/java/org/apache/calcite/rel/logical/LogicalWindow.java
+++ b/core/src/main/java/org/apache/calcite/rel/logical/LogicalWindow.java
@@ -24,7 +24,6 @@ import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Window;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rex.RexFieldCollation;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexLocalRef;
@@ -34,7 +33,6 @@ import org.apache.calcite.rex.RexProgram;
 import org.apache.calcite.rex.RexShuttle;
 import org.apache.calcite.rex.RexWindow;
 import org.apache.calcite.rex.RexWindowBound;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Litmus;
@@ -181,8 +179,7 @@ public final class LogicalWindow extends Window {
     // each window.
     final List<Window.RexWinAggCall> flattenedAggCallList = new ArrayList<>();
     final List<Map.Entry<String, RelDataType>> fieldList =
-        new ArrayList<Map.Entry<String, RelDataType>>(
-            child.getRowType().getFieldList());
+        new ArrayList<>(child.getRowType().getFieldList());
     final int offset = fieldList.size();
 
     // Use better field names for agg calls that are projected.
@@ -349,13 +346,10 @@ public final class LogicalWindow extends Window {
     RelCollation orderKeys = getCollation(
         Lists.newArrayList(
             Iterables.filter(aggWindow.orderKeys,
-              new PredicateImpl<RexFieldCollation>() {
-                public boolean test(RexFieldCollation rexFieldCollation) {
-                  // If ORDER BY references constant (i.e. RexInputRef),
-                  // then we can ignore such ORDER BY key.
-                  return rexFieldCollation.left instanceof RexLocalRef;
-                }
-              })));
+                rexFieldCollation ->
+                    // If ORDER BY references constant (i.e. RexInputRef),
+                    // then we can ignore such ORDER BY key.
+                    rexFieldCollation.left instanceof RexLocalRef)));
     ImmutableBitSet groupSet =
         ImmutableBitSet.of(getProjectOrdinals(aggWindow.partitionKeys));
     final int groupLength = groupSet.length();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/CachingRelMetadataProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/CachingRelMetadataProvider.java b/core/src/main/java/org/apache/calcite/rel/metadata/CachingRelMetadataProvider.java
index f79b187..fd44e47 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/CachingRelMetadataProvider.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/CachingRelMetadataProvider.java
@@ -19,7 +19,6 @@ package org.apache.calcite.rel.metadata;
 import org.apache.calcite.plan.RelOptPlanner;
 import org.apache.calcite.rel.RelNode;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Multimap;
 
@@ -30,6 +29,7 @@ import java.lang.reflect.Proxy;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Implementation of the {@link RelMetadataProvider}
@@ -66,14 +66,12 @@ public class CachingRelMetadataProvider implements RelMetadataProvider {
 
     // TODO jvs 30-Mar-2006: Use meta-metadata to decide which metadata
     // query results can stay fresh until the next Ice Age.
-    return new UnboundMetadata<M>() {
-      public M bind(RelNode rel, RelMetadataQuery mq) {
-        final Metadata metadata = function.bind(rel, mq);
-        return metadataClass.cast(
-            Proxy.newProxyInstance(metadataClass.getClassLoader(),
-                new Class[]{metadataClass},
-                new CachingInvocationHandler(metadata)));
-      }
+    return (rel, mq) -> {
+      final Metadata metadata = function.bind(rel, mq);
+      return metadataClass.cast(
+          Proxy.newProxyInstance(metadataClass.getClassLoader(),
+              new Class[]{metadataClass},
+              new CachingInvocationHandler(metadata)));
     };
   }
 
@@ -102,7 +100,7 @@ public class CachingRelMetadataProvider implements RelMetadataProvider {
     private final Metadata metadata;
 
     CachingInvocationHandler(Metadata metadata) {
-      this.metadata = Preconditions.checkNotNull(metadata);
+      this.metadata = Objects.requireNonNull(metadata);
     }
 
     public Object invoke(Object proxy, Method method, Object[] args)

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/ChainedRelMetadataProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/ChainedRelMetadataProvider.java b/core/src/main/java/org/apache/calcite/rel/metadata/ChainedRelMetadataProvider.java
index 9f1b0cb..af01813 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/ChainedRelMetadataProvider.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/ChainedRelMetadataProvider.java
@@ -21,7 +21,6 @@ import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMultimap;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
 
 import java.lang.reflect.InvocationHandler;
@@ -86,20 +85,18 @@ public class ChainedRelMetadataProvider implements RelMetadataProvider {
     case 1:
       return functions.get(0);
     default:
-      return new UnboundMetadata<M>() {
-        public M bind(RelNode rel, RelMetadataQuery mq) {
-          final List<Metadata> metadataList = Lists.newArrayList();
-          for (UnboundMetadata<M> function : functions) {
-            final Metadata metadata = function.bind(rel, mq);
-            if (metadata != null) {
-              metadataList.add(metadata);
-            }
+      return (rel, mq) -> {
+        final List<Metadata> metadataList = new ArrayList<>();
+        for (UnboundMetadata<M> function : functions) {
+          final Metadata metadata = function.bind(rel, mq);
+          if (metadata != null) {
+            metadataList.add(metadata);
           }
-          return metadataClass.cast(
-              Proxy.newProxyInstance(metadataClass.getClassLoader(),
-                  new Class[]{metadataClass},
-                  new ChainedInvocationHandler(metadataList)));
         }
+        return metadataClass.cast(
+            Proxy.newProxyInstance(metadataClass.getClassLoader(),
+                new Class[]{metadataClass},
+                new ChainedInvocationHandler(metadataList)));
       };
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/JaninoRelMetadataProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/JaninoRelMetadataProvider.java b/core/src/main/java/org/apache/calcite/rel/metadata/JaninoRelMetadataProvider.java
index fe937ed..e3e4407 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/JaninoRelMetadataProvider.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/JaninoRelMetadataProvider.java
@@ -82,7 +82,6 @@ import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.CopyOnWriteArraySet;
 import java.util.concurrent.ExecutionException;
-import javax.annotation.Nonnull;
 
 /**
  * Implementation of the {@link RelMetadataProvider} interface that generates
@@ -102,17 +101,14 @@ public class JaninoRelMetadataProvider implements RelMetadataProvider {
   /** Cache of pre-generated handlers by provider and kind of metadata.
    * For the cache to be effective, providers should implement identity
    * correctly. */
+  @SuppressWarnings("unchecked")
   private static final LoadingCache<Key, MetadataHandler> HANDLERS =
       maxSize(CacheBuilder.newBuilder(),
           SaffronProperties.INSTANCE.metadataHandlerCacheMaximumSize().get())
           .build(
-              new CacheLoader<Key, MetadataHandler>() {
-                public MetadataHandler load(@Nonnull Key key) {
-                  //noinspection unchecked
-                  return load3(key.def, key.provider.handlers(key.def),
-                      key.relClasses);
-                }
-              });
+              CacheLoader.from(key ->
+                  load3(key.def, key.provider.handlers(key.def),
+                      key.relClasses)));
 
   // Pre-register the most common relational operators, to reduce the number of
   // times we re-generate.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/MetadataFactoryImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/MetadataFactoryImpl.java b/core/src/main/java/org/apache/calcite/rel/metadata/MetadataFactoryImpl.java
index 063cf6e..781c697 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/MetadataFactoryImpl.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/MetadataFactoryImpl.java
@@ -36,12 +36,7 @@ import java.util.concurrent.ExecutionException;
  */
 public class MetadataFactoryImpl implements MetadataFactory {
   @SuppressWarnings("unchecked")
-  public static final UnboundMetadata<Metadata> DUMMY =
-      new UnboundMetadata<Metadata>() {
-        public Metadata bind(RelNode rel, RelMetadataQuery mq) {
-          return null;
-        }
-      };
+  public static final UnboundMetadata<Metadata> DUMMY = (rel, mq) -> null;
 
   private final LoadingCache<
       Pair<Class<RelNode>, Class<Metadata>>, UnboundMetadata<Metadata>> cache;
@@ -52,16 +47,12 @@ public class MetadataFactoryImpl implements MetadataFactory {
 
   private static CacheLoader<Pair<Class<RelNode>, Class<Metadata>>,
       UnboundMetadata<Metadata>> loader(final RelMetadataProvider provider) {
-    return new CacheLoader<Pair<Class<RelNode>, Class<Metadata>>,
-        UnboundMetadata<Metadata>>() {
-      @Override public UnboundMetadata<Metadata> load(
-          Pair<Class<RelNode>, Class<Metadata>> key) throws Exception {
-        final UnboundMetadata<Metadata> function =
-            provider.apply(key.left, key.right);
-        // Return DUMMY, not null, so the cache knows to not ask again.
-        return function != null ? function : DUMMY;
-      }
-    };
+    return CacheLoader.from(key -> {
+      final UnboundMetadata<Metadata> function =
+          provider.apply(key.left, key.right);
+      // Return DUMMY, not null, so the cache knows to not ask again.
+      return function != null ? function : DUMMY;
+    });
   }
 
   public <M extends Metadata> M query(RelNode rel, RelMetadataQuery mq,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/ReflectiveRelMetadataProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/ReflectiveRelMetadataProvider.java b/core/src/main/java/org/apache/calcite/rel/metadata/ReflectiveRelMetadataProvider.java
index 9b5abec..20185b7 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/ReflectiveRelMetadataProvider.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/ReflectiveRelMetadataProvider.java
@@ -25,12 +25,10 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.ReflectiveVisitor;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMultimap;
 import com.google.common.collect.Multimap;
 
-import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
@@ -42,6 +40,7 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
@@ -130,80 +129,68 @@ public class ReflectiveRelMetadataProvider
         builder.add(space.find(key, method));
       }
       final List<Method> handlerMethods = builder.build();
-      final UnboundMetadata function =
-          new UnboundMetadata() {
-            public Metadata bind(final RelNode rel,
-                final RelMetadataQuery mq) {
-              return (Metadata) Proxy.newProxyInstance(
-                  space.metadataClass0.getClassLoader(),
-                  new Class[]{space.metadataClass0},
-                  new InvocationHandler() {
-                    public Object invoke(Object proxy, Method method,
-                        Object[] args) throws Throwable {
-                      // Suppose we are an implementation of Selectivity
-                      // that wraps "filter", a LogicalFilter. Then we
-                      // implement
-                      //   Selectivity.selectivity(rex)
-                      // by calling method
-                      //   new SelectivityImpl().selectivity(filter, rex)
-                      if (method.equals(
-                          BuiltInMethod.METADATA_REL.method)) {
-                        return rel;
-                      }
-                      if (method.equals(
-                          BuiltInMethod.OBJECT_TO_STRING.method)) {
-                        return space.metadataClass0.getSimpleName() + "(" + rel
-                            + ")";
-                      }
-                      int i = methods.indexOf(method);
-                      if (i < 0) {
-                        throw new AssertionError("not handled: " + method
-                            + " for " + rel);
-                      }
-                      final Method handlerMethod = handlerMethods.get(i);
-                      if (handlerMethod == null) {
-                        throw new AssertionError("not handled: " + method
-                            + " for " + rel);
-                      }
-                      final Object[] args1;
-                      final List key;
-                      if (args == null) {
-                        args1 = new Object[]{rel, mq};
-                        key = FlatLists.of(rel, method);
-                      } else {
-                        args1 = new Object[args.length + 2];
-                        args1[0] = rel;
-                        args1[1] = mq;
-                        System.arraycopy(args, 0, args1, 2, args.length);
+      final UnboundMetadata function = (rel, mq) ->
+          (Metadata) Proxy.newProxyInstance(
+              space.metadataClass0.getClassLoader(),
+              new Class[]{space.metadataClass0}, (proxy, method, args) -> {
+                // Suppose we are an implementation of Selectivity
+                // that wraps "filter", a LogicalFilter. Then we
+                // implement
+                //   Selectivity.selectivity(rex)
+                // by calling method
+                //   new SelectivityImpl().selectivity(filter, rex)
+                if (method.equals(BuiltInMethod.METADATA_REL.method)) {
+                  return rel;
+                }
+                if (method.equals(BuiltInMethod.OBJECT_TO_STRING.method)) {
+                  return space.metadataClass0.getSimpleName() + "(" + rel + ")";
+                }
+                int i = methods.indexOf(method);
+                if (i < 0) {
+                  throw new AssertionError("not handled: " + method
+                      + " for " + rel);
+                }
+                final Method handlerMethod = handlerMethods.get(i);
+                if (handlerMethod == null) {
+                  throw new AssertionError("not handled: " + method
+                      + " for " + rel);
+                }
+                final Object[] args1;
+                final List key1;
+                if (args == null) {
+                  args1 = new Object[]{rel, mq};
+                  key1 = FlatLists.of(rel, method);
+                } else {
+                  args1 = new Object[args.length + 2];
+                  args1[0] = rel;
+                  args1[1] = mq;
+                  System.arraycopy(args, 0, args1, 2, args.length);
 
-                        final Object[] args2 = args1.clone();
-                        args2[1] = method; // replace RelMetadataQuery with method
-                        for (int j = 0; j < args2.length; j++) {
-                          if (args2[j] == null) {
-                            args2[j] = NullSentinel.INSTANCE;
-                          } else if (args2[j] instanceof RexNode) {
-                            // Can't use RexNode.equals - it is not deep
-                            args2[j] = args2[j].toString();
-                          }
-                        }
-                        key = FlatLists.copyOf(args2);
-                      }
-                      if (mq.map.put(key, NullSentinel.INSTANCE) != null) {
-                        throw CyclicMetadataException.INSTANCE;
-                      }
-                      try {
-                        return handlerMethod.invoke(target, args1);
-                      } catch (InvocationTargetException
-                          | UndeclaredThrowableException e) {
-                        Util.throwIfUnchecked(e.getCause());
-                        throw new RuntimeException(e.getCause());
-                      } finally {
-                        mq.map.remove(key);
-                      }
+                  final Object[] args2 = args1.clone();
+                  args2[1] = method; // replace RelMetadataQuery with method
+                  for (int j = 0; j < args2.length; j++) {
+                    if (args2[j] == null) {
+                      args2[j] = NullSentinel.INSTANCE;
+                    } else if (args2[j] instanceof RexNode) {
+                      // Can't use RexNode.equals - it is not deep
+                      args2[j] = args2[j].toString();
                     }
-                  });
-            }
-          };
+                  }
+                  key1 = FlatLists.copyOf(args2);
+                }
+                if (mq.map.put(key1, NullSentinel.INSTANCE) != null) {
+                  throw CyclicMetadataException.INSTANCE;
+                }
+                try {
+                  return handlerMethod.invoke(target, args1);
+                } catch (InvocationTargetException
+                    | UndeclaredThrowableException e) {
+                  Util.throwIfUnchecked(e.getCause());
+                  throw new RuntimeException(e.getCause());
+                } finally {
+                  mq.map.remove(key1);
+                }
+              });
       methodsMap.put(key, function);
     }
     return new ReflectiveRelMetadataProvider(methodsMap, space.metadataClass0,
@@ -313,7 +300,7 @@ public class ReflectiveRelMetadataProvider
      * {@code map}. */
     @SuppressWarnings({ "unchecked", "SuspiciousMethodCalls" })
     Method find(final Class<? extends RelNode> relNodeClass, Method method) {
-      Preconditions.checkNotNull(relNodeClass);
+      Objects.requireNonNull(relNodeClass);
       for (Class r = relNodeClass;;) {
         Method implementingMethod = handlerMap.get(Pair.of(r, method));
         if (implementingMethod != null) {


[24/30] calcite git commit: [CALCITE-2280] Babel SQL parser

Posted by jh...@apache.org.
[CALCITE-2280] Babel SQL parser

Add BABEL conformance value and SqlConformance.isLiberal() method.

CalciteAssert.withSchema automatically sets the schema as default.


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/3e50a532
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/3e50a532
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/3e50a532

Branch: refs/heads/master
Commit: 3e50a5325357720d109e5fa300dad7a918087139
Parents: c749f25
Author: Julian Hyde <jh...@apache.org>
Authored: Wed May 2 00:03:14 2018 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:41:08 2018 -0700

----------------------------------------------------------------------
 babel/pom.xml                                   | 241 +++++++++++++++++++
 babel/src/main/codegen/config.fmpp              |  80 ++++++
 babel/src/main/codegen/includes/parserImpls.ftl |  18 ++
 .../org/apache/calcite/sql/babel/Babel.java     |  26 ++
 .../apache/calcite/sql/babel/package-info.java  |  26 ++
 .../apache/calcite/test/BabelParserTest.java    |  47 ++++
 .../apache/calcite/test/BabelQuidemTest.java    | 193 +++++++++++++++
 .../java/org/apache/calcite/test/BabelTest.java |  56 +++++
 babel/src/test/resources/sql/dummy.iq           |  27 +++
 babel/src/test/resources/sql/select.iq          |  54 +++++
 .../apache/calcite/runtime/CalciteResource.java |   3 +
 .../sql/validate/SqlAbstractConformance.java    |   4 +
 .../calcite/sql/validate/SqlConformance.java    |  20 ++
 .../sql/validate/SqlConformanceEnum.java        |  30 ++-
 .../calcite/runtime/CalciteResource.properties  |   1 +
 .../org/apache/calcite/test/CalciteAssert.java  | 131 +++++-----
 .../calcite/test/JdbcFrontJdbcBackTest.java     |   1 -
 .../org/apache/calcite/test/QuidemTest.java     |  19 +-
 pom.xml                                         |  21 +-
 .../src/test/resources/sql/materialized_view.iq |   4 +-
 server/src/test/resources/sql/schema.iq         |   2 +-
 21 files changed, 935 insertions(+), 69 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/pom.xml
----------------------------------------------------------------------
diff --git a/babel/pom.xml b/babel/pom.xml
new file mode 100644
index 0000000..20550d7
--- /dev/null
+++ b/babel/pom.xml
@@ -0,0 +1,241 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.apache.calcite</groupId>
+    <artifactId>calcite</artifactId>
+    <version>1.17.0-SNAPSHOT</version>
+  </parent>
+
+  <artifactId>calcite-babel</artifactId>
+  <packaging>jar</packaging>
+  <version>1.17.0-SNAPSHOT</version>
+  <name>Calcite Babel</name>
+  <description>Calcite Babel</description>
+
+  <properties>
+    <top.dir>${project.basedir}/..</top.dir>
+  </properties>
+
+  <dependencies>
+    <!-- Sorted by groupId, artifactId; calcite dependencies first. Put versions
+         in dependencyManagement in the root POM, not here. -->
+    <dependency>
+      <groupId>org.apache.calcite.avatica</groupId>
+      <artifactId>avatica-core</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.calcite</groupId>
+      <artifactId>calcite-core</artifactId>
+      <type>jar</type>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.calcite</groupId>
+      <artifactId>calcite-core</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+
+    <dependency>
+      <groupId>com.google.guava</groupId>
+      <artifactId>guava</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>net.hydromatic</groupId>
+      <artifactId>quidem</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>net.hydromatic</groupId>
+      <artifactId>scott-data-hsqldb</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.hamcrest</groupId>
+      <artifactId>hamcrest-core</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.incava</groupId>
+      <artifactId>java-diff</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.hsqldb</groupId>
+      <artifactId>hsqldb</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-log4j12</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <!-- Sorted by groupId, artifactId. Put versions in
+           pluginManagement in the root POM, not here. -->
+      <plugin>
+        <artifactId>maven-dependency-plugin</artifactId>
+        <version>${maven-dependency-plugin.version}</version>
+        <executions>
+          <execution>
+            <id>analyze</id>
+            <goals>
+              <goal>analyze-only</goal>
+            </goals>
+            <configuration>
+              <failOnWarning>true</failOnWarning>
+              <!-- ignore "unused but declared" warnings -->
+              <ignoredUnusedDeclaredDependencies>
+                <ignoredUnusedDeclaredDependency>net.hydromatic:scott-data-hsqldb</ignoredUnusedDeclaredDependency>
+                <ignoredUnusedDeclaredDependency>org.hsqldb:hsqldb</ignoredUnusedDeclaredDependency>
+                <ignoredUnusedDeclaredDependency>org.incava:java-diff</ignoredUnusedDeclaredDependency>
+                <ignoredUnusedDeclaredDependency>org.slf4j:slf4j-api</ignoredUnusedDeclaredDependency>
+                <ignoredUnusedDeclaredDependency>org.slf4j:slf4j-log4j12</ignoredUnusedDeclaredDependency>
+              </ignoredUnusedDeclaredDependencies>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-jar-plugin</artifactId>
+        <executions>
+          <execution>
+            <goals>
+              <goal>test-jar</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <artifactId>maven-resources-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>copy-fmpp-resources</id>
+            <phase>initialize</phase>
+            <goals>
+              <goal>copy-resources</goal>
+            </goals>
+            <configuration>
+              <outputDirectory>${project.build.directory}/codegen</outputDirectory>
+              <resources>
+                <resource>
+                  <directory>src/main/codegen</directory>
+                  <filtering>false</filtering>
+                </resource>
+              </resources>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-release-plugin</artifactId>
+      </plugin>
+      <!-- Parent module has the same plugin and does the work of
+           generating -sources.jar for each project. But without the
+           plugin declared here, IDEs don't know the sources are
+           available. -->
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-source-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>attach-sources</id>
+            <phase>verify</phase>
+            <goals>
+              <goal>jar-no-fork</goal>
+              <goal>test-jar-no-fork</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>javacc-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>javacc</id>
+            <goals>
+              <goal>javacc</goal>
+            </goals>
+            <configuration>
+              <sourceDirectory>${project.build.directory}/generated-sources/fmpp</sourceDirectory>
+              <outputDirectory>${project.build.directory}/generated-sources/javacc</outputDirectory>
+              <includes>
+                <include>**/Parser.jj</include>
+              </includes>
+              <lookAhead>2</lookAhead>
+              <isStatic>false</isStatic>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+
+  <profiles>
+    <profile>
+      <!-- CALCITE-538: workaround for https://github.com/freemarker/fmpp/issues/11
+        FMPP always overwrites destination file, however we do not want
+        recompile the whole module every time.
+      -->
+      <id>generate-parser</id>
+      <activation>
+        <property>
+          <name>!skipGenerate</name>
+        </property>
+      </activation>
+      <build>
+        <plugins>
+          <plugin>
+            <groupId>com.googlecode.fmpp-maven-plugin</groupId>
+            <artifactId>fmpp-maven-plugin</artifactId>
+            <executions>
+              <execution>
+                <configuration>
+                  <cfgFile>src/main/codegen/config.fmpp</cfgFile>
+                  <outputDirectory>${project.build.directory}/generated-sources/fmpp</outputDirectory>
+                  <templateDirectory>${top.dir}/core/src/main/codegen/templates</templateDirectory>
+                </configuration>
+                <id>generate-fmpp-sources</id>
+                <phase>validate</phase>
+                <goals>
+                  <goal>generate</goal>
+                </goals>
+              </execution>
+            </executions>
+          </plugin>
+        </plugins>
+      </build>
+    </profile>
+  </profiles>
+</project>

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/main/codegen/config.fmpp
----------------------------------------------------------------------
diff --git a/babel/src/main/codegen/config.fmpp b/babel/src/main/codegen/config.fmpp
new file mode 100644
index 0000000..57bbe86
--- /dev/null
+++ b/babel/src/main/codegen/config.fmpp
@@ -0,0 +1,80 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+data: {
+    parser: {
+      # Generated parser implementation class package and name
+      package: "org.apache.calcite.sql.parser.babel",
+      class: "SqlBabelParserImpl",
+
+      # List of import statements.
+      imports: [
+      ]
+
+      # List of keywords.
+      keywords: [
+        "SEMI"
+      ]
+
+      # List of keywords from "keywords" section that are not reserved.
+      nonReservedKeywords: [
+        "SEMI"
+      ]
+
+      # List of methods for parsing custom SQL statements.
+      statementParserMethods: [
+      ]
+
+      # List of methods for parsing custom literals.
+      # Example: ParseJsonLiteral().
+      literalParserMethods: [
+      ]
+
+      # List of methods for parsing custom data types.
+      dataTypeParserMethods: [
+      ]
+
+      # List of methods for parsing extensions to "ALTER <scope>" calls.
+      # Each must accept arguments "(SqlParserPos pos, String scope)".
+      alterStatementParserMethods: [
+      ]
+
+      # List of methods for parsing extensions to "CREATE [OR REPLACE]" calls.
+      # Each must accept arguments "(SqlParserPos pos, boolean replace)".
+      createStatementParserMethods: [
+      ]
+
+      # List of methods for parsing extensions to "DROP" calls.
+      # Each must accept arguments "(SqlParserPos pos)".
+      dropStatementParserMethods: [
+      ]
+
+      # List of files in @includes directory that have parser method
+      # implementations for parsing custom SQL statements, literals or types
+      # given as part of "statementParserMethods", "literalParserMethods" or
+      # "dataTypeParserMethods".
+      implementationFiles: [
+        "parserImpls.ftl"
+      ]
+
+      includeCompoundIdentifier: true
+      includeBraces: true
+      includeAdditionalDeclarations: false
+
+    }
+}
+freemarkerLinks: {
+    includes: includes/
+}

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/main/codegen/includes/parserImpls.ftl
----------------------------------------------------------------------
diff --git a/babel/src/main/codegen/includes/parserImpls.ftl b/babel/src/main/codegen/includes/parserImpls.ftl
new file mode 100644
index 0000000..627a634
--- /dev/null
+++ b/babel/src/main/codegen/includes/parserImpls.ftl
@@ -0,0 +1,18 @@
+<#--
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to you under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+-->
+
+// End parserImpls.ftl

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/main/java/org/apache/calcite/sql/babel/Babel.java
----------------------------------------------------------------------
diff --git a/babel/src/main/java/org/apache/calcite/sql/babel/Babel.java b/babel/src/main/java/org/apache/calcite/sql/babel/Babel.java
new file mode 100644
index 0000000..167a136
--- /dev/null
+++ b/babel/src/main/java/org/apache/calcite/sql/babel/Babel.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.sql.babel;
+
+/** SQL parser that accepts a wide variety of dialects. */
+@SuppressWarnings("unused")
+public class Babel {
+  // This class is currently a place-holder. Javadoc gets upset
+  // if there are no classes in babel/java/main.
+}
+
+// End Babel.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/main/java/org/apache/calcite/sql/babel/package-info.java
----------------------------------------------------------------------
diff --git a/babel/src/main/java/org/apache/calcite/sql/babel/package-info.java b/babel/src/main/java/org/apache/calcite/sql/babel/package-info.java
new file mode 100644
index 0000000..498513a
--- /dev/null
+++ b/babel/src/main/java/org/apache/calcite/sql/babel/package-info.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Parse tree for SQL extensions used by the Babel parser.
+ */
+@PackageMarker
+package org.apache.calcite.sql.babel;
+
+import org.apache.calcite.avatica.util.PackageMarker;
+
+// End package-info.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/test/java/org/apache/calcite/test/BabelParserTest.java
----------------------------------------------------------------------
diff --git a/babel/src/test/java/org/apache/calcite/test/BabelParserTest.java b/babel/src/test/java/org/apache/calcite/test/BabelParserTest.java
new file mode 100644
index 0000000..521266d
--- /dev/null
+++ b/babel/src/test/java/org/apache/calcite/test/BabelParserTest.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.test;
+
+import org.apache.calcite.sql.parser.SqlParserImplFactory;
+import org.apache.calcite.sql.parser.SqlParserTest;
+import org.apache.calcite.sql.parser.babel.SqlBabelParserImpl;
+
+import org.junit.Test;
+
+/**
+ * Tests the "Babel" SQL parser, that understands all dialects of SQL.
+ */
+public class BabelParserTest extends SqlParserTest {
+
+  @Override protected SqlParserImplFactory parserImplFactory() {
+    return SqlBabelParserImpl.FACTORY;
+  }
+
+  @Override public void testGenerateKeyWords() {
+    // by design, method only works in base class; no-ops in this sub-class
+  }
+
+  @Test public void testSelect() {
+    final String sql = "select 1 from t";
+    final String expected = "SELECT 1\n"
+        + "FROM `T`";
+    sql(sql).ok(expected);
+  }
+
+}
+
+// End BabelParserTest.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/test/java/org/apache/calcite/test/BabelQuidemTest.java
----------------------------------------------------------------------
diff --git a/babel/src/test/java/org/apache/calcite/test/BabelQuidemTest.java b/babel/src/test/java/org/apache/calcite/test/BabelQuidemTest.java
new file mode 100644
index 0000000..4c2e304
--- /dev/null
+++ b/babel/src/test/java/org/apache/calcite/test/BabelQuidemTest.java
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.test;
+
+import org.apache.calcite.config.CalciteConnectionConfig;
+import org.apache.calcite.config.CalciteConnectionConfigImpl;
+import org.apache.calcite.config.CalciteConnectionProperty;
+import org.apache.calcite.jdbc.CalciteConnection;
+import org.apache.calcite.materialize.MaterializationService;
+import org.apache.calcite.plan.Contexts;
+import org.apache.calcite.schema.SchemaPlus;
+import org.apache.calcite.sql.SqlNode;
+import org.apache.calcite.sql.SqlWriter;
+import org.apache.calcite.sql.dialect.CalciteSqlDialect;
+import org.apache.calcite.sql.parser.SqlParser;
+import org.apache.calcite.sql.parser.babel.SqlBabelParserImpl;
+import org.apache.calcite.sql.pretty.SqlPrettyWriter;
+import org.apache.calcite.sql.validate.SqlConformanceEnum;
+import org.apache.calcite.tools.Frameworks;
+import org.apache.calcite.tools.Planner;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+import net.hydromatic.quidem.AbstractCommand;
+import net.hydromatic.quidem.Command;
+import net.hydromatic.quidem.CommandHandler;
+import net.hydromatic.quidem.Quidem;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.sql.Connection;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Unit tests for the Babel SQL parser.
+ */
+@RunWith(Parameterized.class)
+@Ignore
+public class BabelQuidemTest extends QuidemTest {
+  /** Creates a BabelQuidemTest. Public per {@link Parameterized}. */
+  @SuppressWarnings("WeakerAccess")
+  public BabelQuidemTest(String path) {
+    super(path);
+  }
+
+  /** Runs a test from the command line.
+   *
+   * <p>For example:
+   *
+   * <blockquote>
+   *   <code>java BabelQuidemTest sql/table.iq</code>
+   * </blockquote> */
+  public static void main(String[] args) throws Exception {
+    for (String arg : args) {
+      new BabelQuidemTest(arg).test();
+    }
+  }
+
+  @Override @Test public void test() throws Exception {
+    MaterializationService.setThreadLocal();
+    super.test();
+  }
+
+  /** For {@link Parameterized} runner. */
+  @Parameterized.Parameters(name = "{index}: quidem({0})")
+  public static Collection<Object[]> data() {
+    // Start with a test file we know exists, then find the directory and list
+    // its files.
+    final String first = "sql/select.iq";
+    return data(first);
+  }
+
+  @Override protected Quidem.ConnectionFactory createConnectionFactory() {
+    return new QuidemConnectionFactory() {
+      @Override public Connection connect(String name, boolean reference)
+          throws Exception {
+        switch (name) {
+        case "babel":
+          return BabelTest.connect();
+        }
+        return super.connect(name, reference);
+      }
+    };
+  }
+
+  @Override protected CommandHandler createCommandHandler() {
+    return new BabelCommandHandler();
+  }
+
+  /** Command that prints the validated parse tree of a SQL statement. */
+  static class ExplainValidatedCommand extends AbstractCommand {
+    private final ImmutableList<String> lines;
+    private final ImmutableList<String> content;
+    private final Set<String> productSet;
+
+    ExplainValidatedCommand(List<String> lines, List<String> content,
+        Set<String> productSet) {
+      this.lines = ImmutableList.copyOf(lines);
+      this.content = ImmutableList.copyOf(content);
+      this.productSet = ImmutableSet.copyOf(productSet);
+    }
+
+    @Override public void execute(Context x, boolean execute) throws Exception {
+      if (execute) {
+        // use Babel parser
+        final SqlParser.ConfigBuilder parserConfig =
+            SqlParser.configBuilder()
+                .setParserFactory(SqlBabelParserImpl.FACTORY);
+
+        // use Babel conformance for validation
+        final Properties properties = new Properties();
+        properties.setProperty(CalciteConnectionProperty.CONFORMANCE.name(),
+            SqlConformanceEnum.BABEL.name());
+        final CalciteConnectionConfig connectionConfig =
+            new CalciteConnectionConfigImpl(properties);
+
+        // extract named schema from connection and use it in planner
+        final CalciteConnection calciteConnection =
+            x.connection().unwrap(CalciteConnection.class);
+        final String schemaName = calciteConnection.getSchema();
+        final SchemaPlus schema =
+            schemaName != null
+                ? calciteConnection.getRootSchema().getSubSchema(schemaName)
+                : calciteConnection.getRootSchema();
+        final Frameworks.ConfigBuilder config =
+            Frameworks.newConfigBuilder()
+                .defaultSchema(schema)
+                .parserConfig(parserConfig.build())
+                .context(Contexts.of(connectionConfig));
+
+        // parse, validate and un-parse
+        final Quidem.SqlCommand sqlCommand = x.previousSqlCommand();
+        final Planner planner = Frameworks.getPlanner(config.build());
+        final SqlNode node = planner.parse(sqlCommand.sql);
+        final SqlNode validateNode = planner.validate(node);
+        final SqlWriter sqlWriter =
+            new SqlPrettyWriter(CalciteSqlDialect.DEFAULT);
+        validateNode.unparse(sqlWriter, 0, 0);
+        x.echo(ImmutableList.of(sqlWriter.toSqlString().getSql()));
+      } else {
+        x.echo(content);
+      }
+      x.echo(lines);
+    }
+  }
+
+  /** Command handler that adds a "!explain-validated-on dialect..." command
+   * (see {@link ExplainValidatedCommand}). */
+  private static class BabelCommandHandler implements CommandHandler {
+    @Override public Command parseCommand(List<String> lines,
+        List<String> content, String line) {
+      final String prefix = "explain-validated-on";
+      if (line.startsWith(prefix)) {
+        final Pattern pattern =
+            Pattern.compile("explain-validated-on( [-_+a-zA-Z0-9]+)*?");
+        final Matcher matcher = pattern.matcher(line);
+        if (matcher.matches()) {
+          final ImmutableSet.Builder<String> set = ImmutableSet.builder();
+          for (int i = 0; i < matcher.groupCount(); i++) {
+            set.add(matcher.group(i + 1));
+          }
+          return new ExplainValidatedCommand(lines, content, set.build());
+        }
+      }
+      return null;
+    }
+  }
+}
+
+// End BabelQuidemTest.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/test/java/org/apache/calcite/test/BabelTest.java
----------------------------------------------------------------------
diff --git a/babel/src/test/java/org/apache/calcite/test/BabelTest.java b/babel/src/test/java/org/apache/calcite/test/BabelTest.java
new file mode 100644
index 0000000..5a21749
--- /dev/null
+++ b/babel/src/test/java/org/apache/calcite/test/BabelTest.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.test;
+
+import org.apache.calcite.config.CalciteConnectionProperty;
+import org.apache.calcite.sql.parser.babel.SqlBabelParserImpl;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Unit tests for Babel framework.
+ */
+public class BabelTest {
+
+  static final String URL = "jdbc:calcite:";
+
+  @Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  static Connection connect() throws SQLException {
+    return DriverManager.getConnection(URL,
+        CalciteAssert.propBuilder()
+            .set(CalciteConnectionProperty.PARSER_FACTORY,
+                SqlBabelParserImpl.class.getName() + "#FACTORY")
+            .build());
+  }
+
+  @Test public void testFoo() {
+    assertThat(1 + 1, is(2));
+  }
+}
+
+// End BabelTest.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/test/resources/sql/dummy.iq
----------------------------------------------------------------------
diff --git a/babel/src/test/resources/sql/dummy.iq b/babel/src/test/resources/sql/dummy.iq
new file mode 100755
index 0000000..e5aa269
--- /dev/null
+++ b/babel/src/test/resources/sql/dummy.iq
@@ -0,0 +1,27 @@
+# dummy.iq
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+!use scott
+!set outputformat mysql
+
+# VALUES as top-level (not Oracle)
+VALUES 1 + 2;
+
+VALUES ROW(1 + 2)
+!explain-validated-on calcite postgres
+
+# End dummy.iq

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/babel/src/test/resources/sql/select.iq
----------------------------------------------------------------------
diff --git a/babel/src/test/resources/sql/select.iq b/babel/src/test/resources/sql/select.iq
new file mode 100755
index 0000000..ef692dc
--- /dev/null
+++ b/babel/src/test/resources/sql/select.iq
@@ -0,0 +1,54 @@
+# select.iq - Babel test for non-standard clauses in SELECT
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+!use scott
+!set outputformat mysql
+
+# ORDER BY column not in SELECT clause
+SELECT ename
+FROM emp, dept
+ORDER BY emp.deptno;
+
+SELECT "EMP"."ENAME"
+FROM "scott"."EMP" AS "EMP",
+        "scott"."DEPT" AS "DEPT"
+ORDER BY "EMP"."DEPTNO"
+!explain-validated-on all
+
+# Test CONNECT BY (Oracle only)
+!if (false) {
+SELECT *
+FROM emp
+START WITH mgr IS NULL
+CONNECT BY empno = PRIOR mgr;
+select(...)
+!explain-validated-on oracle
+!}
+
+# WITH RECURSIVE (Oracle, MySQL 8 onwards)
+!if (false) {
+WITH RECURSIVE t(n) AS (
+    VALUES (1)
+  UNION ALL
+    SELECT n+1 FROM t WHERE n < 100
+)
+SELECT sum(n) FROM t;
+select(...)
+!explain-validated-on mysql8+ oracle
+!}
+
+# End select.iq

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
index 48079eb..122b39e 100644
--- a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
+++ b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
@@ -754,6 +754,9 @@ public interface CalciteResource {
 
   @BaseMessage("Type ''{0}'' not found")
   ExInst<SqlValidatorException> typeNotFound(String name);
+
+  @BaseMessage("Dialect does not support feature: ''{0}''")
+  ExInst<SqlValidatorException> dialectDoesNotSupportFeature(String featureName);
 }
 
 // End CalciteResource.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/main/java/org/apache/calcite/sql/validate/SqlAbstractConformance.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlAbstractConformance.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlAbstractConformance.java
index c4d0f2d..059127b 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlAbstractConformance.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlAbstractConformance.java
@@ -23,6 +23,10 @@ package org.apache.calcite.sql.validate;
  * and behaves the same as in {@link SqlConformanceEnum#DEFAULT}.
  */
 public abstract class SqlAbstractConformance implements SqlConformance {
+  public boolean isLiberal() {
+    return SqlConformanceEnum.DEFAULT.isLiberal();
+  }
+
   public boolean isGroupByAlias() {
     return SqlConformanceEnum.DEFAULT.isGroupByAlias();
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/main/java/org/apache/calcite/sql/validate/SqlConformance.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlConformance.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlConformance.java
index 84eee35..9fa0f5e 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlConformance.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlConformance.java
@@ -62,10 +62,17 @@ public interface SqlConformance {
   SqlConformanceEnum PRAGMATIC_2003 = SqlConformanceEnum.PRAGMATIC_2003;
 
   /**
+   * Whether this dialect supports features from a wide variety of
+   * dialects. This is enabled for the Babel parser, disabled otherwise.
+   */
+  boolean isLiberal();
+
+  /**
    * Whether to allow aliases from the {@code SELECT} clause to be used as
    * column names in the {@code GROUP BY} clause.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5};
    * false otherwise.
@@ -77,6 +84,7 @@ public interface SqlConformance {
    * in the select list'.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5};
    * false otherwise.
@@ -88,6 +96,7 @@ public interface SqlConformance {
    * column names in the {@code HAVING} clause.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5};
    * false otherwise.
@@ -100,6 +109,7 @@ public interface SqlConformance {
    *
    * <p>Among the built-in conformance levels, true in
    * {@link SqlConformanceEnum#DEFAULT},
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5},
    * {@link SqlConformanceEnum#ORACLE_10},
@@ -118,6 +128,7 @@ public interface SqlConformance {
    *
    * <p>Among the built-in conformance levels, true in
    * {@link SqlConformanceEnum#DEFAULT},
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5},
    * {@link SqlConformanceEnum#ORACLE_10},
@@ -156,6 +167,7 @@ public interface SqlConformance {
    * the parser.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5},
    * {@link SqlConformanceEnum#ORACLE_10};
@@ -169,6 +181,7 @@ public interface SqlConformance {
    * {@code mod} function.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5};
    * false otherwise.
@@ -180,6 +193,7 @@ public interface SqlConformance {
    * the parser.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#ORACLE_10};
    * {@link SqlConformanceEnum#ORACLE_12};
@@ -207,6 +221,7 @@ public interface SqlConformance {
    * </ul>
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#SQL_SERVER_2008};
    * {@link SqlConformanceEnum#ORACLE_12};
@@ -228,6 +243,7 @@ public interface SqlConformance {
    * column is not declared {@code NOT NULL}.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#PRAGMATIC_99},
    * {@link SqlConformanceEnum#PRAGMATIC_2003};
@@ -254,6 +270,7 @@ public interface SqlConformance {
    * not.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5};
    * false otherwise.
@@ -293,6 +310,7 @@ public interface SqlConformance {
    * </blockquote>
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT};
    * false otherwise.
    */
@@ -308,6 +326,7 @@ public interface SqlConformance {
    * <p>MySQL and CUBRID allow this behavior.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5};
    * false otherwise.
@@ -318,6 +337,7 @@ public interface SqlConformance {
    * Whether to allow geo-spatial extensions, including the GEOMETRY type.
    *
    * <p>Among the built-in conformance levels, true in
+   * {@link SqlConformanceEnum#BABEL},
    * {@link SqlConformanceEnum#LENIENT},
    * {@link SqlConformanceEnum#MYSQL_5},
    * {@link SqlConformanceEnum#SQL_SERVER_2008};

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/main/java/org/apache/calcite/sql/validate/SqlConformanceEnum.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlConformanceEnum.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlConformanceEnum.java
index c52d39c..192e58b 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlConformanceEnum.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlConformanceEnum.java
@@ -23,9 +23,14 @@ public enum SqlConformanceEnum implements SqlConformance {
   /** Calcite's default SQL behavior. */
   DEFAULT,
 
-  /** Conformance value that allows just about everything. */
+  /** Conformance value that allows just about everything supported by
+   * Calcite. */
   LENIENT,
 
+  /** Conformance value that allows anything supported by any dialect.
+   * Even more liberal than {@link #LENIENT}. */
+  BABEL,
+
   /** Conformance value that instructs Calcite to use SQL semantics strictly
    * consistent with the SQL:92 standard. */
   STRICT_92,
@@ -66,8 +71,18 @@ public enum SqlConformanceEnum implements SqlConformance {
    * consistent with Microsoft SQL Server version 2008. */
   SQL_SERVER_2008;
 
+  public boolean isLiberal() {
+    switch (this) {
+    case BABEL:
+      return true;
+    default:
+      return false;
+    }
+  }
+
   public boolean isGroupByAlias() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
       return true;
@@ -78,6 +93,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean isGroupByOrdinal() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
       return true;
@@ -88,6 +104,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean isHavingAlias() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
       return true;
@@ -99,6 +116,7 @@ public enum SqlConformanceEnum implements SqlConformance {
   public boolean isSortByOrdinal() {
     switch (this) {
     case DEFAULT:
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
     case ORACLE_10:
@@ -116,6 +134,7 @@ public enum SqlConformanceEnum implements SqlConformance {
   public boolean isSortByAlias() {
     switch (this) {
     case DEFAULT:
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
     case ORACLE_10:
@@ -148,6 +167,7 @@ public enum SqlConformanceEnum implements SqlConformance {
   public boolean isBangEqualAllowed() {
     switch (this) {
     case LENIENT:
+    case BABEL:
     case MYSQL_5:
     case ORACLE_10:
     case ORACLE_12:
@@ -159,6 +179,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   @Override public boolean isMinusAllowed() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case ORACLE_10:
     case ORACLE_12:
@@ -170,6 +191,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   @Override public boolean isPercentRemainderAllowed() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
       return true;
@@ -180,6 +202,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean isApplyAllowed() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case SQL_SERVER_2008:
     case ORACLE_12:
@@ -191,6 +214,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean isInsertSubsetColumnsAllowed() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case PRAGMATIC_99:
     case PRAGMATIC_2003:
@@ -202,6 +226,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean allowNiladicParentheses() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
       return true;
@@ -222,6 +247,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean allowExtend() {
     switch (this) {
+    case BABEL:
     case LENIENT:
       return true;
     default:
@@ -231,6 +257,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean isLimitStartCountAllowed() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
       return true;
@@ -241,6 +268,7 @@ public enum SqlConformanceEnum implements SqlConformance {
 
   public boolean allowGeometry() {
     switch (this) {
+    case BABEL:
     case LENIENT:
     case MYSQL_5:
     case SQL_SERVER_2008:

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
----------------------------------------------------------------------
diff --git a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
index d1ea199..bf83769 100644
--- a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
+++ b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
@@ -245,4 +245,5 @@ ViewExists=View ''{0}'' already exists and REPLACE not specified
 SchemaNotFound=Schema ''{0}'' not found
 ViewNotFound=View ''{0}'' not found
 TypeNotFound=Type ''{0}'' not found
+DialectDoesNotSupportFeature=Dialect does not support feature: ''{0}''
 # End CalciteResource.properties

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/CalciteAssert.java b/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
index 9056ecc..171fed4 100644
--- a/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
+++ b/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
@@ -670,35 +670,31 @@ public class CalciteAssert {
   }
 
   public static SchemaPlus addSchema(SchemaPlus rootSchema, SchemaSpec schema) {
-    SchemaPlus foodmart;
-    SchemaPlus jdbcScott;
+    final SchemaPlus foodmart;
+    final SchemaPlus jdbcScott;
     final ConnectionSpec cs;
     final DataSource dataSource;
     switch (schema) {
     case REFLECTIVE_FOODMART:
-      return rootSchema.add("foodmart",
+      return rootSchema.add(schema.schemaName,
           new ReflectiveSchema(new JdbcTest.FoodmartSchema()));
     case JDBC_SCOTT:
       cs = DatabaseInstance.HSQLDB.scott;
       dataSource = JdbcSchema.dataSource(cs.url, cs.driver, cs.username,
           cs.password);
-      return rootSchema.add("JDBC_SCOTT",
-          JdbcSchema.create(rootSchema, "JDBC_SCOTT", dataSource, cs.catalog,
-              cs.schema));
+      return rootSchema.add(schema.schemaName,
+          JdbcSchema.create(rootSchema, schema.schemaName, dataSource,
+              cs.catalog, cs.schema));
     case JDBC_FOODMART:
       cs = DB.foodmart;
       dataSource =
           JdbcSchema.dataSource(cs.url, cs.driver, cs.username, cs.password);
-      return rootSchema.add("foodmart",
-          JdbcSchema.create(rootSchema, "foodmart", dataSource, cs.catalog,
-              cs.schema));
+      return rootSchema.add(schema.schemaName,
+          JdbcSchema.create(rootSchema, schema.schemaName, dataSource,
+              cs.catalog, cs.schema));
     case JDBC_FOODMART_WITH_LATTICE:
-      foodmart = rootSchema.getSubSchema("foodmart");
-      if (foodmart == null) {
-        foodmart =
-            CalciteAssert.addSchema(rootSchema, SchemaSpec.JDBC_FOODMART);
-      }
-      foodmart.add("lattice",
+      foodmart = addSchemaIfNotExists(rootSchema, SchemaSpec.JDBC_FOODMART);
+      foodmart.add(schema.schemaName,
           Lattice.create(foodmart.unwrap(CalciteSchema.class),
               "select 1 from \"foodmart\".\"sales_fact_1997\" as s\n"
                   + "join \"foodmart\".\"time_by_day\" as t using (\"time_id\")\n"
@@ -708,23 +704,16 @@ public class CalciteAssert {
               true));
       return foodmart;
     case SCOTT:
-      jdbcScott = rootSchema.getSubSchema("jdbc_scott");
-      if (jdbcScott == null) {
-        jdbcScott =
-            CalciteAssert.addSchema(rootSchema, SchemaSpec.JDBC_SCOTT);
-      }
-      return rootSchema.add("scott", new CloneSchema(jdbcScott));
+      jdbcScott = addSchemaIfNotExists(rootSchema, SchemaSpec.JDBC_SCOTT);
+      return rootSchema.add(schema.schemaName, new CloneSchema(jdbcScott));
     case CLONE_FOODMART:
-      foodmart = rootSchema.getSubSchema("foodmart");
-      if (foodmart == null) {
-        foodmart =
-            CalciteAssert.addSchema(rootSchema, SchemaSpec.JDBC_FOODMART);
-      }
+      foodmart = addSchemaIfNotExists(rootSchema, SchemaSpec.JDBC_FOODMART);
       return rootSchema.add("foodmart2", new CloneSchema(foodmart));
     case GEO:
       ModelHandler.addFunctions(rootSchema, null, ImmutableList.of(),
           GeoFunctions.class.getName(), "*", true);
-      final SchemaPlus s = rootSchema.add("GEO", new AbstractSchema());
+      final SchemaPlus s =
+          rootSchema.add(schema.schemaName, new AbstractSchema());
       ModelHandler.addFunctions(s, "countries", ImmutableList.of(),
           CountriesTableFunction.class.getName(), null, false);
       final String sql = "select * from table(\"countries\"(true))";
@@ -733,21 +722,23 @@ public class CalciteAssert {
       s.add("countries", viewMacro);
       return s;
     case HR:
-      return rootSchema.add("hr",
+      return rootSchema.add(schema.schemaName,
           new ReflectiveSchema(new JdbcTest.HrSchema()));
     case LINGUAL:
-      return rootSchema.add("SALES",
+      return rootSchema.add(schema.schemaName,
           new ReflectiveSchema(new JdbcTest.LingualSchema()));
     case BLANK:
-      return rootSchema.add("BLANK", new AbstractSchema());
+      return rootSchema.add(schema.schemaName, new AbstractSchema());
     case ORINOCO:
-      final SchemaPlus orinoco = rootSchema.add("ORINOCO", new AbstractSchema());
+      final SchemaPlus orinoco =
+          rootSchema.add(schema.schemaName, new AbstractSchema());
       orinoco.add("ORDERS",
           new StreamTest.OrdersHistoryTable(
               StreamTest.OrdersStreamTableFactory.getRowList()));
       return orinoco;
     case POST:
-      final SchemaPlus post = rootSchema.add("POST", new AbstractSchema());
+      final SchemaPlus post =
+          rootSchema.add(schema.schemaName, new AbstractSchema());
       post.add("EMP",
           ViewTable.viewMacro(post,
               "select * from (values\n"
@@ -789,6 +780,15 @@ public class CalciteAssert {
     }
   }
 
+  private static SchemaPlus addSchemaIfNotExists(SchemaPlus rootSchema,
+        SchemaSpec schemaSpec) {
+    final SchemaPlus schema = rootSchema.getSubSchema(schemaSpec.schemaName);
+    if (schema != null) {
+      return schema;
+    }
+    return addSchema(rootSchema, schemaSpec);
+  }
+
   /**
    * Asserts that two objects are equal. If they are not, an
    * {@link AssertionError} is thrown with the given message. If
@@ -909,6 +909,12 @@ public class CalciteAssert {
           connectionFactory.with(new AddSchemaPostProcessor(name, schema)));
     }
 
+    /** Sets the default schema of the connection. Schema name may be null. */
+    public AssertThat withDefaultSchema(String schema) {
+      return new AssertThat(
+          connectionFactory.with(new DefaultSchemaPostProcessor(schema)));
+    }
+
     public AssertThat with(ConnectionPostProcessor postProcessor) {
       return new AssertThat(connectionFactory.with(postProcessor));
     }
@@ -1032,12 +1038,6 @@ public class CalciteAssert {
       }
     }
 
-    public AssertThat withDefaultSchema(String schema) {
-      return new AssertThat(
-          connectionFactory.with(
-              new AddSchemaPostProcessor(schema, null)));
-    }
-
     /** Use sparingly. Does not close the connection. */
     public Connection connect() throws SQLException {
       return connectionFactory.createConnection();
@@ -1100,8 +1100,8 @@ public class CalciteAssert {
     private final Schema schema;
 
     public AddSchemaPostProcessor(String name, Schema schema) {
-      this.name = name;
-      this.schema = schema;
+      this.name = Objects.requireNonNull(name);
+      this.schema = Objects.requireNonNull(schema);
     }
 
     public Connection apply(Connection connection) throws SQLException {
@@ -1115,6 +1115,21 @@ public class CalciteAssert {
     }
   }
 
+  /** Sets a default schema name. */
+  public static class DefaultSchemaPostProcessor
+      implements ConnectionPostProcessor {
+    private final String name;
+
+    public DefaultSchemaPostProcessor(String name) {
+      this.name = name;
+    }
+
+    public Connection apply(Connection connection) throws SQLException {
+      connection.setSchema(name);
+      return connection;
+    }
+  }
+
   /** Adds {@link SchemaSpec} (set of schemes) to a connection. */
   public static class AddSchemaSpecPostProcessor
       implements ConnectionPostProcessor {
@@ -1135,9 +1150,7 @@ public class CalciteAssert {
       default:
         addSchema(rootSchema, schemaSpec);
       }
-      if (schemaSpec == SchemaSpec.CLONE_FOODMART) {
-        con.setSchema("foodmart2");
-      }
+      con.setSchema(schemaSpec.schemaName);
       return connection;
     }
   }
@@ -1755,18 +1768,26 @@ public class CalciteAssert {
 
   /** Specification for common test schemas. */
   public enum SchemaSpec {
-    REFLECTIVE_FOODMART,
-    JDBC_FOODMART,
-    CLONE_FOODMART,
-    JDBC_FOODMART_WITH_LATTICE,
-    GEO,
-    HR,
-    JDBC_SCOTT,
-    SCOTT,
-    BLANK,
-    LINGUAL,
-    POST,
-    ORINOCO
+    REFLECTIVE_FOODMART("foodmart"),
+    JDBC_FOODMART("foodmart"),
+    CLONE_FOODMART("foodmart2"),
+    JDBC_FOODMART_WITH_LATTICE("lattice"),
+    GEO("GEO"),
+    HR("hr"),
+    JDBC_SCOTT("JDBC_SCOTT"),
+    SCOTT("scott"),
+    BLANK("BLANK"),
+    LINGUAL("SALES"),
+    POST("POST"),
+    ORINOCO("ORINOCO");
+
+    /** The name of the schema that is usually created from this specification.
+     * (Names are not unique, and you can use another name if you wish.) */
+    public final String schemaName;
+
+    SchemaSpec(String schemaName) {
+      this.schemaName = schemaName;
+    }
   }
 
   /** Converts a {@link ResultSet} to string. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java b/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
index a0a753c..3f9ec26 100644
--- a/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
+++ b/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
@@ -137,7 +137,6 @@ public class JdbcFrontJdbcBackTest {
   @Test public void testCase() {
     that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
-        .withDefaultSchema("foodmart")
         .query("select\n"
             + "  case when \"sales_fact_1997\".\"promotion_id\" = 1 then 0\n"
             + "  else \"sales_fact_1997\".\"store_sales\" end as \"c0\"\n"

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/core/src/test/java/org/apache/calcite/test/QuidemTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/QuidemTest.java b/core/src/test/java/org/apache/calcite/test/QuidemTest.java
index e70c7e9..6bf727f 100644
--- a/core/src/test/java/org/apache/calcite/test/QuidemTest.java
+++ b/core/src/test/java/org/apache/calcite/test/QuidemTest.java
@@ -35,6 +35,7 @@ import org.apache.calcite.util.Util;
 import com.google.common.collect.Lists;
 import com.google.common.io.PatternFilenameFilter;
 
+import net.hydromatic.quidem.CommandHandler;
 import net.hydromatic.quidem.Quidem;
 
 import org.junit.Test;
@@ -152,7 +153,11 @@ public abstract class QuidemTest {
     try (final Reader reader = Util.reader(inFile);
          final Writer writer = Util.printWriter(outFile);
          final Closer closer = new Closer()) {
-      new Quidem(reader, writer, QuidemTest::getEnv, createConnectionFactory())
+      final Quidem.Config config = Quidem.configBuilder()
+          .withReader(reader)
+          .withWriter(writer)
+          .withConnectionFactory(createConnectionFactory())
+          .withCommandHandler(createCommandHandler())
           .withPropertyHandler((propertyName, value) -> {
             if (propertyName.equals("bindable")) {
               final boolean b = value instanceof Boolean
@@ -165,7 +170,9 @@ public abstract class QuidemTest {
               closer.add(Prepare.THREAD_EXPAND.push(b));
             }
           })
-          .execute();
+          .withEnv(QuidemTest::getEnv)
+          .build();
+      new Quidem(config).execute();
     }
     final String diff = DiffTestCase.diff(inFile, outFile);
     if (!diff.isEmpty()) {
@@ -174,6 +181,11 @@ public abstract class QuidemTest {
     }
   }
 
+  /** Creates a command handler. */
+  protected CommandHandler createCommandHandler() {
+    return Quidem.EMPTY_COMMAND_HANDLER;
+  }
+
   /** Creates a connection factory. */
   protected Quidem.ConnectionFactory createConnectionFactory() {
     return new QuidemConnectionFactory();
@@ -246,7 +258,6 @@ public abstract class QuidemTest {
         return CalciteAssert.that()
             .with(CalciteAssert.Config.REGULAR)
             .with(CalciteAssert.SchemaSpec.POST)
-            .withDefaultSchema("POST")
             .connect();
       case "catchall":
         return CalciteAssert.that()
@@ -257,7 +268,6 @@ public abstract class QuidemTest {
       case "orinoco":
         return CalciteAssert.that()
             .with(CalciteAssert.SchemaSpec.ORINOCO)
-            .withDefaultSchema("ORINOCO")
             .connect();
       case "blank":
         return CalciteAssert.that()
@@ -265,7 +275,6 @@ public abstract class QuidemTest {
                 "org.apache.calcite.sql.parser.parserextensiontesting"
                     + ".ExtensionSqlParserImpl#FACTORY")
             .with(CalciteAssert.SchemaSpec.BLANK)
-            .withDefaultSchema("BLANK")
             .connect();
       case "seq":
         final Connection connection = CalciteAssert.that()

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 8ac7193..bea1327 100644
--- a/pom.xml
+++ b/pom.xml
@@ -136,6 +136,18 @@ limitations under the License.
     <xerces.version>2.9.1</xerces.version>
     <sketches.version>0.9.0</sketches.version>
     <fmpp.version>0.9.14</fmpp.version>
+
+    <!-- Other properties (not version numbers) -->
+    <maven-javadoc-plugin.excludePackageNames>
+      org.apache.calcite.benchmarks.generated,
+      org.apache.calcite.sql.parser.babel,
+      org.apache.calcite.sql.parser.ddl,
+      org.apache.calcite.sql.parser.impl,
+      org.apache.calcite.sql.parser.parserextensiontesting,
+      org.apache.calcite.piglet.parser,
+      org.openjdk.jmh,org.apache.calcite.adapter.elasticsearch2
+    </maven-javadoc-plugin.excludePackageNames>
+    <maven-javadoc-plugin.link>https://docs.oracle.com/javase/9/docs/api/</maven-javadoc-plugin.link>
   </properties>
 
   <issueManagement>
@@ -151,6 +163,7 @@ limitations under the License.
   </scm>
 
   <modules>
+    <module>babel</module>
     <module>cassandra</module>
     <module>core</module>
     <module>druid</module>
@@ -720,9 +733,9 @@ limitations under the License.
         <configuration>
           <additionalparam>-html5</additionalparam>
           <links>
-            <link>https://docs.oracle.com/javase/9/docs/api/</link>
+            <link>${maven-javadoc-plugin.link}</link>
           </links>
-          <excludePackageNames>org.apache.calcite.benchmarks.generated,org.apache.calcite.sql.parser.ddl,org.apache.calcite.sql.parser.impl,org.apache.calcite.sql.parser.parserextensiontesting,org.apache.calcite.piglet.parser,org.openjdk.jmh,org.apache.calcite.adapter.elasticsearch2</excludePackageNames>
+          <excludePackageNames>${maven-javadoc-plugin.excludePackageNames}</excludePackageNames>
           <show>private</show>
         </configuration>
       </plugin>
@@ -960,9 +973,9 @@ limitations under the License.
         <version>${maven-javadoc-plugin.version}</version>
         <configuration>
           <links>
-            <link>https://docs.oracle.com/javase/8/docs/api/</link>
+            <link>${maven-javadoc-plugin.link}</link>
           </links>
-          <excludePackageNames>org.apache.calcite.benchmarks.generated,org.apache.calcite.sql.parser.ddl,org.apache.calcite.sql.parser.impl,org.apache.calcite.sql.parser.parserextensiontesting,org.apache.calcite.piglet.parser,org.openjdk.jmh,org.apache.calcite.adapter.elasticsearch2</excludePackageNames>
+          <excludePackageNames>${maven-javadoc-plugin.excludePackageNames}</excludePackageNames>
           <notimestamp>true</notimestamp>
           <windowtitle>Apache Calcite API</windowtitle>
         </configuration>

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/server/src/test/resources/sql/materialized_view.iq
----------------------------------------------------------------------
diff --git a/server/src/test/resources/sql/materialized_view.iq b/server/src/test/resources/sql/materialized_view.iq
index e587313..0e02a18 100644
--- a/server/src/test/resources/sql/materialized_view.iq
+++ b/server/src/test/resources/sql/materialized_view.iq
@@ -93,12 +93,12 @@ drop materialized view if exists v;
 
 # Create materialized view without AS - fails
 create materialized view d;
-Encountered "<EOF>" at line 1, column 27.
+Encountered "<EOF>" at line 1, column 26.
 !error
 
 # Create materialized view without AS - fails
 create materialized view d (x, y);
-Encountered "<EOF>" at line 1, column 34.
+Encountered "<EOF>" at line 1, column 33.
 !error
 
 # Create materialized view without AS - fails

http://git-wip-us.apache.org/repos/asf/calcite/blob/3e50a532/server/src/test/resources/sql/schema.iq
----------------------------------------------------------------------
diff --git a/server/src/test/resources/sql/schema.iq b/server/src/test/resources/sql/schema.iq
index 65c6396..82ad470 100755
--- a/server/src/test/resources/sql/schema.iq
+++ b/server/src/test/resources/sql/schema.iq
@@ -91,7 +91,7 @@ Encountered "library" at line 1, column 18.
 !error
 
 create foreign schema fs;
-Encountered "<EOF>" at line 1, column 25.
+Encountered "<EOF>" at line 1, column 24.
 Was expecting one of:
     "TYPE" ...
     "LIBRARY" ...


[03/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/test/java/org/apache/calcite/linq4j/test/Linq4jTest.java
----------------------------------------------------------------------
diff --git a/linq4j/src/test/java/org/apache/calcite/linq4j/test/Linq4jTest.java b/linq4j/src/test/java/org/apache/calcite/linq4j/test/Linq4jTest.java
index fb24043..8f76c1b 100644
--- a/linq4j/src/test/java/org/apache/calcite/linq4j/test/Linq4jTest.java
+++ b/linq4j/src/test/java/org/apache/calcite/linq4j/test/Linq4jTest.java
@@ -77,68 +77,28 @@ import static org.junit.Assert.fail;
  * Tests for LINQ4J.
  */
 public class Linq4jTest {
-  public static final Function1<Employee, String> EMP_NAME_SELECTOR =
-      new Function1<Employee, String>() {
-        public String apply(Employee employee) {
-          return employee.name;
-        }
-      };
+  public static final Function1<Employee, String> EMP_NAME_SELECTOR = employee -> employee.name;
 
   public static final Function1<Employee, Integer> EMP_DEPTNO_SELECTOR =
-      new Function1<Employee, Integer>() {
-        public Integer apply(Employee employee) {
-          return employee.deptno;
-        }
-      };
+      employee -> employee.deptno;
 
-  public static final Function1<Employee, Integer> EMP_EMPNO_SELECTOR =
-      new Function1<Employee, Integer>() {
-        public Integer apply(Employee employee) {
-          return employee.empno;
-        }
-      };
+  public static final Function1<Employee, Integer> EMP_EMPNO_SELECTOR = employee -> employee.empno;
 
   public static final Function1<Department, Enumerable<Employee>> DEPT_EMPLOYEES_SELECTOR =
-      new Function1<Department, Enumerable<Employee>>() {
-        public Enumerable<Employee> apply(Department a0) {
-          return Linq4j.asEnumerable(a0.employees);
-        }
-      };
+      a0 -> Linq4j.asEnumerable(a0.employees);
 
   public static final Function1<Department, String> DEPT_NAME_SELECTOR =
-      new Function1<Department, String>() {
-        public String apply(Department department) {
-          return department.name;
-        }
-      };
+      department -> department.name;
 
   public static final Function1<Department, Integer> DEPT_DEPTNO_SELECTOR =
-      new Function1<Department, Integer>() {
-        public Integer apply(Department department) {
-          return department.deptno;
-        }
-      };
+      department -> department.deptno;
 
   public static final IntegerFunction1<Department> DEPT_DEPTNO_SELECTOR2 =
-      new IntegerFunction1<Department>() {
-        public int apply(Department department) {
-          return department.deptno;
-        }
-      };
+      department -> department.deptno;
 
-  public static final Function1<Object, Integer> ONE_SELECTOR =
-      new Function1<Object, Integer>() {
-        public Integer apply(Object employee) {
-          return 1;
-        }
-      };
+  public static final Function1<Object, Integer> ONE_SELECTOR = employee -> 1;
 
-  private static final Function2<Object, Object, Integer> PAIR_SELECTOR =
-      new Function2<Object, Object, Integer>() {
-        public Integer apply(Object employee, Object v2) {
-          return 1;
-        }
-      };
+  private static final Function2<Object, Object, Integer> PAIR_SELECTOR = (employee, v2) -> 1;
 
   @Test public void testSelect() {
     List<String> names =
@@ -151,12 +111,7 @@ public class Linq4jTest {
   @Test public void testWhere() {
     List<String> names =
         Linq4j.asEnumerable(emps)
-            .where(
-                new Predicate1<Employee>() {
-                  public boolean apply(Employee employee) {
-                    return employee.deptno < 15;
-                  }
-                })
+            .where(employee -> employee.deptno < 15)
             .select(EMP_NAME_SELECTOR)
             .toList();
     assertEquals("[Fred, Eric, Janet]", names.toString());
@@ -166,12 +121,7 @@ public class Linq4jTest {
     // Returns every other employee.
     List<String> names =
         Linq4j.asEnumerable(emps)
-            .where(
-                new Predicate2<Employee, Integer>() {
-                  public boolean apply(Employee employee, Integer n) {
-                    return n % 2 == 0;
-                  }
-                })
+            .where((employee, n) -> n % 2 == 0)
             .select(EMP_NAME_SELECTOR)
             .toList();
     assertEquals("[Fred, Eric]", names.toString());
@@ -181,12 +131,7 @@ public class Linq4jTest {
     final List<String> nameSeqs =
         Linq4j.asEnumerable(depts)
             .selectMany(DEPT_EMPLOYEES_SELECTOR)
-            .select(
-                new Function2<Employee, Integer, String>() {
-                  public String apply(Employee v1, Integer v2) {
-                    return "#" + v2 + ": " + v1.name;
-                  }
-                })
+            .select((v1, v2) -> "#" + v2 + ": " + v1.name)
             .toList();
     assertEquals(
         "[#0: Fred, #1: Eric, #2: Janet, #3: Bill]", nameSeqs.toString());
@@ -199,12 +144,7 @@ public class Linq4jTest {
 
   @Test public void testCountPredicate() {
     final int count =
-        Linq4j.asEnumerable(depts).count(
-            new Predicate1<Department>() {
-              public boolean apply(Department v1) {
-                return v1.employees.size() > 0;
-              }
-            });
+        Linq4j.asEnumerable(depts).count(v1 -> v1.employees.size() > 0);
     assertEquals(2, count);
   }
 
@@ -215,27 +155,14 @@ public class Linq4jTest {
 
   @Test public void testLongCountPredicate() {
     final long count =
-        Linq4j.asEnumerable(depts).longCount(
-            new Predicate1<Department>() {
-              public boolean apply(Department v1) {
-                return v1.employees.size() > 0;
-              }
-            });
+        Linq4j.asEnumerable(depts).longCount(v1 -> v1.employees.size() > 0);
     assertEquals(2, count);
   }
 
   @Test public void testAllPredicate() {
-    Predicate1<Employee> allEmpnoGE100 = new Predicate1<Employee>() {
-      public boolean apply(Employee emp) {
-        return emp.empno >= 100;
-      }
-    };
+    Predicate1<Employee> allEmpnoGE100 = emp -> emp.empno >= 100;
 
-    Predicate1<Employee> allEmpnoGT100 = new Predicate1<Employee>() {
-      public boolean apply(Employee emp) {
-        return emp.empno > 100;
-      }
-    };
+    Predicate1<Employee> allEmpnoGT100 = emp -> emp.empno > 100;
 
     assertTrue(Linq4j.asEnumerable(emps).all(allEmpnoGE100));
     assertFalse(Linq4j.asEnumerable(emps).all(allEmpnoGT100));
@@ -248,17 +175,9 @@ public class Linq4jTest {
   }
 
   @Test public void testAnyPredicate() {
-    Predicate1<Department> deptoNameIT = new Predicate1<Department>() {
-      public boolean apply(Department v1) {
-        return v1.name != null && v1.name.equals("IT");
-      }
-    };
+    Predicate1<Department> deptoNameIT = v1 -> v1.name != null && v1.name.equals("IT");
 
-    Predicate1<Department> deptoNameSales = new Predicate1<Department>() {
-      public boolean apply(Department v1) {
-        return v1.name != null && v1.name.equals("Sales");
-      }
-    };
+    Predicate1<Department> deptoNameSales = v1 -> v1.name != null && v1.name.equals("Sales");
 
     assertFalse(Linq4j.asEnumerable(depts).any(deptoNameIT));
     assertTrue(Linq4j.asEnumerable(depts).any(deptoNameSales));
@@ -315,11 +234,7 @@ public class Linq4jTest {
             .select(DEPT_NAME_SELECTOR)
             .aggregate(
                 null,
-                new Function2<String, String, String>() {
-                  public String apply(String v1, String v2) {
-                    return v1 == null ? v2 : v1 + "," + v2;
-                  }
-                }));
+                (Function2<String, String, String>) (v1, v2) -> v1 == null ? v2 : v1 + "," + v2));
   }
 
   @Test public void testToMap() {
@@ -333,15 +248,16 @@ public class Linq4jTest {
   @Test public void testToMapWithComparer() {
     final Map<String, String> map =
         Linq4j.asEnumerable(Arrays.asList("foo", "bar", "far"))
-            .toMap(Functions.<String>identitySelector(), new EqualityComparer<String>() {
-              public boolean equal(String v1, String v2) {
-                return String.CASE_INSENSITIVE_ORDER.compare(v1, v2) == 0;
-              }
-              public int hashCode(String s) {
-                return s == null ? Objects.hashCode(null)
-                    : s.toLowerCase(Locale.ROOT).hashCode();
-              }
-            });
+            .toMap(Functions.identitySelector(),
+                new EqualityComparer<String>() {
+                  public boolean equal(String v1, String v2) {
+                    return String.CASE_INSENSITIVE_ORDER.compare(v1, v2) == 0;
+                  }
+                  public int hashCode(String s) {
+                    return s == null ? Objects.hashCode(null)
+                        : s.toLowerCase(Locale.ROOT).hashCode();
+                  }
+                });
     assertEquals(3, map.size());
     assertTrue(map.get("foo").equals("foo"));
     assertTrue(map.get("Foo").equals("foo"));
@@ -359,12 +275,8 @@ public class Linq4jTest {
   @Test public void testToMap2WithComparer() {
     final Map<String, String> map =
         Linq4j.asEnumerable(Arrays.asList("foo", "bar", "far"))
-            .toMap(Functions.<String>identitySelector(),
-                new Function1<String, String>() {
-                  public String apply(String x) {
-                    return x == null ? null : x.toUpperCase(Locale.ROOT);
-                  }
-                },
+            .toMap(Functions.identitySelector(),
+                x -> x == null ? null : x.toUpperCase(Locale.ROOT),
                 new EqualityComparer<String>() {
                   public boolean equal(String v1, String v2) {
                     return String.CASE_INSENSITIVE_ORDER.compare(v1, v2) == 0;
@@ -430,13 +342,8 @@ public class Linq4jTest {
 
     assertEquals(
         "[10:3, 30:1]",
-        lookup.applyResultSelector(
-            new Function2<Integer, Enumerable<String>, String>() {
-              public String apply(Integer v1, Enumerable<String> v2) {
-                return v1 + ":" + v2.count();
-              }
-            })
-            .orderBy(Functions.<String>identitySelector())
+        lookup.applyResultSelector((v1, v2) -> v1 + ":" + v2.count())
+            .orderBy(Functions.identitySelector())
             .toList().toString());
   }
 
@@ -538,17 +445,9 @@ public class Linq4jTest {
   }
 
   @Test public void testFirstPredicate1() {
-    Predicate1<String> startWithS = new Predicate1<String>() {
-      public boolean apply(String s) {
-        return s != null && Character.toString(s.charAt(0)).equals("S");
-      }
-    };
+    Predicate1<String> startWithS = s -> s != null && Character.toString(s.charAt(0)).equals("S");
 
-    Predicate1<Integer> numberGT15 = new Predicate1<Integer>() {
-      public boolean apply(Integer i) {
-        return i > 15;
-      }
-    };
+    Predicate1<Integer> numberGT15 = i -> i > 15;
 
     String[] people = {"Brill", "Smith", "Simpsom"};
     String[] peopleWithoutCharS = {"Brill", "Andrew", "Alice"};
@@ -578,17 +477,9 @@ public class Linq4jTest {
   }
 
   @Test public void testFirstOrDefaultPredicate1() {
-    Predicate1<String> startWithS = new Predicate1<String>() {
-      public boolean apply(String s) {
-        return s != null && Character.toString(s.charAt(0)).equals("S");
-      }
-    };
+    Predicate1<String> startWithS = s -> s != null && Character.toString(s.charAt(0)).equals("S");
 
-    Predicate1<Integer> numberGT15 = new Predicate1<Integer>() {
-      public boolean apply(Integer i) {
-        return i > 15;
-      }
-    };
+    Predicate1<Integer> numberGT15 = i -> i > 15;
 
     String[] people = {"Brill", "Smith", "Simpsom"};
     String[] peopleWithoutCharS = {"Brill", "Andrew", "Alice"};
@@ -643,17 +534,9 @@ public class Linq4jTest {
   }
 
   @Test public void testSinglePredicate1() {
-    Predicate1<String> startWithS = new Predicate1<String>() {
-      public boolean apply(String s) {
-        return s != null && Character.toString(s.charAt(0)).equals("S");
-      }
-    };
+    Predicate1<String> startWithS = s -> s != null && Character.toString(s.charAt(0)).equals("S");
 
-    Predicate1<Integer> numberGT15 = new Predicate1<Integer>() {
-      public boolean apply(Integer i) {
-        return i > 15;
-      }
-    };
+    Predicate1<Integer> numberGT15 = i -> i > 15;
 
     String[] people = {"Brill", "Smith"};
     String[] twoPeopleWithCharS = {"Brill", "Smith", "Simpson"};
@@ -697,17 +580,9 @@ public class Linq4jTest {
 
   @Test
   public void testSingleOrDefaultPredicate1() {
-    Predicate1<String> startWithS = new Predicate1<String>() {
-      public boolean apply(String s) {
-        return s != null && Character.toString(s.charAt(0)).equals("S");
-      }
-    };
+    Predicate1<String> startWithS = s -> s != null && Character.toString(s.charAt(0)).equals("S");
 
-    Predicate1<Integer> numberGT15 = new Predicate1<Integer>() {
-      public boolean apply(Integer i) {
-        return i > 15;
-      }
-    };
+    Predicate1<Integer> numberGT15 = i -> i > 15;
 
     String[] people = {"Brill", "Smith"};
     String[] twoPeopleWithCharS = {"Brill", "Smith", "Simpson"};
@@ -749,12 +624,7 @@ public class Linq4jTest {
 
   @Test public void testSelectorEqualityComparer() {
     final EqualityComparer<Employee> comparer =
-        Functions.selectorComparer(
-            new Function1<Employee, Object>() {
-              public Object apply(Employee a0) {
-                return a0.deptno;
-              }
-            });
+        Functions.selectorComparer((Function1<Employee, Object>) a0 -> a0.deptno);
     assertTrue(comparer.equal(emps[0], emps[0]));
     assertEquals(comparer.hashCode(emps[0]), comparer.hashCode(emps[0]));
 
@@ -793,7 +663,7 @@ public class Linq4jTest {
 
     StringBuilder buf = new StringBuilder();
     for (Grouping<String, Employee> grouping
-        : lookup.orderBy(Linq4jTest.<String, Employee>groupingKeyExtractor())) {
+        : lookup.orderBy(Linq4jTest.groupingKeyExtractor())) {
       buf.append(grouping).append("\n");
     }
     assertEquals(
@@ -803,11 +673,7 @@ public class Linq4jTest {
   }
 
   private static <K extends Comparable, V> Function1<Grouping<K, V>, K> groupingKeyExtractor() {
-    return new Function1<Grouping<K, V>, K>() {
-      public K apply(Grouping<K, V> a0) {
-        return a0.getKey();
-      }
-    };
+    return Grouping::getKey;
   }
 
   /**
@@ -818,20 +684,11 @@ public class Linq4jTest {
     String s =
         Linq4j.asEnumerable(emps)
             .groupBy(
-                EMP_DEPTNO_SELECTOR, new Function0<String>() {
-                  public String apply() {
-                    return null;
-                  }
-                }, new Function2<String, Employee, String>() {
-                  public String apply(String v1, Employee e0) {
-                    return v1 == null ? e0.name : (v1 + "+" + e0.name);
-                  }
-                }, new Function2<Integer, String, String>() {
-                  public String apply(Integer v1, String v2) {
-                    return v1 + ": " + v2;
-                  }
-                })
-            .orderBy(Functions.<String>identitySelector())
+                EMP_DEPTNO_SELECTOR,
+                (Function0<String>) () -> null,
+                (v1, e0) -> v1 == null ? e0.name : (v1 + "+" + e0.name),
+                (v1, v2) -> v1 + ": " + v2)
+            .orderBy(Functions.identitySelector())
             .toList()
             .toString();
     assertEquals(
@@ -849,21 +706,8 @@ public class Linq4jTest {
     String s =
         Linq4j.asEnumerable(emps)
             .aggregate(
-                new Function0<String>() {
-                  public String apply() {
-                    return null;
-                  }
-                }.apply(), //CHECKSTYLE: IGNORE 0
-                new Function2<String, Employee, String>() {
-                  public String apply(String v1, Employee e0) {
-                    return v1 == null ? e0.name : (v1 + "+" + e0.name);
-                  }
-                },
-                new Function1<String, String>() {
-                  public String apply(String v2) {
-                    return "<no key>: " + v2;
-                  }
-                });
+                ((Function0<String>) () -> null).apply(), //CHECKSTYLE: IGNORE 0
+                (v1, e0) -> v1 == null ? e0.name : (v1 + "+" + e0.name), v2 -> "<no key>: " + v2);
     assertEquals(
         "<no key>: Fred+Bill+Eric+Janet",
         s);
@@ -903,11 +747,7 @@ public class Linq4jTest {
 
   @Test public void testTransformEnumerator() {
     final List<String> strings = Arrays.asList("one", "two", "three");
-    final Function1<String, Integer> func = new Function1<String, Integer>() {
-      public Integer apply(String a0) {
-        return a0.length();
-      }
-    };
+    final Function1<String, Integer> func = String::length;
     final Enumerator<Integer> enumerator =
         Linq4j.transform(Linq4j.enumerator(strings), func);
     assertThat(enumerator.moveNext(), is(true));
@@ -919,7 +759,7 @@ public class Linq4jTest {
     assertThat(enumerator.moveNext(), is(false));
 
     final Enumerator<Integer> enumerator2 =
-        Linq4j.transform(Linq4j.<String>emptyEnumerator(), func);
+        Linq4j.transform(Linq4j.emptyEnumerator(), func);
     assertThat(enumerator2.moveNext(), is(false));
   }
 
@@ -1078,20 +918,17 @@ public class Linq4jTest {
                 Linq4j.asEnumerable(emps)
                     .concat(Linq4j.asEnumerable(badEmps)),
                 DEPT_DEPTNO_SELECTOR,
-                EMP_DEPTNO_SELECTOR,
-                new Function2<Department, Enumerable<Employee>, String>() {
-                  public String apply(Department v1, Enumerable<Employee> v2) {
-                    final StringBuilder buf = new StringBuilder("[");
-                    int n = 0;
-                    for (Employee employee : v2) {
-                      if (n++ > 0) {
-                        buf.append(", ");
-                      }
-                      buf.append(employee.name);
+                EMP_DEPTNO_SELECTOR, (v1, v2) -> {
+                  final StringBuilder buf = new StringBuilder("[");
+                  int n = 0;
+                  for (Employee employee : v2) {
+                    if (n++ > 0) {
+                      buf.append(", ");
                     }
-                    return buf.append("] work(s) in ").append(v1.name)
-                        .toString();
+                    buf.append(employee.name);
                   }
+                  return buf.append("] work(s) in ").append(v1.name)
+                      .toString();
                 })
             .toList()
             .toString();
@@ -1112,20 +949,17 @@ public class Linq4jTest {
                 Linq4j.asEnumerable(emps)
                     .concat(Linq4j.asEnumerable(badEmps)),
                 DEPT_DEPTNO_SELECTOR,
-                EMP_DEPTNO_SELECTOR,
-                new Function2<Department, Enumerable<Employee>, String>() {
-                  public String apply(Department v1, Enumerable<Employee> v2) {
-                    final StringBuilder buf = new StringBuilder("[");
-                    int n = 0;
-                    for (Employee employee : v2) {
-                      if (n++ > 0) {
-                        buf.append(", ");
-                      }
-                      buf.append(employee.name);
+                EMP_DEPTNO_SELECTOR, (v1, v2) -> {
+                  final StringBuilder buf = new StringBuilder("[");
+                  int n = 0;
+                  for (Employee employee : v2) {
+                    if (n++ > 0) {
+                      buf.append(", ");
                     }
-                    return buf.append("] work(s) in ").append(v1.name)
-                        .toString();
+                    buf.append(employee.name);
                   }
+                  return buf.append("] work(s) in ").append(v1.name)
+                      .toString();
                 },
                 new EqualityComparer<Integer>() {
                   public boolean equal(Integer v1, Integer v2) {
@@ -1150,13 +984,8 @@ public class Linq4jTest {
             .join(
                 Linq4j.asEnumerable(depts),
                 EMP_DEPTNO_SELECTOR,
-                DEPT_DEPTNO_SELECTOR,
-                new Function2<Employee, Department, String>() {
-                  public String apply(Employee v1, Department v2) {
-                    return v1.name + " works in " + v2.name;
-                  }
-                })
-            .orderBy(Functions.<String>identitySelector())
+                DEPT_DEPTNO_SELECTOR, (v1, v2) -> v1.name + " works in " + v2.name)
+            .orderBy(Functions.identitySelector())
             .toList()
             .toString();
     assertEquals(
@@ -1178,14 +1007,9 @@ public class Linq4jTest {
             .join(
                 Linq4j.asEnumerable(depts),
                 EMP_DEPTNO_SELECTOR,
-                DEPT_DEPTNO_SELECTOR,
-                new Function2<Employee, Department, String>() {
-                  public String apply(Employee v1, Department v2) {
-                    return v1.name + " works in "
-                        + (v2 == null ? null : v2.name);
-                  }
-                }, null, false, true)
-            .orderBy(Functions.<String>identitySelector())
+                DEPT_DEPTNO_SELECTOR, (v1, v2) -> v1.name + " works in "
+                    + (v2 == null ? null : v2.name), null, false, true)
+            .orderBy(Functions.identitySelector())
             .toList()
             .toString();
     assertEquals(
@@ -1208,14 +1032,9 @@ public class Linq4jTest {
             .join(
                 Linq4j.asEnumerable(depts),
                 EMP_DEPTNO_SELECTOR,
-                DEPT_DEPTNO_SELECTOR,
-                new Function2<Employee, Department, String>() {
-                  public String apply(Employee v1, Department v2) {
-                    return (v1 == null ? null : v1.name)
-                        + " works in " + (v2 == null ? null : v2.name);
-                  }
-                }, null, true, false)
-            .orderBy(Functions.<String>identitySelector())
+                DEPT_DEPTNO_SELECTOR, (v1, v2) -> (v1 == null ? null : v1.name)
+                    + " works in " + (v2 == null ? null : v2.name), null, true, false)
+            .orderBy(Functions.identitySelector())
             .toList()
             .toString();
     assertEquals(
@@ -1238,14 +1057,9 @@ public class Linq4jTest {
             .join(
                 Linq4j.asEnumerable(depts),
                 EMP_DEPTNO_SELECTOR,
-                DEPT_DEPTNO_SELECTOR,
-                new Function2<Employee, Department, String>() {
-                  public String apply(Employee v1, Department v2) {
-                    return (v1 == null ? null : v1.name)
-                        + " works in " + (v2 == null ? null : v2.name);
-                  }
-                }, null, true, true)
-            .orderBy(Functions.<String>identitySelector())
+                DEPT_DEPTNO_SELECTOR, (v1, v2) -> (v1 == null ? null : v1.name)
+                    + " works in " + (v2 == null ? null : v2.name), null, true, true)
+            .orderBy(Functions.identitySelector())
             .toList()
             .toString();
     assertEquals(
@@ -1285,19 +1099,19 @@ public class Linq4jTest {
 
     final Enumerator<List<String>> product0 =
         Linq4j.product(
-            Arrays.asList(Linq4j.<String>emptyEnumerator()));
+            Arrays.asList(Linq4j.emptyEnumerator()));
     assertFalse(product0.moveNext());
 
     final Enumerator<List<String>> productFullEmpty =
         Linq4j.product(
             Arrays.asList(
-                abc.enumerator(), Linq4j.<String>emptyEnumerator()));
+                abc.enumerator(), Linq4j.emptyEnumerator()));
     assertFalse(productFullEmpty.moveNext());
 
     final Enumerator<List<String>> productEmptyFull =
         Linq4j.product(
             Arrays.asList(
-                abc.enumerator(), Linq4j.<String>emptyEnumerator()));
+                abc.enumerator(), Linq4j.emptyEnumerator()));
     assertFalse(productEmptyFull.moveNext());
 
     final Enumerator<List<String>> productAbcXy =
@@ -1347,12 +1161,7 @@ public class Linq4jTest {
         Linq4j.asEnumerable(emps)
             .asQueryable()
             .where(
-                Expressions.lambda(
-                    new Predicate1<Employee>() {
-                      public boolean apply(Employee v1) {
-                        return v1.deptno == 10;
-                      }
-                    }));
+                Expressions.lambda(v1 -> v1.deptno == 10));
     assertEquals(3, nh2.count());
 
     // use lambda, this time call whereN
@@ -1365,7 +1174,7 @@ public class Linq4jTest {
             .asQueryable()
             .whereN(
                 Expressions.lambda(
-                    Predicate2.class,
+                    (Class<Predicate2<Employee, Integer>>) (Class) Predicate2.class,
                     Expressions.andAlso(
                         Expressions.equal(
                             Expressions.field(
@@ -1469,12 +1278,7 @@ public class Linq4jTest {
         Linq4j.asEnumerable(depts);
     final List<Department> deptList =
         EnumerableDefaults.takeWhile(
-            enumerableDepts,
-            new Predicate1<Department>() {
-              public boolean apply(Department v1) {
-                return v1.name.contains("e");
-              }
-            }).toList();
+            enumerableDepts, v1 -> v1.name.contains("e")).toList();
 
     // Only one department:
     // 0: Sales --> true
@@ -1508,11 +1312,7 @@ public class Linq4jTest {
   @Test public void testTakeWhileQueryableFunctionExpressionPredicate() {
     final Queryable<Department> queryableDepts =
         Linq4j.asEnumerable(depts).asQueryable();
-    Predicate1<Department> predicate = new Predicate1<Department>() {
-      public boolean apply(Department v1) {
-        return "HR".equals(v1.name);
-      }
-    };
+    Predicate1<Department> predicate = v1 -> "HR".equals(v1.name);
     List<Department> deptList =
         QueryableDefaults.takeWhile(
             queryableDepts, Expressions.lambda(predicate))
@@ -1520,11 +1320,7 @@ public class Linq4jTest {
 
     assertEquals(0, deptList.size());
 
-    predicate = new Predicate1<Department>() {
-      public boolean apply(Department v1) {
-        return "Sales".equals(v1.name);
-      }
-    };
+    predicate = v1 -> "Sales".equals(v1.name);
     deptList =
         QueryableDefaults.takeWhile(
             queryableDepts, Expressions.lambda(predicate))
@@ -1575,29 +1371,14 @@ public class Linq4jTest {
     assertEquals(2, Linq4j.asEnumerable(depts).skip(1).count());
     assertEquals(
         2,
-        Linq4j.asEnumerable(depts).skipWhile(
-            new Predicate1<Department>() {
-              public boolean apply(Department v1) {
-                return v1.name.equals("Sales");
-              }
-            }).count());
+        Linq4j.asEnumerable(depts).skipWhile(v1 -> v1.name.equals("Sales")).count());
     assertEquals(
         3,
-        Linq4j.asEnumerable(depts).skipWhile(
-            new Predicate1<Department>() {
-              public boolean apply(Department v1) {
-                return !v1.name.equals("Sales");
-              }
-            }).count());
+        Linq4j.asEnumerable(depts).skipWhile(v1 -> !v1.name.equals("Sales")).count());
     assertEquals(
         1,
-        Linq4j.asEnumerable(depts).skipWhile(
-            new Predicate2<Department, Integer>() {
-              public boolean apply(Department v1, Integer v2) {
-                return v1.name.equals("Sales")
-                    || v2 == 1;
-              }
-            }).count());
+        Linq4j.asEnumerable(depts).skipWhile((v1, v2) -> v1.name.equals("Sales")
+            || v2 == 1).count());
 
     assertEquals(
         2, Linq4j.asEnumerable(depts).skip(1).count());
@@ -1605,13 +1386,8 @@ public class Linq4jTest {
         0, Linq4j.asEnumerable(depts).skip(5).count());
     assertEquals(
         1,
-        Linq4j.asEnumerable(depts).skipWhile(
-            new Predicate2<Department, Integer>() {
-              public boolean apply(Department v1, Integer v2) {
-                return v1.name.equals("Sales")
-                    || v2 == 1;
-              }
-            }).count());
+        Linq4j.asEnumerable(depts).skipWhile((v1, v2) -> v1.name.equals("Sales")
+            || v2 == 1).count());
 
     assertEquals(
         2, Linq4j.asEnumerable(depts).asQueryable().skip(1).count());
@@ -1620,13 +1396,8 @@ public class Linq4jTest {
     assertEquals(
         1,
         Linq4j.asEnumerable(depts).asQueryable().skipWhileN(
-            Expressions.<Predicate2<Department, Integer>>lambda(
-                new Predicate2<Department, Integer>() {
-                  public boolean apply(Department v1, Integer v2) {
-                    return v1.name.equals("Sales")
-                        || v2 == 1;
-                  }
-                })).count());
+            Expressions.lambda((v1, v2) -> v1.name.equals("Sales")
+                || v2 == 1)).count());
   }
 
   @Test public void testOrderBy() {
@@ -1649,7 +1420,7 @@ public class Linq4jTest {
         Linq4j.asEnumerable(emps)
             .orderBy(EMP_NAME_SELECTOR)
             .orderBy(
-                EMP_DEPTNO_SELECTOR, Collections.<Integer>reverseOrder())
+                EMP_DEPTNO_SELECTOR, Collections.reverseOrder())
             .toList().toString());
   }
 
@@ -1697,12 +1468,7 @@ public class Linq4jTest {
         new Employee(130, "Janet", 10));
     final List<Employee> result = new ArrayList<>();
     Linq4j.asEnumerable(employees)
-        .where(
-            new Predicate1<Employee>() {
-              public boolean apply(Employee e) {
-                return e.name.contains("e");
-              }
-            })
+        .where(e -> e.name.contains("e"))
         .into(result);
     assertEquals(
         "[Employee(name: Fred, deptno:10), Employee(name: Janet, deptno:10)]",
@@ -1722,12 +1488,7 @@ public class Linq4jTest {
     final List<Grouping<Object, Map.Entry<Employee, Department>>> result =
         new ArrayList<>();
     Linq4j.asEnumerable(empDepts.entrySet())
-        .groupBy(
-            new Function1<Map.Entry<Employee, Department>, Object>() {
-              public Object apply(Map.Entry<Employee, Department> entry) {
-                return entry.getValue();
-              }
-            })
+        .groupBy((Function1<Map.Entry<Employee, Department>, Object>) Map.Entry::getValue)
         .into(result);
     assertNotNull(result.toString());
   }
@@ -1883,17 +1644,9 @@ public class Linq4jTest {
   @Test public void testLastWithPredicate() {
     final Enumerable<String> enumerable =
         Linq4j.asEnumerable(Arrays.asList("jimi", "mitch", "ming"));
-    assertEquals("mitch", enumerable.last(new Predicate1<String>() {
-      public boolean apply(String x) {
-        return x.startsWith("mit");
-      }
-    }));
+    assertEquals("mitch", enumerable.last(x -> x.startsWith("mit")));
     try {
-      enumerable.last(new Predicate1<String>() {
-        public boolean apply(String x) {
-          return false;
-        }
-      });
+      enumerable.last(x -> false);
       fail();
     } catch (Exception ignored) {
       // ok
@@ -1902,11 +1655,9 @@ public class Linq4jTest {
     @SuppressWarnings("unchecked")
     final Enumerable<String> emptyEnumerable = Linq4j.asEnumerable(Collections.EMPTY_LIST);
     try {
-      emptyEnumerable.last(new Predicate1<String>() {
-        public boolean apply(String x) {
-          fail();
-          return false;
-        }
+      emptyEnumerable.last(x -> {
+        fail();
+        return false;
       });
       fail();
     } catch (Exception ignored) {
@@ -1917,44 +1668,28 @@ public class Linq4jTest {
   @Test public void testLastOrDefaultWithPredicate() {
     final Enumerable<String> enumerable =
         Linq4j.asEnumerable(Arrays.asList("jimi", "mitch", "ming"));
-    assertEquals("mitch", enumerable.lastOrDefault(new Predicate1<String>() {
-      public boolean apply(String x) {
-        return x.startsWith("mit");
-      }
-    }));
-    assertNull(enumerable.lastOrDefault(new Predicate1<String>() {
-      public boolean apply(String x) {
-        return false;
-      }
-    }));
+    assertEquals("mitch", enumerable.lastOrDefault(x -> x.startsWith("mit")));
+    assertNull(enumerable.lastOrDefault(x -> false));
 
     @SuppressWarnings("unchecked")
     final Enumerable<String> emptyEnumerable = Linq4j.asEnumerable(Collections.EMPTY_LIST);
-    assertNull(emptyEnumerable.lastOrDefault(new Predicate1<String>() {
-      public boolean apply(String x) {
-        fail();
-        return false;
-      }
-    }));
+    assertNull(
+        emptyEnumerable.lastOrDefault(x -> {
+          fail();
+          return false;
+        }));
   }
 
   @Test public void testSelectManyWithIndexableSelector() {
     final int[] indexRef = new int[]{0};
     final List<String> nameSeqs =
         Linq4j.asEnumerable(depts)
-            .selectMany(new Function2<Department, Integer, Enumerable<Employee>>() {
-              public Enumerable<Employee> apply(Department element, Integer index) {
-                assertEquals(indexRef[0], index.longValue());
-                indexRef[0] = index + 1;
-                return Linq4j.asEnumerable(element.employees);
-              }
+            .selectMany((element, index) -> {
+              assertEquals(indexRef[0], index.longValue());
+              indexRef[0] = index + 1;
+              return Linq4j.asEnumerable(element.employees);
             })
-            .select(
-                new Function2<Employee, Integer, String>() {
-                  public String apply(Employee v1, Integer v2) {
-                    return "#" + v2 + ": " + v1.name;
-                  }
-                })
+            .select((v1, v2) -> "#" + v2 + ": " + v1.name)
             .toList();
     assertEquals(
         "[#0: Fred, #1: Eric, #2: Janet, #3: Bill]", nameSeqs.toString());
@@ -1964,16 +1699,8 @@ public class Linq4jTest {
     final List<String> nameSeqs =
         Linq4j.asEnumerable(depts)
             .selectMany(DEPT_EMPLOYEES_SELECTOR,
-                new Function2<Department, Employee, String>() {
-                  public String apply(Department element, Employee subElement) {
-                    return subElement.name + "@" + element.name;
-                  }
-                })
-            .select(new Function2<String, Integer, String>() {
-              public String apply(String v0, Integer v1) {
-                return "#" + v1 + ": " + v0;
-              }
-            })
+                (element, subElement) -> subElement.name + "@" + element.name)
+            .select((v0, v1) -> "#" + v1 + ": " + v0)
             .toList();
     assertEquals(
         "[#0: Fred@Sales, #1: Eric@Sales, #2: Janet@Sales, #3: Bill@Marketing]",
@@ -1984,24 +1711,12 @@ public class Linq4jTest {
     final int[] indexRef = new int[]{0};
     final List<String> nameSeqs =
         Linq4j.asEnumerable(depts)
-            .selectMany(
-                new Function2<Department, Integer, Enumerable<Employee>>() {
-                  public Enumerable<Employee> apply(Department element, Integer index) {
-                    assertEquals(indexRef[0], index.longValue());
-                    indexRef[0] = index + 1;
-                    return Linq4j.asEnumerable(element.employees);
-                  }
-                },
-                new Function2<Department, Employee, String>() {
-                  public String apply(Department element, Employee subElement) {
-                    return subElement.name + "@" + element.name;
-                  }
-                })
-            .select(new Function2<String, Integer, String>() {
-              public String apply(String v0, Integer v1) {
-                return "#" + v1 + ": " + v0;
-              }
-            })
+            .selectMany((element, index) -> {
+              assertEquals(indexRef[0], index.longValue());
+              indexRef[0] = index + 1;
+              return Linq4j.asEnumerable(element.employees);
+            }, (element, subElement) -> subElement.name + "@" + element.name)
+            .select((v0, v1) -> "#" + v1 + ": " + v0)
             .toList();
     assertEquals(
         "[#0: Fred@Sales, #1: Eric@Sales, #2: Janet@Sales, #3: Bill@Marketing]",
@@ -2036,25 +1751,14 @@ public class Linq4jTest {
   }
 
   @Test public void testSequenceEqualWithoutCollection() {
-    final Enumerable<String> enumerable1 = Linq4j.asEnumerable(new Iterable<String>() {
-      public Iterator<String> iterator() {
-        return Arrays.asList("ming", "foo", "bar").iterator();
-      }
-    });
-    final Enumerable<String> enumerable2 = Linq4j.asEnumerable(new Iterable<String>() {
-      public Iterator<String> iterator() {
-        return Arrays.asList("ming", "foo", "bar").iterator();
-      }
-    });
+    final Enumerable<String> enumerable1 = Linq4j.asEnumerable(
+        () -> Arrays.asList("ming", "foo", "bar").iterator());
+    final Enumerable<String> enumerable2 = Linq4j.asEnumerable(
+        () -> Arrays.asList("ming", "foo", "bar").iterator());
     assertTrue(enumerable1.sequenceEqual(enumerable2));
     assertFalse(
         enumerable1.sequenceEqual(
-            Linq4j.asEnumerable(
-                new Iterable<String>() {
-                  public Iterator<String> iterator() {
-                    return Arrays.asList("ming", "foo", "far").iterator();
-                  }
-                })));
+            Linq4j.asEnumerable(() -> Arrays.asList("ming", "foo", "far").iterator())));
 
     try {
       EnumerableDefaults.sequenceEqual(null, enumerable2);
@@ -2111,16 +1815,10 @@ public class Linq4jTest {
   }
 
   @Test public void testSequenceEqualWithComparerWithoutCollection() {
-    final Enumerable<String> enumerable1 = Linq4j.asEnumerable(new Iterable<String>() {
-      public Iterator<String> iterator() {
-        return Arrays.asList("ming", "foo", "bar").iterator();
-      }
-    });
-    final Enumerable<String> enumerable2 = Linq4j.asEnumerable(new Iterable<String>() {
-      public Iterator<String> iterator() {
-        return Arrays.asList("ming", "foo", "bar").iterator();
-      }
-    });
+    final Enumerable<String> enumerable1 = Linq4j.asEnumerable(
+        () -> Arrays.asList("ming", "foo", "bar").iterator());
+    final Enumerable<String> enumerable2 = Linq4j.asEnumerable(
+        () -> Arrays.asList("ming", "foo", "bar").iterator());
     final EqualityComparer<String> equalityComparer = new EqualityComparer<String>() {
       public boolean equal(String v1, String v2) {
         return !Objects.equals(v1, v2); // reverse the equality.
@@ -2130,14 +1828,10 @@ public class Linq4jTest {
       }
     };
     assertFalse(enumerable1.sequenceEqual(enumerable2, equalityComparer));
+    final Enumerable<String> enumerable3 = Linq4j.asEnumerable(
+        () -> Arrays.asList("fun", "lol", "far").iterator());
     assertTrue(
-        enumerable1.sequenceEqual(
-            Linq4j.asEnumerable(
-                new Iterable<String>() {
-                  public Iterator<String> iterator() {
-                    return Arrays.asList("fun", "lol", "far").iterator();
-                  }
-                }), equalityComparer));
+        enumerable1.sequenceEqual(enumerable3, equalityComparer));
 
     try {
       EnumerableDefaults.sequenceEqual(null, enumerable2);
@@ -2160,21 +1854,12 @@ public class Linq4jTest {
     String s =
         Linq4j.asEnumerable(emps)
             .groupBy(EMP_DEPTNO_SELECTOR)
-            .select(new Function1<Grouping<Integer, Employee>, String>() {
-              public String apply(Grouping<Integer, Employee> group) {
-                return String.format(Locale.ROOT, "%s: %s", group.getKey(),
-                    stringJoin("+", group.select(new Function1<Employee, String>() {
-                      public String apply(Employee element) {
-                        return element.name;
-                      }
-                    })));
-              }
-            })
+            .select(group ->
+                String.format(Locale.ROOT, "%s: %s", group.getKey(),
+                    stringJoin("+", group.select(element -> element.name))))
             .toList()
             .toString();
-    assertEquals(
-        "[10: Fred+Eric+Janet, 30: Bill]",
-        s);
+    assertThat(s, is("[10: Fred+Eric+Janet, 30: Bill]"));
   }
 
   @Test public void testGroupByWithKeySelectorAndComparer() {
@@ -2188,38 +1873,24 @@ public class Linq4jTest {
                 return 0;
               }
             })
-            .select(new Function1<Grouping<Integer, Employee>, String>() {
-              public String apply(Grouping<Integer, Employee> group) {
-                return String.format(Locale.ROOT, "%s: %s", group.getKey(),
-                    stringJoin("+", group.select(new Function1<Employee, String>() {
-                      public String apply(Employee element) {
-                        return element.name;
-                      }
-                    })));
-              }
-            })
+            .select(group ->
+                String.format(Locale.ROOT, "%s: %s", group.getKey(),
+                    stringJoin("+", group.select(element -> element.name))))
             .toList()
             .toString();
-    assertEquals(
-        "[10: Fred+Bill+Eric+Janet]",
-        s);
+    assertThat(s, is("[10: Fred+Bill+Eric+Janet]"));
   }
 
   @Test public void testGroupByWithKeySelectorAndElementSelector() {
     String s =
         Linq4j.asEnumerable(emps)
             .groupBy(EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR)
-            .select(new Function1<Grouping<Integer, String>, String>() {
-              public String apply(Grouping<Integer, String> group) {
-                return String.format(Locale.ROOT, "%s: %s", group.getKey(),
-                    stringJoin("+", group));
-              }
-            })
+            .select(group ->
+                String.format(Locale.ROOT, "%s: %s", group.getKey(),
+                    stringJoin("+", group)))
             .toList()
             .toString();
-    assertEquals(
-        "[10: Fred+Eric+Janet, 30: Bill]",
-        s);
+    assertThat(s, is("[10: Fred+Eric+Janet, 30: Bill]"));
   }
 
   /** Equivalent to {@link String}.join, but that method is only in JDK 1.8 and
@@ -2239,20 +1910,18 @@ public class Linq4jTest {
   @Test public void testGroupByWithKeySelectorAndElementSelectorAndComparer() {
     String s =
         Linq4j.asEnumerable(emps)
-            .groupBy(EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR,  new EqualityComparer<Integer>() {
-              public boolean equal(Integer v1, Integer v2) {
-                return true;
-              }
-              public int hashCode(Integer integer) {
-                return 0;
-              }
-            })
-            .select(new Function1<Grouping<Integer, String>, String>() {
-              public String apply(Grouping<Integer, String> group) {
-                return String.format(Locale.ROOT, "%s: %s", group.getKey(),
-                    stringJoin("+", group));
-              }
-            })
+            .groupBy(EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR,
+                new EqualityComparer<Integer>() {
+                  public boolean equal(Integer v1, Integer v2) {
+                    return true;
+                  }
+                  public int hashCode(Integer integer) {
+                    return 0;
+                  }
+                })
+            .select(group ->
+                String.format(Locale.ROOT, "%s: %s", group.getKey(),
+                    stringJoin("+", group)))
             .toList()
             .toString();
     assertEquals(
@@ -2263,16 +1932,8 @@ public class Linq4jTest {
   @Test public void testGroupByWithKeySelectorAndResultSelector() {
     String s =
         Linq4j.asEnumerable(emps)
-            .groupBy(EMP_DEPTNO_SELECTOR, new Function2<Integer, Enumerable<Employee>, String>() {
-              public String apply(Integer key, Enumerable<Employee> group) {
-                return String.format(Locale.ROOT, "%s: %s", key,
-                    stringJoin("+", group.select(new Function1<Employee, String>() {
-                      public String apply(Employee element) {
-                        return element.name;
-                      }
-                    })));
-              }
-            })
+            .groupBy(EMP_DEPTNO_SELECTOR, (key, group) -> String.format(Locale.ROOT, "%s: %s", key,
+                stringJoin("+", group.select(element -> element.name))))
             .toList()
             .toString();
     assertEquals(
@@ -2283,23 +1944,17 @@ public class Linq4jTest {
   @Test public void testGroupByWithKeySelectorAndResultSelectorAndComparer() {
     String s =
         Linq4j.asEnumerable(emps)
-            .groupBy(EMP_DEPTNO_SELECTOR, new Function2<Integer, Enumerable<Employee>, String>() {
-              public String apply(Integer key, Enumerable<Employee> group) {
-                return String.format(Locale.ROOT, "%s: %s", key,
-                    stringJoin("+", group.select(new Function1<Employee, String>() {
-                      public String apply(Employee element) {
-                        return element.name;
-                      }
-                    })));
-              }
-            }, new EqualityComparer<Integer>() {
-              public boolean equal(Integer v1, Integer v2) {
-                return true;
-              }
-              public int hashCode(Integer integer) {
-                return 0;
-              }
-            })
+            .groupBy(EMP_DEPTNO_SELECTOR,
+                (key, group) -> String.format(Locale.ROOT, "%s: %s", key,
+                    stringJoin("+", group.select(element -> element.name))),
+                new EqualityComparer<Integer>() {
+                  public boolean equal(Integer v1, Integer v2) {
+                    return true;
+                  }
+                  public int hashCode(Integer integer) {
+                    return 0;
+                  }
+                })
             .toList()
             .toString();
     assertEquals(
@@ -2311,12 +1966,8 @@ public class Linq4jTest {
     String s =
         Linq4j.asEnumerable(emps)
             .groupBy(EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR,
-                new Function2<Integer, Enumerable<String>, String>() {
-                  public String apply(Integer key, Enumerable<String> group) {
-                    return String.format(Locale.ROOT, "%s: %s", key,
-                        stringJoin("+", group));
-                  }
-                })
+                (key, group) -> String.format(Locale.ROOT, "%s: %s", key,
+                    stringJoin("+", group)))
             .toList()
             .toString();
     assertEquals(
@@ -2328,12 +1979,8 @@ public class Linq4jTest {
     String s =
         Linq4j.asEnumerable(emps)
             .groupBy(EMP_DEPTNO_SELECTOR, EMP_NAME_SELECTOR,
-                new Function2<Integer, Enumerable<String>, String>() {
-                  public String apply(Integer key, Enumerable<String> group) {
-                    return String.format(Locale.ROOT, "%s: %s", key,
-                        stringJoin("+", group));
-                  }
-                },
+                (key, group) -> String.format(Locale.ROOT, "%s: %s", key,
+                    stringJoin("+", group)),
                 new EqualityComparer<Integer>() {
                   public boolean equal(Integer v1, Integer v2) {
                     return true;
@@ -2354,12 +2001,7 @@ public class Linq4jTest {
     final Enumerable<String> e1 = Linq4j.asEnumerable(Arrays.asList("a", "b", "c"));
     final Enumerable<String> e2 = Linq4j.asEnumerable(Arrays.asList("1", "2", "3"));
 
-    final Enumerable<String> zipped = e1.zip(e2,
-        new Function2<String, String, String>() {
-          public String apply(String v0, String v1) {
-            return v0 + v1;
-          }
-        });
+    final Enumerable<String> zipped = e1.zip(e2, (v0, v1) -> v0 + v1);
     assertEquals(3, zipped.count());
     zipped.enumerator().reset();
     for (int i = 0; i < 3; i++) {
@@ -2371,12 +2013,7 @@ public class Linq4jTest {
     final Enumerable<String> e1 = Linq4j.asEnumerable(Arrays.asList("a", "b"));
     final Enumerable<String> e2 = Linq4j.asEnumerable(Arrays.asList("1", "2", "3"));
 
-    final Function2<String, String, String> resultSelector =
-        new Function2<String, String, String>() {
-          public String apply(String v0, String v1) {
-            return v0 + v1;
-          }
-        };
+    final Function2<String, String, String> resultSelector = (v0, v1) -> v0 + v1;
 
     final Enumerable<String> zipped1 = e1.zip(e2, resultSelector);
     assertEquals(2, zipped1.count());
@@ -2530,7 +2167,7 @@ public class Linq4jTest {
   //CHECKSTYLE: IGNORE 1
   public static final Department[] depts = {
       new Department("Sales", 10, Arrays.asList(emps[0], emps[2], emps[3])),
-      new Department("HR", 20, Collections.<Employee>emptyList()),
+      new Department("HR", 20, ImmutableList.of()),
       new Department("Marketing", 30, ImmutableList.of(emps[1])),
   };
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoEnumerator.java
----------------------------------------------------------------------
diff --git a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoEnumerator.java b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoEnumerator.java
index 054006b..80bc0e8 100644
--- a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoEnumerator.java
+++ b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoEnumerator.java
@@ -79,20 +79,12 @@ class MongoEnumerator implements Enumerator<Object> {
   }
 
   static Function1<Document, Map> mapGetter() {
-    return new Function1<Document, Map>() {
-      public Map apply(Document a0) {
-        return (Map) a0;
-      }
-    };
+    return a0 -> (Map) a0;
   }
 
   static Function1<Document, Object> singletonGetter(final String fieldName,
       final Class fieldClass) {
-    return new Function1<Document, Object>() {
-      public Object apply(Document a0) {
-        return convert(a0.get(fieldName), fieldClass);
-      }
-    };
+    return a0 -> convert(a0.get(fieldName), fieldClass);
   }
 
   /**
@@ -100,16 +92,14 @@ class MongoEnumerator implements Enumerator<Object> {
    */
   static Function1<Document, Object[]> listGetter(
       final List<Map.Entry<String, Class>> fields) {
-    return new Function1<Document, Object[]>() {
-      public Object[] apply(Document a0) {
-        Object[] objects = new Object[fields.size()];
-        for (int i = 0; i < fields.size(); i++) {
-          final Map.Entry<String, Class> field = fields.get(i);
-          final String name = field.getKey();
-          objects[i] = convert(a0.get(name), field.getValue());
-        }
-        return objects;
+    return a0 -> {
+      Object[] objects = new Object[fields.size()];
+      for (int i = 0; i < fields.size(); i++) {
+        final Map.Entry<String, Class> field = fields.get(i);
+        final String name = field.getKey();
+        objects[i] = convert(a0.get(name), field.getValue());
       }
+      return objects;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoSchema.java
----------------------------------------------------------------------
diff --git a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoSchema.java b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoSchema.java
index b7202ae..db00445 100644
--- a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoSchema.java
+++ b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoSchema.java
@@ -20,9 +20,7 @@ import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.AbstractSchema;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
-
 import com.mongodb.MongoClient;
 import com.mongodb.MongoClientOptions;
 import com.mongodb.MongoCredential;
@@ -31,6 +29,7 @@ import com.mongodb.client.MongoDatabase;
 
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Schema mapped onto a directory of MONGO files. Each table in the schema
@@ -67,7 +66,7 @@ public class MongoSchema extends AbstractSchema {
   @VisibleForTesting
   MongoSchema(MongoDatabase mongoDb) {
     super();
-    this.mongoDb = Preconditions.checkNotNull(mongoDb, "mongoDb");
+    this.mongoDb = Objects.requireNonNull(mongoDb, "mongoDb");
   }
 
   @Override protected Map<String, Table> getTableMap() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverter.java
----------------------------------------------------------------------
diff --git a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverter.java b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverter.java
index 579c484..53a8668 100644
--- a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverter.java
+++ b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverter.java
@@ -39,7 +39,6 @@ import org.apache.calcite.runtime.Hook;
 import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.util.AbstractList;
@@ -156,12 +155,7 @@ public class MongoToEnumerableConverter
   /** E.g. {@code constantList("x", "y")} returns
    * {@code {ConstantExpression("x"), ConstantExpression("y")}}. */
   private static <T> List<Expression> constantList(List<T> values) {
-    return Lists.transform(values,
-        new Function<T, Expression>() {
-          public Expression apply(T a0) {
-            return Expressions.constant(a0);
-          }
-        });
+    return Lists.transform(values, Expressions::constant);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverterRule.java
----------------------------------------------------------------------
diff --git a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverterRule.java b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverterRule.java
index fb2221e..54295d1 100644
--- a/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverterRule.java
+++ b/mongodb/src/main/java/org/apache/calcite/adapter/mongodb/MongoToEnumerableConverterRule.java
@@ -23,7 +23,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -39,7 +39,7 @@ public class MongoToEnumerableConverterRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public MongoToEnumerableConverterRule(RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(), MongoRel.CONVENTION,
+    super(RelNode.class, (Predicate<RelNode>) r -> true, MongoRel.CONVENTION,
         EnumerableConvention.INSTANCE, relBuilderFactory,
         "MongoToEnumerableConverterRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoAdapterTest.java
----------------------------------------------------------------------
diff --git a/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoAdapterTest.java b/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoAdapterTest.java
index 4001a8d..b7d4acd 100644
--- a/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoAdapterTest.java
+++ b/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoAdapterTest.java
@@ -21,12 +21,9 @@ import org.apache.calcite.schema.SchemaFactory;
 import org.apache.calcite.schema.SchemaPlus;
 import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.test.MongoAssertions;
-
 import org.apache.calcite.util.Bug;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.io.LineProcessor;
 import com.google.common.io.Resources;
 import com.mongodb.client.MongoCollection;
@@ -39,9 +36,7 @@ import org.bson.BsonDocument;
 import org.bson.BsonInt32;
 import org.bson.BsonString;
 import org.bson.Document;
-
 import org.hamcrest.CoreMatchers;
-
 import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.ClassRule;
@@ -52,7 +47,6 @@ import java.io.IOException;
 import java.io.UncheckedIOException;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
-import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.time.Instant;
 import java.time.LocalDate;
@@ -60,6 +54,8 @@ import java.time.ZoneOffset;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
+import java.util.function.Consumer;
 
 /**
  * Testing mongo adapter functionality. By default runs with
@@ -109,7 +105,7 @@ public class MongoAdapterTest implements SchemaFactory {
 
   private static void populate(MongoCollection<Document> collection, URL resource)
       throws IOException {
-    Preconditions.checkNotNull(collection, "collection");
+    Objects.requireNonNull(collection, "collection");
 
     if (collection.count() > 0) {
       // delete any existing documents (run from a clean set)
@@ -146,7 +142,7 @@ public class MongoAdapterTest implements SchemaFactory {
   }
 
   private CalciteAssert.AssertThat assertModel(URL url) {
-    Preconditions.checkNotNull(url, "url");
+    Objects.requireNonNull(url, "url");
     try {
       return assertModel(Resources.toString(url, StandardCharsets.UTF_8));
     } catch (IOException e) {
@@ -724,18 +720,14 @@ public class MongoAdapterTest implements SchemaFactory {
   @Test public void testCountViaInt() {
     assertModel(MODEL)
         .query("select count(*) from zips")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet input) {
-                try {
-                  Assert.assertThat(input.next(), CoreMatchers.is(true));
-                  Assert.assertThat(input.getInt(1), CoreMatchers.is(ZIPS_SIZE));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(input -> {
+          try {
+            Assert.assertThat(input.next(), CoreMatchers.is(true));
+            Assert.assertThat(input.getInt(1), CoreMatchers.is(ZIPS_SIZE));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /**
@@ -745,17 +737,14 @@ public class MongoAdapterTest implements SchemaFactory {
    * @param strings Expected expressions
    * @return validation function
    */
-  private static Function<List, Void> mongoChecker(final String... strings) {
-    return new Function<List, Void>() {
-      public Void apply(List actual) {
-        Object[] actualArray =
-            actual == null || actual.isEmpty()
-                ? null
-                : ((List) actual.get(0)).toArray();
-        CalciteAssert.assertArrayEqual("expected MongoDB query not found",
-            strings, actualArray);
-        return null;
-      }
+  private static Consumer<List> mongoChecker(final String... strings) {
+    return actual -> {
+      Object[] actualArray =
+          actual == null || actual.isEmpty()
+              ? null
+              : ((List) actual.get(0)).toArray();
+      CalciteAssert.assertArrayEqual("expected MongoDB query not found",
+          strings, actualArray);
     };
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoDatabasePolicy.java
----------------------------------------------------------------------
diff --git a/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoDatabasePolicy.java b/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoDatabasePolicy.java
index 52a0715..f325360 100644
--- a/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoDatabasePolicy.java
+++ b/mongodb/src/test/java/org/apache/calcite/adapter/mongodb/MongoDatabasePolicy.java
@@ -19,14 +19,13 @@ package org.apache.calcite.adapter.mongodb;
 import org.apache.calcite.test.MongoAssertions;
 
 import com.github.fakemongo.Fongo;
-
-import com.google.common.base.Preconditions;
-
 import com.mongodb.MongoClient;
 import com.mongodb.client.MongoDatabase;
 
 import org.junit.rules.ExternalResource;
 
+import java.util.Objects;
+
 /**
  * Instantiates a new connection to Fongo (or Mongo) database depending on the
  * current profile (unit or integration tests).
@@ -46,7 +45,7 @@ class MongoDatabasePolicy extends ExternalResource {
   private final MongoClient client;
 
   private MongoDatabasePolicy(MongoClient client) {
-    this.client = Preconditions.checkNotNull(client, "client");
+    this.client = Objects.requireNonNull(client, "client");
     this.database = client.getDatabase(DB_NAME);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/mongodb/src/test/java/org/apache/calcite/test/MongoAssertions.java
----------------------------------------------------------------------
diff --git a/mongodb/src/test/java/org/apache/calcite/test/MongoAssertions.java b/mongodb/src/test/java/org/apache/calcite/test/MongoAssertions.java
index 67626c3..4ee63c8 100644
--- a/mongodb/src/test/java/org/apache/calcite/test/MongoAssertions.java
+++ b/mongodb/src/test/java/org/apache/calcite/test/MongoAssertions.java
@@ -18,15 +18,15 @@ package org.apache.calcite.test;
 
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Ordering;
 
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.junit.Assert.assertThat;
@@ -47,29 +47,26 @@ public class MongoAssertions {
    * @param lines Expected expressions
    * @return validation function
    */
-  public static Function<ResultSet, Void> checkResultUnordered(
+  public static Consumer<ResultSet> checkResultUnordered(
       final String... lines) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final List<String> expectedList =
-              Ordering.natural().immutableSortedCopy(Arrays.asList(lines));
+    return resultSet -> {
+      try {
+        final List<String> expectedList =
+            Ordering.natural().immutableSortedCopy(Arrays.asList(lines));
 
-          final List<String> actualList = Lists.newArrayList();
-          CalciteAssert.toStringList(resultSet, actualList);
-          for (int i = 0; i < actualList.size(); i++) {
-            String s = actualList.get(i);
-            actualList.set(i,
-                s.replaceAll("\\.0;", ";").replaceAll("\\.0$", ""));
-          }
-          Collections.sort(actualList);
-
-          assertThat(Ordering.natural().immutableSortedCopy(actualList),
-              equalTo(expectedList));
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+        final List<String> actualList = new ArrayList<>();
+        CalciteAssert.toStringList(resultSet, actualList);
+        for (int i = 0; i < actualList.size(); i++) {
+          String s = actualList.get(i);
+          actualList.set(i,
+              s.replaceAll("\\.0;", ";").replaceAll("\\.0$", ""));
         }
+        Collections.sort(actualList);
+
+        assertThat(Ordering.natural().immutableSortedCopy(actualList),
+            equalTo(expectedList));
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/pig/src/main/java/org/apache/calcite/adapter/pig/PigAggregate.java
----------------------------------------------------------------------
diff --git a/pig/src/main/java/org/apache/calcite/adapter/pig/PigAggregate.java b/pig/src/main/java/org/apache/calcite/adapter/pig/PigAggregate.java
index 6ccbfac..b367fb3 100644
--- a/pig/src/main/java/org/apache/calcite/adapter/pig/PigAggregate.java
+++ b/pig/src/main/java/org/apache/calcite/adapter/pig/PigAggregate.java
@@ -27,8 +27,6 @@ import org.apache.calcite.util.ImmutableBitSet;
 
 import org.apache.pig.scripting.Pig;
 
-import com.google.common.base.Joiner;
-
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -95,8 +93,8 @@ public class PigAggregate extends Aggregate implements PigRel {
       for (int fieldIndex : groupedFieldIndexes) {
         groupedFieldNames.add(allFields.get(fieldIndex).getName());
       }
-      return relAlias + " = GROUP " + relAlias + " BY (" + Joiner.on(", ").join(groupedFieldNames)
-          + ");";
+      return relAlias + " = GROUP " + relAlias + " BY ("
+          + String.join(", ", groupedFieldNames) + ");";
     }
   }
 
@@ -112,7 +110,7 @@ public class PigAggregate extends Aggregate implements PigRel {
     final String generateCall = getPigGenerateCall(implementor);
     final List<String> distinctCalls = getDistinctCalls(implementor);
     return relAlias + " = FOREACH " + relAlias + " {\n"
-        + Joiner.on(";\n").join(distinctCalls) + generateCall + "\n};";
+        + String.join(";\n", distinctCalls) + generateCall + "\n};";
   }
 
   private String getPigGenerateCall(Implementor implementor) {
@@ -130,7 +128,7 @@ public class PigAggregate extends Aggregate implements PigRel {
     List<String> allFields = new ArrayList<>(groupFields.size() + pigAggCalls.size());
     allFields.addAll(groupFields);
     allFields.addAll(pigAggCalls);
-    return "  GENERATE " + Joiner.on(", ").join(allFields) + ';';
+    return "  GENERATE " + String.join(", ", allFields) + ';';
   }
 
   private List<String> getPigAggregateCalls(Implementor implementor) {
@@ -145,7 +143,7 @@ public class PigAggregate extends Aggregate implements PigRel {
   private String getPigAggregateCall(String relAlias, AggregateCall aggCall) {
     final PigAggFunction aggFunc = toPigAggFunc(aggCall);
     final String alias = aggCall.getName();
-    final String fields = Joiner.on(", ").join(getArgNames(relAlias, aggCall));
+    final String fields = String.join(", ", getArgNames(relAlias, aggCall));
     return aggFunc.name() + "(" + fields + ") AS " + alias;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/pig/src/main/java/org/apache/calcite/adapter/pig/PigFilter.java
----------------------------------------------------------------------
diff --git a/pig/src/main/java/org/apache/calcite/adapter/pig/PigFilter.java b/pig/src/main/java/org/apache/calcite/adapter/pig/PigFilter.java
index 63cc1ea..f3023f6 100644
--- a/pig/src/main/java/org/apache/calcite/adapter/pig/PigFilter.java
+++ b/pig/src/main/java/org/apache/calcite/adapter/pig/PigFilter.java
@@ -27,7 +27,6 @@ import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
 
-import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 
 import java.util.ArrayList;
@@ -77,7 +76,8 @@ public class PigFilter extends Filter implements PigRel {
     for (RexNode node : RelOptUtil.conjunctions(condition)) {
       filterConditionsConjunction.add(getSingleFilterCondition(implementor, node));
     }
-    String allFilterConditions = Joiner.on(" AND ").join(filterConditionsConjunction);
+    String allFilterConditions =
+        String.join(" AND ", filterConditionsConjunction);
     return relationAlias + " = FILTER " + relationAlias + " BY " + allFilterConditions + ';';
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/pig/src/main/java/org/apache/calcite/adapter/pig/PigRel.java
----------------------------------------------------------------------
diff --git a/pig/src/main/java/org/apache/calcite/adapter/pig/PigRel.java b/pig/src/main/java/org/apache/calcite/adapter/pig/PigRel.java
index 868d3d5..a9073a7 100644
--- a/pig/src/main/java/org/apache/calcite/adapter/pig/PigRel.java
+++ b/pig/src/main/java/org/apache/calcite/adapter/pig/PigRel.java
@@ -19,8 +19,6 @@ package org.apache.calcite.adapter.pig;
 import org.apache.calcite.plan.Convention;
 import org.apache.calcite.rel.RelNode;
 
-import com.google.common.base.Joiner;
-
 import java.util.ArrayList;
 import java.util.List;
 
@@ -83,7 +81,7 @@ public interface PigRel extends RelNode {
     }
 
     public String getScript() {
-      return Joiner.on("\n").join(statements);
+      return String.join("\n", statements);
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/pig/src/main/java/org/apache/calcite/adapter/pig/PigTableScan.java
----------------------------------------------------------------------
diff --git a/pig/src/main/java/org/apache/calcite/adapter/pig/PigTableScan.java b/pig/src/main/java/org/apache/calcite/adapter/pig/PigTableScan.java
index 95c3536..57fbdd9 100644
--- a/pig/src/main/java/org/apache/calcite/adapter/pig/PigTableScan.java
+++ b/pig/src/main/java/org/apache/calcite/adapter/pig/PigTableScan.java
@@ -29,8 +29,6 @@ import org.apache.calcite.rel.type.RelDataTypeField;
 
 import org.apache.pig.data.DataType;
 
-import com.google.common.base.Joiner;
-
 import java.util.ArrayList;
 import java.util.List;
 
@@ -65,7 +63,7 @@ public class PigTableScan extends TableScan implements PigRel {
     for (RelDataTypeField f : getTable().getRowType().getFieldList()) {
       fieldNamesAndTypes.add(getConcatenatedFieldNameAndTypeForPigSchema(implementor, f));
     }
-    return Joiner.on(", ").join(fieldNamesAndTypes);
+    return String.join(", ", fieldNamesAndTypes);
   }
 
   private String getConcatenatedFieldNameAndTypeForPigSchema(Implementor implementor,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/pig/src/test/java/org/apache/calcite/test/PigAdapterTest.java
----------------------------------------------------------------------
diff --git a/pig/src/test/java/org/apache/calcite/test/PigAdapterTest.java b/pig/src/test/java/org/apache/calcite/test/PigAdapterTest.java
index 77ebb18..0bc4544 100644
--- a/pig/src/test/java/org/apache/calcite/test/PigAdapterTest.java
+++ b/pig/src/test/java/org/apache/calcite/test/PigAdapterTest.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.test;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableMap;
 
 import org.junit.Test;
@@ -24,6 +23,7 @@ import org.junit.Test;
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.util.List;
+import java.util.function.Consumer;
 
 import static org.junit.Assert.assertEquals;
 
@@ -170,17 +170,14 @@ public class PigAdapterTest extends AbstractPigTest {
   /** Returns a function that checks that a particular Pig Latin scriptis
    * generated to implement a query. */
   @SuppressWarnings("rawtypes")
-  private static Function<List, Void> pigScriptChecker(final String... strings) {
-    return new Function<List, Void>() {
-      public Void apply(List actual) {
-        String actualArray =
-            actual == null || actual.isEmpty()
-                ? null
-                : (String) actual.get(0);
-        assertEquals("expected Pig script not found",
-            strings[0], actualArray);
-        return null;
-      }
+  private static Consumer<List> pigScriptChecker(final String... strings) {
+    return actual -> {
+      String actualArray =
+          actual == null || actual.isEmpty()
+              ? null
+              : (String) actual.get(0);
+      assertEquals("expected Pig script not found",
+          strings[0], actualArray);
     };
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/piglet/src/main/java/org/apache/calcite/piglet/Ast.java
----------------------------------------------------------------------
diff --git a/piglet/src/main/java/org/apache/calcite/piglet/Ast.java b/piglet/src/main/java/org/apache/calcite/piglet/Ast.java
index 5a06ec1..22b1e21 100644
--- a/piglet/src/main/java/org/apache/calcite/piglet/Ast.java
+++ b/piglet/src/main/java/org/apache/calcite/piglet/Ast.java
@@ -23,11 +23,11 @@ import org.apache.calcite.sql.parser.SqlParserUtil;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.math.BigDecimal;
 import java.util.List;
+import java.util.Objects;
 
 /** Abstract syntax tree.
  *
@@ -136,8 +136,8 @@ public class Ast {
     public final SqlParserPos pos;
 
     protected Node(SqlParserPos pos, Op op) {
-      this.op = Preconditions.checkNotNull(op);
-      this.pos = Preconditions.checkNotNull(pos);
+      this.op = Objects.requireNonNull(op);
+      this.pos = Objects.requireNonNull(pos);
     }
   }
 
@@ -154,7 +154,7 @@ public class Ast {
 
     protected Assignment(SqlParserPos pos, Op op, Identifier target) {
       super(pos, op);
-      this.target = Preconditions.checkNotNull(target);
+      this.target = Objects.requireNonNull(target);
     }
   }
 
@@ -164,7 +164,7 @@ public class Ast {
 
     public LoadStmt(SqlParserPos pos, Identifier target, Literal name) {
       super(pos, Op.LOAD, target);
-      this.name = Preconditions.checkNotNull(name);
+      this.name = Objects.requireNonNull(name);
     }
   }
 
@@ -333,7 +333,7 @@ public class Ast {
 
     public DumpStmt(SqlParserPos pos, Identifier relation) {
       super(pos, Op.DUMP);
-      this.relation = Preconditions.checkNotNull(relation);
+      this.relation = Objects.requireNonNull(relation);
     }
   }
 
@@ -343,7 +343,7 @@ public class Ast {
 
     public DescribeStmt(SqlParserPos pos, Identifier relation) {
       super(pos, Op.DESCRIBE);
-      this.relation = Preconditions.checkNotNull(relation);
+      this.relation = Objects.requireNonNull(relation);
     }
   }
 
@@ -353,7 +353,7 @@ public class Ast {
 
     public Literal(SqlParserPos pos, Object value) {
       super(pos, Op.LITERAL);
-      this.value = Preconditions.checkNotNull(value);
+      this.value = Objects.requireNonNull(value);
     }
 
     public static NumericLiteral createExactNumeric(String s,
@@ -408,7 +408,7 @@ public class Ast {
 
     public Identifier(SqlParserPos pos, String value) {
       super(pos, Op.IDENTIFIER);
-      this.value = Preconditions.checkNotNull(value);
+      this.value = Objects.requireNonNull(value);
     }
 
     public boolean isStar() {
@@ -466,8 +466,8 @@ public class Ast {
 
     public FieldSchema(SqlParserPos pos, Identifier id, Type type) {
       super(pos, Op.FIELD_SCHEMA);
-      this.id = Preconditions.checkNotNull(id);
-      this.type = Preconditions.checkNotNull(type);
+      this.id = Objects.requireNonNull(id);
+      this.type = Objects.requireNonNull(type);
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/piglet/src/main/javacc/PigletParser.jj
----------------------------------------------------------------------
diff --git a/piglet/src/main/javacc/PigletParser.jj b/piglet/src/main/javacc/PigletParser.jj
index d11b819..ae244d9 100644
--- a/piglet/src/main/javacc/PigletParser.jj
+++ b/piglet/src/main/javacc/PigletParser.jj
@@ -35,10 +35,10 @@ import org.apache.calcite.util.trace.CalciteTrace;
 import org.apache.calcite.util.Pair;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import org.slf4j.Logger;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import static org.apache.calcite.util.Static.RESOURCE;
@@ -161,7 +161,7 @@ JAVACODE SqlParseException convertException(Throwable ex) {
  */
 Program stmtListEof() :
 {
-  final List<Stmt> list = Lists.newArrayList();
+  final List<Stmt> list = new ArrayList<Stmt>();
   Stmt s;
 }
 {
@@ -326,7 +326,7 @@ Assignment foreachStmt(final Identifier target) :
 List<Stmt> nestedStmtList() :
 {
   Assignment s;
-  final List<Stmt> list = Lists.newArrayList();
+  final List<Stmt> list = new ArrayList<Stmt>();
 }
 {
   s = nestedStmt() {
@@ -388,7 +388,8 @@ OrderStmt orderStmt(final Identifier target) :
 
 List<Pair<Identifier, Direction>> orderFieldCommaList() :
 {
-  final List<Pair<Identifier, Direction>> list = Lists.newArrayList();
+  final List<Pair<Identifier, Direction>> list =
+      new ArrayList<Pair<Identifier, Direction>>();
   Pair<Identifier, Direction> field;
 }
 {
@@ -730,7 +731,7 @@ Node atom() :
 /** A non-empty list of expressions. */
 List<Node> expCommaList() :
 {
-  final List<Node> list = Lists.newArrayList();
+  final List<Node> list = new ArrayList<Node>();
   Node e;
 }
 {
@@ -1045,7 +1046,7 @@ String commonNonReservedKeyWord() :
  *****************************************/
 
 TOKEN_MGR_DECLS : {
-    List<Integer> lexicalStateStack = Lists.newArrayList();
+    List<Integer> lexicalStateStack = new ArrayList<Integer>();
 
     void pushState() {
       lexicalStateStack.add(curLexState);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/piglet/src/test/java/org/apache/calcite/test/Fluent.java
----------------------------------------------------------------------
diff --git a/piglet/src/test/java/org/apache/calcite/test/Fluent.java b/piglet/src/test/java/org/apache/calcite/test/Fluent.java
index 7afd781..fc65939 100644
--- a/piglet/src/test/java/org/apache/calcite/test/Fluent.java
+++ b/piglet/src/test/java/org/apache/calcite/test/Fluent.java
@@ -24,7 +24,6 @@ import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.tools.PigRelBuilder;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Ordering;
 
 import java.io.StringReader;
@@ -32,6 +31,7 @@ import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.assertThat;
@@ -59,39 +59,33 @@ class Fluent {
 
   public Fluent returns(final String out)
       throws ParseException {
-    return returns(
-        new Function<String, Void>() {
-          public Void apply(String s) {
-            assertThat(s, is(out));
-            return null;
-          }
-        });
+    return returns(s -> {
+      assertThat(s, is(out));
+      return null;
+    });
   }
 
   public Fluent returnsUnordered(String... lines) throws ParseException {
     final List<String> expectedLines =
         Ordering.natural().immutableSortedCopy(Arrays.asList(lines));
-    return returns(
-        new Function<String, Void>() {
-          public Void apply(String s) {
-            final List<String> actualLines = new ArrayList<>();
-            for (;;) {
-              int i = s.indexOf('\n');
-              if (i < 0) {
-                if (!s.isEmpty()) {
-                  actualLines.add(s);
-                }
-                break;
-              } else {
-                actualLines.add(s.substring(0, i));
-                s = s.substring(i + 1);
-              }
-            }
-            assertThat(Ordering.natural().sortedCopy(actualLines),
-                is(expectedLines));
-            return null;
+    return returns(s -> {
+      final List<String> actualLines = new ArrayList<>();
+      for (;;) {
+        int i = s.indexOf('\n');
+        if (i < 0) {
+          if (!s.isEmpty()) {
+            actualLines.add(s);
           }
-        });
+          break;
+        } else {
+          actualLines.add(s.substring(0, i));
+          s = s.substring(i + 1);
+        }
+      }
+      assertThat(Ordering.natural().sortedCopy(actualLines),
+          is(expectedLines));
+      return null;
+    });
   }
 
   public Fluent returns(Function<String, Void> checker) throws ParseException {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/main/java/org/apache/calcite/adapter/os/DuTableFunction.java
----------------------------------------------------------------------
diff --git a/plus/src/main/java/org/apache/calcite/adapter/os/DuTableFunction.java b/plus/src/main/java/org/apache/calcite/adapter/os/DuTableFunction.java
index 336f5fa..ede8c97 100644
--- a/plus/src/main/java/org/apache/calcite/adapter/os/DuTableFunction.java
+++ b/plus/src/main/java/org/apache/calcite/adapter/os/DuTableFunction.java
@@ -19,7 +19,6 @@ package org.apache.calcite.adapter.os;
 import org.apache.calcite.DataContext;
 import org.apache.calcite.config.CalciteConnectionConfig;
 import org.apache.calcite.linq4j.Enumerable;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.schema.ScannableTable;
@@ -44,11 +43,9 @@ public class DuTableFunction {
     return new ScannableTable() {
       public Enumerable<Object[]> scan(DataContext root) {
         return Processes.processLines("du", "-ak")
-            .select(new Function1<String, Object[]>() {
-              public Object[] apply(String a0) {
-                final String[] fields = a0.split("\t");
-                return new Object[] {Long.valueOf(fields[0]), fields[1]};
-              }
+            .select(a0 -> {
+              final String[] fields = a0.split("\t");
+              return new Object[] {Long.valueOf(fields[0]), fields[1]};
             });
       }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/main/java/org/apache/calcite/adapter/os/Processes.java
----------------------------------------------------------------------
diff --git a/plus/src/main/java/org/apache/calcite/adapter/os/Processes.java b/plus/src/main/java/org/apache/calcite/adapter/os/Processes.java
index 8caa7c3..18aa514 100644
--- a/plus/src/main/java/org/apache/calcite/adapter/os/Processes.java
+++ b/plus/src/main/java/org/apache/calcite/adapter/os/Processes.java
@@ -20,8 +20,6 @@ import org.apache.calcite.linq4j.AbstractEnumerable;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Enumerator;
 
-import com.google.common.base.Supplier;
-
 import java.io.BufferedInputStream;
 import java.io.BufferedReader;
 import java.io.IOException;
@@ -29,6 +27,7 @@ import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
+import java.util.function.Supplier;
 
 /**
  * Utilities regarding operating system processes.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/main/java/org/apache/calcite/adapter/os/SqlShell.java
----------------------------------------------------------------------
diff --git a/plus/src/main/java/org/apache/calcite/adapter/os/SqlShell.java b/plus/src/main/java/org/apache/calcite/adapter/os/SqlShell.java
index 6cdbfab..92da79f 100644
--- a/plus/src/main/java/org/apache/calcite/adapter/os/SqlShell.java
+++ b/plus/src/main/java/org/apache/calcite/adapter/os/SqlShell.java
@@ -20,8 +20,6 @@ import org.apache.calcite.linq4j.Enumerator;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.util.JsonBuilder;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Maps;
 
@@ -41,6 +39,7 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -58,9 +57,9 @@ public class SqlShell {
   SqlShell(InputStreamReader in, PrintWriter out,
       PrintWriter err, String... args) {
     this.args = ImmutableList.copyOf(args);
-    this.in = Preconditions.checkNotNull(in);
-    this.out = Preconditions.checkNotNull(out);
-    this.err = Preconditions.checkNotNull(err);
+    this.in = Objects.requireNonNull(in);
+    this.out = Objects.requireNonNull(out);
+    this.err = Objects.requireNonNull(err);
   }
 
   private static String model() {
@@ -286,32 +285,30 @@ public class SqlShell {
             out.println(",");
           }
           json.append(b, 0,
-              Maps.asMap(fields, new Function<String, Object>() {
-                public Object apply(String columnLabel) {
-                  try {
-                    final int i = fieldOrdinals.get(columnLabel);
-                    switch (m.getColumnType(i)) {
-                    case Types.BOOLEAN:
-                      final boolean b = r.getBoolean(i);
-                      return !b && r.wasNull() ? null : b;
-                    case Types.DECIMAL:
-                    case Types.FLOAT:
-                    case Types.REAL:
-                    case Types.DOUBLE:
-                      final double d = r.getDouble(i);
-                      return d == 0D && r.wasNull() ? null : d;
-                    case Types.BIGINT:
-                    case Types.INTEGER:
-                    case Types.SMALLINT:
-                    case Types.TINYINT:
-                      final long v = r.getLong(i);
-                      return v == 0L && r.wasNull() ? null : v;
-                    default:
-                      return r.getString(i);
-                    }
-                  } catch (SQLException e) {
-                    throw new RuntimeException(e);
+              Maps.asMap(fields, columnLabel -> {
+                try {
+                  final int i1 = fieldOrdinals.get(columnLabel);
+                  switch (m.getColumnType(i1)) {
+                  case Types.BOOLEAN:
+                    final boolean b1 = r.getBoolean(i1);
+                    return !b1 && r.wasNull() ? null : b1;
+                  case Types.DECIMAL:
+                  case Types.FLOAT:
+                  case Types.REAL:
+                  case Types.DOUBLE:
+                    final double d = r.getDouble(i1);
+                    return d == 0D && r.wasNull() ? null : d;
+                  case Types.BIGINT:
+                  case Types.INTEGER:
+                  case Types.SMALLINT:
+                  case Types.TINYINT:
+                    final long v = r.getLong(i1);
+                    return v == 0L && r.wasNull() ? null : v;
+                  default:
+                    return r.getString(i1);
                   }
+                } catch (SQLException e) {
+                  throw new RuntimeException(e);
                 }
               }));
           out.append(b);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/plus/src/main/java/org/apache/calcite/adapter/tpcds/TpcdsSchema.java
----------------------------------------------------------------------
diff --git a/plus/src/main/java/org/apache/calcite/adapter/tpcds/TpcdsSchema.java b/plus/src/main/java/org/apache/calcite/adapter/tpcds/TpcdsSchema.java
index e18ba84..618324e 100644
--- a/plus/src/main/java/org/apache/calcite/adapter/tpcds/TpcdsSchema.java
+++ b/plus/src/main/java/org/apache/calcite/adapter/tpcds/TpcdsSchema.java
@@ -30,8 +30,8 @@ import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.AbstractSchema;
 import org.apache.calcite.schema.impl.AbstractTableQueryable;
 import org.apache.calcite.util.Bug;
-import org.apache.calcite.util.ImmutableBitSet;
 
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
 import net.hydromatic.tpcds.TpcdsColumn;
@@ -39,7 +39,6 @@ import net.hydromatic.tpcds.TpcdsEntity;
 import net.hydromatic.tpcds.TpcdsTable;
 
 import java.sql.Date;
-import java.util.Collections;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -115,7 +114,7 @@ public class TpcdsSchema extends AbstractSchema {
       Bug.upgrade("add row count estimate to TpcdsTable, and use it");
       Integer rowCount = TABLE_ROW_COUNTS.get(tpcdsTable.name);
       assert rowCount != null : tpcdsTable.name;
-      return Statistics.of(rowCount, Collections.<ImmutableBitSet>emptyList());
+      return Statistics.of(rowCount, ImmutableList.of());
     }
 
     public <T> Queryable<T> asQueryable(final QueryProvider queryProvider,


[23/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
[CALCITE-2259] Allow Java 8 syntax

In summary: use lambdas where possible, switch from Guava function
types to Java function types or lambdas, but continue to use Guava
components (such as immutable collections and cache) that have no
equivalent in the Java runtime.

1. Change single-abstract-method (SAM) classes to lambdas. Preserve
formatting wherever possible.

2. Change AssertQuery.returns argument type from Guava Function to Java
Consumer. If you are using a lambda and see 'returns is deprecated',
remove the 'return null;' line, and the lambda will become a Consumer
(whose return is void).

3. Change RelOptRuleOperand and RelOptRule.operand methods to take Java
Predicate rather than Guava Predicate.

4. Change the argument of Hook.add and .addThread from Guava Function to
Java Consumer.

5. Change 'list.toArray(new T[list.size()])' to 'list.toArray(new T[0])'
because the latter is simpler, and just as efficient on recent Java
versions.

6. Resource references; change "try (Closeable ignore = foo())" to "try
  (foo())", especially uses of TryThreadLocal and Hook.Closeable.

7. Convert linq4j Function1 to java Function, Function2 to java BiFunction

8. Fix occurrences of Intellij's "Explicit type can be replaced with
<>" inspection. (Occurs for "List<String> list = new
ArrayList<String>();".)

9. Change Guava Preconditions.checkNotNull to Java
Objects.requireNonNull. (Kevin Risden)

10. Break out anonymous classes and fix dependency problems.

11. Use CacheLoader.of(Function) where possible.

12. Replace sub-classes of ThreadLocal with ThreadLocal.withInitial().

13. Replace Guava collection methods with calls to Java collection types,
for example replace Lists.newArrayList() with new ArrayList<>(),
Maps.newHashSet() with new HashSet<>(), similarly Sets.

14. Replace Guava Joiner with String.join.

15. Replace Collections.emptyList() with ImmutableList.of() in a few
places.

For backwards compatibility, we preserved (and deprecated) the old
methods that used Guava types. In a few cases where new and old have
the same signature (after erasure), we could not add a method with the
same name, so we gave the new method a "J" suffix. Examples include
Hook.property and .propertyJ, RelOptRule.operand and .operandJ.

In test code, we have not slavishly ensured backwards compatibility.

We do not intend to remove uses of Guava's immutable collections.

We have ignored Intellij's "Pseudo functional style code" inspection
most of the time, but in a few cases have converted Lists.transform(),
Iterables.transform(), and Iterables.filter() into Java streams. Use
the Util.toImmutableList() collector if the result is to be an
immutable list. Use Util.transform() rather than Lists.transform()
if you have a Java function rather than a Guava function or lambda.

Not covered in this change (might be done in future):
* Convert Collections.sort(list) to list.sort.
* Review uses of 'for (Map.Entry<K, V> e : map.entrySet())' and see
  whether it makes sense to convert to 'map.forEach((k, v) ->
  ...)'. Intellij inspection is called 'Replace with Map.forEach'.

Breaking changes:
* LatticeStatisticProvider.Factory, result of RexUtil.notFun(), and
  arguments to Mappings.target() are Function (was Guava, now Java)
* Argument to SqlSpecialOperator.TokenSequence.parser() is Predicate
  (was Guava, now Java)
* AggregateNode.AccumulatorFactory extends Supplier (was Guava, now Java)


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/d59b639d
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/d59b639d
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/d59b639d

Branch: refs/heads/master
Commit: d59b639d27da704f00eff616324a2c04aa06f84c
Parents: 5bbc501
Author: Julian Hyde <jh...@apache.org>
Authored: Thu Jul 5 13:21:59 2018 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 10:16:26 2018 -0700

----------------------------------------------------------------------
 .../adapter/cassandra/CassandraRules.java       |   42 +-
 .../adapter/cassandra/CassandraSchema.java      |   21 +-
 .../adapter/cassandra/CassandraTable.java       |   51 +-
 .../CassandraToEnumerableConverter.java         |    8 +-
 .../CassandraToEnumerableConverterRule.java     |    4 +-
 core/src/main/codegen/templates/Parser.jj       |   16 +-
 .../calcite/adapter/clone/ArrayTable.java       |    8 +-
 .../calcite/adapter/clone/CloneSchema.java      |   34 +-
 .../calcite/adapter/clone/ColumnLoader.java     |   37 +-
 .../apache/calcite/adapter/clone/ListTable.java |    3 +-
 .../elasticsearch/ElasticsearchFilter.java      |    1 -
 .../elasticsearch/ElasticsearchProject.java     |   20 +-
 .../elasticsearch/ElasticsearchTableScan.java   |    5 +-
 .../ElasticsearchToEnumerableConverter.java     |   11 +-
 .../ElasticsearchToEnumerableConverterRule.java |    4 +-
 .../calcite/adapter/enumerable/EnumUtils.java   |   12 +-
 .../adapter/enumerable/EnumerableAggregate.java |    3 +-
 .../adapter/enumerable/EnumerableBindable.java  |   20 +-
 .../adapter/enumerable/EnumerableCalc.java      |   14 +-
 .../adapter/enumerable/EnumerableCalcRule.java  |   10 +-
 .../enumerable/EnumerableCorrelateRule.java     |    4 +-
 .../adapter/enumerable/EnumerableFilter.java    |   18 +-
 .../enumerable/EnumerableFilterRule.java        |    9 +-
 .../enumerable/EnumerableInterpreterRule.java   |    4 +-
 .../adapter/enumerable/EnumerableLimit.java     |   16 +-
 .../adapter/enumerable/EnumerableMergeJoin.java |    2 +-
 .../enumerable/EnumerableMergeJoinRule.java     |    9 +-
 .../adapter/enumerable/EnumerableProject.java   |   20 +-
 .../enumerable/EnumerableProjectRule.java       |    9 +-
 .../adapter/enumerable/EnumerableRel.java       |   26 +-
 .../enumerable/EnumerableRelImplementor.java    |   50 +-
 .../EnumerableTableFunctionScanRule.java        |    4 +-
 .../enumerable/EnumerableTableModifyRule.java   |    4 +-
 .../adapter/enumerable/EnumerableTableScan.java |   17 +-
 .../enumerable/EnumerableTableScanRule.java     |    4 +-
 .../adapter/enumerable/EnumerableUncollect.java |    2 +-
 .../adapter/enumerable/EnumerableValues.java    |   15 +-
 .../enumerable/EnumerableValuesRule.java        |    4 +-
 .../adapter/enumerable/EnumerableWindow.java    |  203 ++-
 .../enumerable/NestedBlockBuilderImpl.java      |    6 +-
 .../adapter/enumerable/PhysTypeImpl.java        |   24 +-
 .../calcite/adapter/enumerable/RexImpTable.java |  198 ++-
 .../adapter/enumerable/RexToLixTranslator.java  |    8 +-
 .../enumerable/impl/WinAggAddContextImpl.java   |   10 +-
 .../impl/WinAggResultContextImpl.java           |   13 +-
 .../apache/calcite/adapter/jdbc/JdbcRules.java  |   64 +-
 .../apache/calcite/adapter/jdbc/JdbcSchema.java |    6 +-
 .../apache/calcite/adapter/jdbc/JdbcTable.java  |   25 +-
 .../jdbc/JdbcToEnumerableConverterRule.java     |    4 +-
 .../apache/calcite/adapter/jdbc/JdbcUtils.java  |   41 +-
 .../config/CalciteConnectionConfigImpl.java     |    2 +-
 .../calcite/interpreter/AggregateNode.java      |   23 +-
 .../apache/calcite/interpreter/Bindables.java   |   54 +-
 .../calcite/interpreter/InterpretableRel.java   |    8 +-
 .../apache/calcite/interpreter/Interpreter.java |    6 +-
 .../calcite/interpreter/JaninoRexCompiler.java  |   19 +-
 .../apache/calcite/interpreter/JoinNode.java    |    4 +-
 .../NoneToBindableConverterRule.java            |    4 +-
 .../apache/calcite/interpreter/SortNode.java    |   34 +-
 .../calcite/interpreter/TableScanNode.java      |   41 +-
 .../apache/calcite/interpreter/UnionNode.java   |    4 +-
 .../apache/calcite/interpreter/ValuesNode.java  |    4 +-
 .../calcite/jdbc/CalciteConnectionImpl.java     |   43 +-
 .../apache/calcite/jdbc/CalciteMetaImpl.java    |  187 +--
 .../org/apache/calcite/jdbc/CalcitePrepare.java |   13 +-
 .../apache/calcite/jdbc/CalciteResultSet.java   |    7 +-
 .../org/apache/calcite/jdbc/CalciteSchema.java  |   27 +-
 .../org/apache/calcite/jdbc/JavaRecordType.java |    4 +-
 .../calcite/jdbc/JavaTypeFactoryImpl.java       |   15 +-
 .../org/apache/calcite/jdbc/MetadataSchema.java |   12 +-
 .../CachingLatticeStatisticProvider.java        |   10 +-
 .../org/apache/calcite/materialize/Lattice.java |   98 +-
 .../materialize/LatticeStatisticProvider.java   |    3 +-
 .../materialize/MaterializationActor.java       |   10 +-
 .../materialize/MaterializationService.java     |   46 +-
 .../ProfilerLatticeStatisticProvider.java       |   88 +-
 .../SqlLatticeStatisticProvider.java            |   24 +-
 .../calcite/materialize/TileSuggester.java      |   12 +-
 .../calcite/plan/AbstractRelOptPlanner.java     |    9 +-
 .../java/org/apache/calcite/plan/Contexts.java  |    9 +-
 .../apache/calcite/plan/ConventionTraitDef.java |    9 +-
 .../apache/calcite/plan/RelCompositeTrait.java  |    6 +-
 .../org/apache/calcite/plan/RelOptCluster.java  |    7 +-
 .../calcite/plan/RelOptMaterialization.java     |   18 +-
 .../calcite/plan/RelOptMaterializations.java    |   31 +-
 .../calcite/plan/RelOptPredicateList.java       |   13 +-
 .../org/apache/calcite/plan/RelOptRule.java     |   62 +-
 .../org/apache/calcite/plan/RelOptRuleCall.java |    2 +-
 .../apache/calcite/plan/RelOptRuleOperand.java  |    9 +-
 .../calcite/plan/RelOptRuleOperandChildren.java |    4 +-
 .../org/apache/calcite/plan/RelOptUtil.java     |  118 +-
 .../org/apache/calcite/plan/RelTraitDef.java    |    7 +-
 .../org/apache/calcite/plan/RelTraitSet.java    |    4 +-
 .../calcite/plan/RexImplicationChecker.java     |   12 +-
 .../java/org/apache/calcite/plan/Strong.java    |    4 +-
 .../calcite/plan/SubstitutionVisitor.java       |   46 +-
 .../org/apache/calcite/plan/hep/HepPlanner.java |    4 +-
 .../plan/hep/HepRelMetadataProvider.java        |   21 +-
 .../apache/calcite/plan/volcano/RelSubset.java  |   17 +-
 .../apache/calcite/plan/volcano/RuleQueue.java  |   49 +-
 .../calcite/plan/volcano/VolcanoPlanner.java    |   37 +-
 .../volcano/VolcanoRelMetadataProvider.java     |  103 +-
 .../calcite/plan/volcano/VolcanoRuleCall.java   |    2 +-
 .../calcite/prepare/CalciteCatalogReader.java   |   99 +-
 .../calcite/prepare/CalciteMaterializer.java    |    4 +-
 .../calcite/prepare/CalcitePrepareImpl.java     |   79 +-
 .../calcite/prepare/LixToRelTranslator.java     |    4 +-
 .../org/apache/calcite/prepare/PlannerImpl.java |   23 +-
 .../org/apache/calcite/prepare/Prepare.java     |   12 +-
 .../apache/calcite/prepare/RelOptTableImpl.java |   41 +-
 .../apache/calcite/profile/ProfilerImpl.java    |   65 +-
 .../apache/calcite/profile/SimpleProfiler.java  |   26 +-
 .../org/apache/calcite/rel/RelCollations.java   |   10 +-
 .../apache/calcite/rel/RelDistributions.java    |    3 +-
 .../apache/calcite/rel/RelFieldCollation.java   |    6 +-
 .../java/org/apache/calcite/rel/RelRoot.java    |    4 +-
 .../calcite/rel/convert/ConverterRule.java      |   25 +-
 .../org/apache/calcite/rel/core/Aggregate.java  |   51 +-
 .../apache/calcite/rel/core/AggregateCall.java  |    5 +-
 .../org/apache/calcite/rel/core/Correlate.java  |    3 +-
 .../org/apache/calcite/rel/core/EquiJoin.java   |    7 +-
 .../org/apache/calcite/rel/core/Exchange.java   |    5 +-
 .../java/org/apache/calcite/rel/core/Join.java  |    6 +-
 .../org/apache/calcite/rel/core/JoinInfo.java   |    9 +-
 .../java/org/apache/calcite/rel/core/Match.java |    9 +-
 .../org/apache/calcite/rel/core/Project.java    |    9 +-
 .../apache/calcite/rel/core/RelFactories.java   |    3 +-
 .../org/apache/calcite/rel/core/SemiJoin.java   |    5 +-
 .../java/org/apache/calcite/rel/core/SetOp.java |    9 +-
 .../apache/calcite/rel/core/SortExchange.java   |    4 +-
 .../calcite/rel/core/TableFunctionScan.java     |    2 +-
 .../apache/calcite/rel/core/TableModify.java    |    5 +-
 .../org/apache/calcite/rel/core/Values.java     |   86 +-
 .../apache/calcite/rel/logical/LogicalCalc.java |   15 +-
 .../calcite/rel/logical/LogicalFilter.java      |   26 +-
 .../apache/calcite/rel/logical/LogicalJoin.java |   14 +-
 .../calcite/rel/logical/LogicalProject.java     |   12 +-
 .../calcite/rel/logical/LogicalTableScan.java   |   17 +-
 .../calcite/rel/logical/LogicalValues.java      |   12 +-
 .../calcite/rel/logical/LogicalWindow.java      |   16 +-
 .../metadata/CachingRelMetadataProvider.java    |   18 +-
 .../metadata/ChainedRelMetadataProvider.java    |   23 +-
 .../rel/metadata/JaninoRelMetadataProvider.java |   12 +-
 .../rel/metadata/MetadataFactoryImpl.java       |   23 +-
 .../metadata/ReflectiveRelMetadataProvider.java |  137 +-
 .../rel/metadata/RelMdAllPredicates.java        |   23 +-
 .../calcite/rel/metadata/RelMdCollation.java    |    9 +-
 .../rel/metadata/RelMdColumnUniqueness.java     |   10 -
 .../rel/metadata/RelMdExpressionLineage.java    |   37 +-
 .../calcite/rel/metadata/RelMdPredicates.java   |   34 +-
 .../apache/calcite/rel/metadata/RelMdSize.java  |    4 +-
 .../rel/metadata/RelMdTableReferences.java      |    4 +-
 .../calcite/rel/metadata/RelMetadataQuery.java  |   24 +-
 .../calcite/rel/metadata/UnboundMetadata.java   |    1 +
 .../calcite/rel/mutable/MutableMultiRel.java    |    8 +-
 .../apache/calcite/rel/mutable/MutableRel.java  |    8 +-
 .../apache/calcite/rel/mutable/MutableRels.java |   17 +-
 .../calcite/rel/rel2sql/RelToSqlConverter.java  |   19 +-
 .../calcite/rel/rel2sql/SqlImplementor.java     |    8 +-
 .../rel/rules/AbstractMaterializedViewRule.java |   24 +-
 .../AggregateExpandDistinctAggregatesRule.java  |    6 +-
 .../rel/rules/AggregateExtractProjectRule.java  |   27 +-
 .../rel/rules/AggregateFilterTransposeRule.java |   11 +-
 .../rel/rules/AggregateJoinTransposeRule.java   |   42 +-
 .../rel/rules/AggregateProjectMergeRule.java    |    6 +-
 .../AggregateProjectPullUpConstantsRule.java    |    2 +-
 .../rel/rules/AggregateReduceFunctionsRule.java |   11 +-
 .../rel/rules/AggregateStarTableRule.java       |   10 +-
 .../rel/rules/AggregateUnionAggregateRule.java  |    2 +-
 .../rel/rules/AggregateUnionTransposeRule.java  |    4 +-
 .../calcite/rel/rules/AggregateValuesRule.java  |    7 +-
 .../calcite/rel/rules/CalcRelSplitter.java      |    2 +-
 .../calcite/rel/rules/DateRangeRules.java       |   41 +-
 .../rel/rules/FilterAggregateTransposeRule.java |    6 +-
 .../calcite/rel/rules/FilterJoinRule.java       |   18 +-
 .../calcite/rel/rules/FilterTableScanRule.java  |   30 +-
 .../calcite/rel/rules/JoinAssociateRule.java    |    9 +-
 .../rel/rules/JoinProjectTransposeRule.java     |    2 +-
 .../calcite/rel/rules/JoinToMultiJoinRule.java  |   18 +-
 .../apache/calcite/rel/rules/LoptJoinTree.java  |   13 +-
 .../apache/calcite/rel/rules/LoptMultiJoin.java |    5 +-
 .../calcite/rel/rules/LoptOptimizeJoinRule.java |    8 +-
 .../rules/MaterializedViewFilterScanRule.java   |    2 +-
 .../rel/rules/MultiJoinOptimizeBushyRule.java   |   19 +-
 .../rules/ProjectCorrelateTransposeRule.java    |    3 +-
 .../rel/rules/ProjectFilterTransposeRule.java   |    6 +-
 .../rel/rules/ProjectJoinTransposeRule.java     |    3 +-
 .../calcite/rel/rules/ProjectRemoveRule.java    |   15 +-
 .../rel/rules/ProjectSetOpTransposeRule.java    |    4 +-
 .../calcite/rel/rules/ProjectTableScanRule.java |   26 +-
 .../calcite/rel/rules/ProjectToWindowRule.java  |   35 +-
 .../calcite/rel/rules/PruneEmptyRules.java      |   42 +-
 .../apache/calcite/rel/rules/PushProjector.java |   31 +-
 .../rel/rules/ReduceExpressionsRule.java        |   14 +-
 .../apache/calcite/rel/rules/SemiJoinRule.java  |   36 +-
 .../rel/rules/SortJoinTransposeRule.java        |    1 -
 .../rel/rules/SortProjectTransposeRule.java     |    2 +-
 .../calcite/rel/rules/SubQueryRemoveRule.java   |    9 +-
 .../rel/rules/UnionPullUpConstantsRule.java     |    2 +-
 .../calcite/rel/rules/ValuesReduceRule.java     |    6 +-
 .../apache/calcite/rel/stream/StreamRules.java  |    9 +-
 .../calcite/rel/type/DynamicRecordTypeImpl.java |    5 +-
 .../calcite/rel/type/RelDataTypeFactory.java    |    5 +-
 .../rel/type/RelDataTypeFactoryImpl.java        |   40 +-
 .../calcite/rel/type/RelDataTypeField.java      |   14 +-
 .../calcite/rel/type/RelDataTypeImpl.java       |   36 +-
 .../apache/calcite/rel/type/RelRecordType.java  |    5 +-
 .../java/org/apache/calcite/rex/RexBuilder.java |   27 +-
 .../java/org/apache/calcite/rex/RexCall.java    |    6 +-
 .../apache/calcite/rex/RexCorrelVariable.java   |    4 +-
 .../org/apache/calcite/rex/RexExecutorImpl.java |    7 +-
 .../java/org/apache/calcite/rex/RexLiteral.java |    4 +-
 .../java/org/apache/calcite/rex/RexOver.java    |    3 +-
 .../calcite/rex/RexPermuteInputsShuttle.java    |    2 +-
 .../java/org/apache/calcite/rex/RexProgram.java |    5 +-
 .../apache/calcite/rex/RexProgramBuilder.java   |    7 +-
 .../java/org/apache/calcite/rex/RexShuttle.java |    9 +-
 .../org/apache/calcite/rex/RexSimplify.java     |   22 +-
 .../rex/RexSqlStandardConvertletTable.java      |   80 +-
 .../org/apache/calcite/rex/RexSubQuery.java     |    4 +-
 .../java/org/apache/calcite/rex/RexUtil.java    |  243 ++-
 .../apache/calcite/runtime/BinarySearch.java    |    8 +-
 .../org/apache/calcite/runtime/Enumerables.java |   32 +-
 .../org/apache/calcite/runtime/FlatLists.java   |   24 +
 .../apache/calcite/runtime/GeoFunctions.java    |    7 +-
 .../java/org/apache/calcite/runtime/Hook.java   |   85 +-
 .../org/apache/calcite/runtime/HttpUtils.java   |    9 +-
 .../apache/calcite/runtime/PredicateImpl.java   |    3 +
 .../calcite/runtime/ResultSetEnumerable.java    |  138 +-
 .../apache/calcite/runtime/SqlFunctions.java    |   68 +-
 .../calcite/schema/FunctionParameter.java       |    8 -
 .../java/org/apache/calcite/schema/Schemas.java |   63 +-
 .../org/apache/calcite/schema/Statistics.java   |   12 +-
 .../java/org/apache/calcite/schema/Table.java   |    6 +-
 .../calcite/schema/impl/AbstractSchema.java     |    4 -
 .../schema/impl/AggregateFunctionImpl.java      |    6 +-
 .../schema/impl/MaterializedViewTable.java      |    5 +-
 .../schema/impl/ModifiableViewTable.java        |    4 +-
 .../apache/calcite/schema/impl/StarTable.java   |    4 +-
 .../org/apache/calcite/sql/SqlBasicCall.java    |    7 +-
 .../calcite/sql/SqlBinaryStringLiteral.java     |   14 +-
 .../java/org/apache/calcite/sql/SqlCall.java    |    2 +-
 .../org/apache/calcite/sql/SqlCallBinding.java  |   26 +-
 .../calcite/sql/SqlCharStringLiteral.java       |   13 +-
 .../org/apache/calcite/sql/SqlDataTypeSpec.java |    6 +-
 .../java/org/apache/calcite/sql/SqlDdl.java     |    4 +-
 .../apache/calcite/sql/SqlDescribeSchema.java   |    2 +-
 .../apache/calcite/sql/SqlDescribeTable.java    |    2 +-
 .../java/org/apache/calcite/sql/SqlDialect.java |   51 +-
 .../org/apache/calcite/sql/SqlFunction.java     |   14 +-
 .../org/apache/calcite/sql/SqlIdentifier.java   |   28 +-
 .../calcite/sql/SqlIntervalQualifier.java       |    5 +-
 .../apache/calcite/sql/SqlJdbcFunctionCall.java |    4 +-
 .../java/org/apache/calcite/sql/SqlJoin.java    |   11 +-
 .../apache/calcite/sql/SqlMatchRecognize.java   |   19 +-
 .../java/org/apache/calcite/sql/SqlNode.java    |    5 +-
 .../org/apache/calcite/sql/SqlNodeList.java     |    2 +-
 .../org/apache/calcite/sql/SqlOperator.java     |    2 +-
 .../java/org/apache/calcite/sql/SqlSelect.java  |   11 +-
 .../org/apache/calcite/sql/SqlSetOption.java    |    5 +-
 .../apache/calcite/sql/SqlSpecialOperator.java  |    2 +-
 .../java/org/apache/calcite/sql/SqlUtil.java    |  140 +-
 .../apache/calcite/sql/advise/SqlAdvisor.java   |   19 +-
 .../sql/advise/SqlAdvisorGetHintsFunction.java  |   14 +-
 .../calcite/sql/advise/SqlAdvisorHint.java      |    2 +-
 .../sql/dialect/JethroDataSqlDialect.java       |    8 +-
 .../calcite/sql/dialect/MssqlSqlDialect.java    |    2 -
 .../calcite/sql/fun/OracleSqlOperatorTable.java |   27 +-
 .../sql/fun/SqlDatetimeSubtractionOperator.java |    2 -
 .../calcite/sql/fun/SqlLeadLagAggFunction.java  |   26 +-
 .../calcite/sql/fun/SqlQuantifyOperator.java    |    4 +-
 .../calcite/sql/fun/SqlStdOperatorTable.java    |    4 +-
 .../sql/fun/SqlTimestampAddFunction.java        |   13 +-
 .../sql/parser/SqlAbstractParserImpl.java       |    4 +-
 .../apache/calcite/sql/parser/SqlParser.java    |   21 +-
 .../apache/calcite/sql/parser/SqlParserPos.java |   12 +-
 .../calcite/sql/parser/SqlParserUtil.java       |   73 +-
 .../calcite/sql/pretty/SqlPrettyWriter.java     |    2 +-
 .../apache/calcite/sql/type/ArraySqlType.java   |    4 +-
 .../sql/type/ComparableOperandTypeChecker.java  |    4 +-
 .../sql/type/CompositeOperandTypeChecker.java   |    6 +-
 .../sql/type/FamilyOperandTypeChecker.java      |    6 +-
 .../org/apache/calcite/sql/type/InferTypes.java |   87 +-
 .../calcite/sql/type/IntervalSqlType.java       |   10 +-
 .../apache/calcite/sql/type/OperandTypes.java   |   18 +-
 .../apache/calcite/sql/type/ReturnTypes.java    |  576 ++++----
 .../sql/type/SqlTypeAssignmentRules.java        |   16 +-
 .../calcite/sql/type/SqlTypeTransforms.java     |   98 +-
 .../apache/calcite/sql/type/SqlTypeUtil.java    |   11 +-
 .../org/apache/calcite/sql/util/SqlShuttle.java |    2 +-
 .../apache/calcite/sql/validate/AggChecker.java |    2 +-
 .../apache/calcite/sql/validate/AggVisitor.java |    5 +-
 .../sql/validate/AggregatingSelectScope.java    |   29 +-
 .../calcite/sql/validate/CatalogScope.java      |   22 +-
 .../calcite/sql/validate/DelegatingScope.java   |    2 +-
 .../sql/validate/IdentifierNamespace.java       |    6 +-
 .../apache/calcite/sql/validate/ListScope.java  |    8 +-
 .../calcite/sql/validate/SchemaNamespace.java   |    4 +-
 .../apache/calcite/sql/validate/ScopeChild.java |   15 -
 .../sql/validate/SqlIdentifierMoniker.java      |    5 +-
 .../calcite/sql/validate/SqlMonikerImpl.java    |    3 +-
 .../sql/validate/SqlUserDefinedAggFunction.java |   14 +-
 .../sql/validate/SqlUserDefinedFunction.java    |    3 +-
 .../sql/validate/SqlUserDefinedTableMacro.java  |   12 +-
 .../calcite/sql/validate/SqlValidatorImpl.java  |   58 +-
 .../calcite/sql/validate/SqlValidatorScope.java |   20 +-
 .../calcite/sql/validate/SqlValidatorUtil.java  |   44 +-
 .../calcite/sql/validate/TableNamespace.java    |   25 +-
 .../apache/calcite/sql/validate/TableScope.java |    6 +-
 .../calcite/sql/validate/UnnestNamespace.java   |    1 -
 .../sql2rel/ReflectiveConvertletTable.java      |   57 +-
 .../apache/calcite/sql2rel/RelDecorrelator.java |  128 +-
 .../apache/calcite/sql2rel/RelFieldTrimmer.java |    9 +-
 .../sql2rel/RelStructuredTypeFlattener.java     |   28 +-
 .../calcite/sql2rel/SqlToRelConverter.java      |   85 +-
 .../sql2rel/StandardConvertletTable.java        |  311 ++--
 .../org/apache/calcite/tools/Frameworks.java    |   19 +-
 .../java/org/apache/calcite/tools/Programs.java |  177 +--
 .../org/apache/calcite/tools/RelBuilder.java    |  145 +-
 .../java/org/apache/calcite/util/BitSets.java   |   28 +-
 .../org/apache/calcite/util/CancelFlag.java     |    5 +-
 .../org/apache/calcite/util/Compatible.java     |   96 +-
 .../apache/calcite/util/CompatibleGuava11.java  |   31 +-
 .../apache/calcite/util/ImmutableBitSet.java    |   70 +-
 .../calcite/util/ImmutableNullableList.java     |    6 +-
 .../apache/calcite/util/IntegerIntervalSet.java |   20 +-
 .../java/org/apache/calcite/util/NameSet.java   |   17 +-
 .../main/java/org/apache/calcite/util/Pair.java |  255 ++--
 .../calcite/util/PartiallyOrderedSet.java       |   41 +-
 .../calcite/util/PrecedenceClimbingParser.java  |   10 +-
 .../org/apache/calcite/util/ReflectUtil.java    |    4 +-
 .../java/org/apache/calcite/util/Sources.java   |    7 +-
 .../org/apache/calcite/util/TryThreadLocal.java |   12 +-
 .../calcite/util/UnmodifiableArrayList.java     |    5 +-
 .../main/java/org/apache/calcite/util/Util.java |  112 +-
 .../java/org/apache/calcite/util/XmlOutput.java |    4 +-
 .../util/graph/BreadthFirstIterator.java        |    6 +-
 .../util/graph/DefaultDirectedGraph.java        |    2 +-
 .../apache/calcite/util/graph/DefaultEdge.java  |    6 +-
 .../calcite/util/graph/DepthFirstIterator.java  |    8 +-
 .../util/graph/TopologicalOrderIterator.java    |    6 +-
 .../calcite/util/javac/JavaCompilerArgs.java    |    6 +-
 .../apache/calcite/util/mapping/Mappings.java   |   60 +-
 .../apache/calcite/util/trace/CalciteTrace.java |    6 +-
 .../calcite/jdbc/CalciteRemoteDriverTest.java   |   84 +-
 .../org/apache/calcite/plan/RelOptUtilTest.java |    7 +-
 .../org/apache/calcite/plan/RelWriterTest.java  |  100 +-
 .../calcite/plan/volcano/ComboRuleTest.java     |    1 -
 .../plan/volcano/TraitConversionTest.java       |    1 -
 .../plan/volcano/TraitPropagationTest.java      |    9 +-
 .../prepare/LookupOperatorOverloadsTest.java    |    2 +-
 .../apache/calcite/profile/ProfilerTest.java    |  374 +++--
 .../apache/calcite/rel/RelCollationTest.java    |    9 +-
 .../rel/rel2sql/RelToSqlConverterTest.java      |   21 +-
 .../calcite/rel/rules/DateRangeRulesTest.java   |   20 +-
 .../org/apache/calcite/rex/RexExecutorTest.java |  302 ++--
 .../calcite/runtime/BinarySearchTest.java       |    4 +-
 .../apache/calcite/runtime/EnumerablesTest.java |   79 +-
 .../calcite/sql/parser/SqlParserTest.java       |    6 +-
 .../calcite/sql/test/DefaultSqlTestFactory.java |   53 +-
 .../calcite/sql/test/SqlOperatorBaseTest.java   |   23 +-
 .../apache/calcite/sql/test/SqlTesterImpl.java  |   64 +-
 .../org/apache/calcite/sql/test/SqlTests.java   |   21 +-
 .../calcite/sql/type/SqlTypeFactoryTest.java    |    1 -
 .../org/apache/calcite/test/CalciteAssert.java  |  489 +++---
 .../apache/calcite/test/CollectionTypeTest.java |    3 +-
 .../calcite/test/ExceptionMessageTest.java      |    7 +-
 .../test/FoodMartLatticeStatisticProvider.java  |    8 +-
 .../calcite/test/InduceGroupingTypeTest.java    |   29 +-
 .../apache/calcite/test/InterpreterTest.java    |    5 +-
 .../apache/calcite/test/JdbcAdapterTest.java    |  201 ++-
 .../calcite/test/JdbcFrontJdbcBackTest.java     |  128 +-
 .../calcite/test/JdbcFrontLinqBackTest.java     |   57 +-
 .../java/org/apache/calcite/test/JdbcTest.java  | 1392 ++++++++----------
 .../org/apache/calcite/test/LatticeTest.java    |  103 +-
 .../calcite/test/LinqFrontJdbcBackTest.java     |    3 +-
 .../java/org/apache/calcite/test/Matchers.java  |   37 +-
 .../calcite/test/MaterializationTest.java       |   79 +-
 .../apache/calcite/test/MockCatalogReader.java  |   41 +-
 .../apache/calcite/test/MockRelOptPlanner.java  |    6 +-
 .../calcite/test/MultiJdbcSchemaJoinTest.java   |    3 +-
 .../org/apache/calcite/test/MutableRelTest.java |    4 +-
 .../org/apache/calcite/test/QuidemTest.java     |   77 +-
 .../calcite/test/ReflectiveSchemaTest.java      |  209 ++-
 .../org/apache/calcite/test/RelBuilderTest.java |    2 +-
 .../apache/calcite/test/RelMetadataTest.java    |  209 ++-
 .../apache/calcite/test/RelOptRulesTest.java    |   94 +-
 .../org/apache/calcite/test/RelOptTestBase.java |   66 +-
 .../org/apache/calcite/test/RexProgramTest.java |    5 +-
 .../apache/calcite/test/ScannableTableTest.java |   19 +-
 .../org/apache/calcite/test/SqlLineTest.java    |    2 +-
 .../org/apache/calcite/test/SqlTestGen.java     |    2 +-
 .../test/SqlToRelConverterExtendedTest.java     |   39 +-
 .../calcite/test/SqlToRelConverterTest.java     |   28 +-
 .../apache/calcite/test/SqlToRelTestBase.java   |   79 +-
 .../apache/calcite/test/SqlValidatorTest.java   |   57 +-
 .../calcite/test/SqlValidatorTestCase.java      |   11 +-
 .../org/apache/calcite/test/StreamTest.java     |  147 +-
 .../apache/calcite/test/TableFunctionTest.java  |   30 +-
 .../java/org/apache/calcite/test/UdfTest.java   |   48 +-
 .../ConcurrentTestTimedCommandGenerator.java    |   10 +-
 .../apache/calcite/tools/FrameworksTest.java    |  158 +-
 .../org/apache/calcite/tools/PlannerTest.java   |    3 +-
 .../org/apache/calcite/util/BitSetsTest.java    |    9 +-
 .../org/apache/calcite/util/ChunkListTest.java  |  199 ++-
 .../calcite/util/ImmutableBitSetTest.java       |   10 +-
 .../calcite/util/PartiallyOrderedSetTest.java   |  142 +-
 .../calcite/util/PermutationTestCase.java       |    1 -
 .../util/PrecedenceClimbingParserTest.java      |   11 +-
 .../java/org/apache/calcite/util/Smalls.java    |   49 +-
 .../java/org/apache/calcite/util/UtilTest.java  |  117 +-
 .../calcite/util/graph/DirectedGraphTest.java   |   20 +-
 .../calcite/util/mapping/MappingTest.java       |    2 +-
 .../adapter/druid/DefaultDimensionSpec.java     |    6 +-
 .../adapter/druid/DruidConnectionImpl.java      |    6 +-
 .../adapter/druid/DruidDateTimeUtils.java       |   46 +-
 .../calcite/adapter/druid/DruidExpressions.java |   27 +-
 .../calcite/adapter/druid/DruidJsonFilter.java  |   12 +-
 .../calcite/adapter/druid/DruidQuery.java       |   48 +-
 .../calcite/adapter/druid/DruidRules.java       |   19 +-
 .../calcite/adapter/druid/DruidSchema.java      |   39 +-
 .../calcite/adapter/druid/DruidTable.java       |   16 +-
 .../adapter/druid/ExtractionDimensionSpec.java  |    6 +-
 .../adapter/druid/FloorOperatorConversion.java  |    1 -
 .../calcite/adapter/druid/Granularities.java    |    8 +-
 .../adapter/druid/NaryOperatorConverter.java    |    7 +-
 .../calcite/adapter/druid/VirtualColumn.java    |    6 +-
 .../adapter/druid/DruidQueryFilterTest.java     |    4 +-
 .../org/apache/calcite/test/DruidAdapterIT.java |  239 ++-
 .../apache/calcite/test/DruidAdapterIT2.java    |  237 ++-
 elasticsearch2/pom.xml                          |    4 -
 .../Elasticsearch2Enumerator.java               |   46 +-
 .../elasticsearch2/Elasticsearch2Schema.java    |    8 +-
 .../EmbeddedElasticsearchNode.java              |    3 +-
 .../EmbeddedElasticsearchPolicy.java            |    6 +-
 .../calcite/test/Elasticsearch2AdapterIT.java   |  265 ++++
 .../calcite/test/ElasticsearchChecker.java      |   22 +-
 elasticsearch5/pom.xml                          |    4 -
 .../Elasticsearch5Enumerator.java               |   44 +-
 .../elasticsearch5/Elasticsearch5Schema.java    |    7 +-
 .../EmbeddedElasticsearchNode.java              |    3 +-
 .../EmbeddedElasticsearchPolicy.java            |    7 +-
 .../calcite/test/Elasticsearch5AdapterIT.java   |  265 ++++
 .../calcite/test/ElasticsearchChecker.java      |   28 +-
 .../calcite/adapter/csv/CsvEnumerator.java      |    4 +-
 .../apache/calcite/adapter/csv/CsvSchema.java   |   14 +-
 .../java/org/apache/calcite/test/CsvTest.java   |  134 +-
 .../org/apache/calcite/example/maze/Maze.java   |   26 +-
 .../apache/calcite/example/maze/MazeTable.java  |    7 +-
 .../calcite/adapter/file/FileRowConverter.java  |    6 +-
 .../apache/calcite/adapter/file/FileSchema.java |   14 +-
 .../apache/calcite/adapter/file/SqlTest.java    |   80 +-
 .../calcite/adapter/geode/rel/GeodeRules.java   |   13 +-
 .../adapter/geode/rel/GeodeSchemaFactory.java   |    2 +-
 .../geode/rel/GeodeToEnumerableConverter.java   |    8 +-
 .../geode/util/JavaTypeFactoryExtImpl.java      |    1 -
 .../adapter/geode/rel/BaseGeodeAdapterIT.java   |   32 +-
 .../apache/calcite/linq4j/DefaultQueryable.java |    2 +-
 .../calcite/linq4j/EnumerableDefaults.java      |  157 +-
 .../org/apache/calcite/linq4j/Extensions.java   |  111 +-
 .../org/apache/calcite/linq4j/GroupingImpl.java |    7 +-
 .../java/org/apache/calcite/linq4j/Linq4j.java  |   16 +-
 .../java/org/apache/calcite/linq4j/Ord.java     |   36 +-
 .../calcite/linq4j/QueryableDefaults.java       |    4 +-
 .../calcite/linq4j/QueryableRecorder.java       |   16 +-
 .../calcite/linq4j/function/Function1.java      |    6 +-
 .../calcite/linq4j/function/Functions.java      |   69 +-
 .../calcite/linq4j/function/Predicate1.java     |   12 +-
 .../calcite/linq4j/function/Predicate2.java     |   12 +-
 .../linq4j/tree/ClassDeclarationFinder.java     |   32 +-
 .../calcite/linq4j/tree/ConstantExpression.java |   29 +-
 .../linq4j/tree/ConstructorDeclaration.java     |   18 +-
 .../linq4j/tree/DeterministicCodeOptimizer.java |    2 +-
 .../apache/calcite/linq4j/tree/Expressions.java |   16 +-
 .../calcite/linq4j/tree/FunctionExpression.java |   38 +-
 .../calcite/linq4j/tree/MethodDeclaration.java  |    8 +-
 .../calcite/linq4j/tree/TryStatement.java       |    6 +-
 .../org/apache/calcite/linq4j/tree/Types.java   |    6 +-
 .../test/java/com/example/Linq4jExample.java    |   27 +-
 .../calcite/linq4j/function/FunctionTest.java   |   61 +-
 .../calcite/linq4j/test/CorrelateJoinTest.java  |   42 +-
 .../calcite/linq4j/test/DeterministicTest.java  |   67 +-
 .../calcite/linq4j/test/ExpressionTest.java     |   27 +-
 .../apache/calcite/linq4j/test/Linq4jTest.java  |  727 +++------
 .../adapter/mongodb/MongoEnumerator.java        |   28 +-
 .../calcite/adapter/mongodb/MongoSchema.java    |    5 +-
 .../mongodb/MongoToEnumerableConverter.java     |    8 +-
 .../mongodb/MongoToEnumerableConverterRule.java |    4 +-
 .../adapter/mongodb/MongoAdapterTest.java       |   51 +-
 .../adapter/mongodb/MongoDatabasePolicy.java    |    7 +-
 .../apache/calcite/test/MongoAssertions.java    |   41 +-
 .../calcite/adapter/pig/PigAggregate.java       |   12 +-
 .../apache/calcite/adapter/pig/PigFilter.java   |    4 +-
 .../org/apache/calcite/adapter/pig/PigRel.java  |    4 +-
 .../calcite/adapter/pig/PigTableScan.java       |    4 +-
 .../org/apache/calcite/test/PigAdapterTest.java |   21 +-
 .../java/org/apache/calcite/piglet/Ast.java     |   22 +-
 piglet/src/main/javacc/PigletParser.jj          |   13 +-
 .../java/org/apache/calcite/test/Fluent.java    |   50 +-
 .../calcite/adapter/os/DuTableFunction.java     |    9 +-
 .../apache/calcite/adapter/os/Processes.java    |    3 +-
 .../org/apache/calcite/adapter/os/SqlShell.java |   57 +-
 .../calcite/adapter/tpcds/TpcdsSchema.java      |    5 +-
 .../calcite/chinook/EnvironmentFairy.java       |    7 +-
 .../calcite/adapter/os/OsAdapterTest.java       |  191 +--
 .../apache/calcite/adapter/tpcds/TpcdsTest.java |   35 +-
 .../apache/calcite/adapter/tpch/TpchTest.java   |   15 +-
 .../src/main/codegen/includes/parserImpls.ftl   |    6 +-
 .../calcite/sql/ddl/SqlCreateForeignSchema.java |    3 +-
 .../sql/ddl/SqlCreateMaterializedView.java      |    6 +-
 .../apache/calcite/sql/ddl/SqlCreateSchema.java |    7 +-
 .../apache/calcite/sql/ddl/SqlCreateTable.java  |   11 +-
 .../apache/calcite/sql/ddl/SqlCreateType.java   |    5 +-
 .../apache/calcite/sql/ddl/SqlCreateView.java   |    6 +-
 .../apache/calcite/sql/ddl/SqlDropObject.java   |    2 +-
 site/.gitignore                                 |    2 +-
 site/README.md                                  |    2 +-
 site/docker-compose.yml                         |    4 +-
 .../spark/EnumerableToSparkConverterRule.java   |    4 +-
 .../calcite/adapter/spark/HttpServer.java       |   22 +-
 .../adapter/spark/JdbcToSparkConverter.java     |    2 +-
 .../adapter/spark/JdbcToSparkConverterRule.java |    4 +-
 .../calcite/adapter/spark/SparkRules.java       |   48 +-
 .../apache/calcite/test/SplunkAdapterTest.java  |   68 +-
 src/main/config/forbidden-apis/signatures.txt   |   35 +
 525 files changed, 7983 insertions(+), 10608 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraRules.java
----------------------------------------------------------------------
diff --git a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraRules.java b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraRules.java
index 94091b2..cdf86dc 100644
--- a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraRules.java
+++ b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraRules.java
@@ -38,17 +38,14 @@ import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexVisitorImpl;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.function.Predicate;
 
 /**
  * Rules and relational operators for
@@ -95,7 +92,7 @@ public class CassandraRules {
 
     CassandraConverterRule(Class<? extends RelNode> clazz,
         String description) {
-      this(clazz, Predicates.<RelNode>alwaysTrue(), description);
+      this(clazz, r -> true, description);
     }
 
     <R extends RelNode> CassandraConverterRule(Class<R> clazz,
@@ -113,13 +110,9 @@ public class CassandraRules {
    */
   private static class CassandraFilterRule extends RelOptRule {
     private static final Predicate<LogicalFilter> PREDICATE =
-        new PredicateImpl<LogicalFilter>() {
-          public boolean test(LogicalFilter input) {
-            // TODO: Check for an equality predicate on the partition key
-            // Right now this just checks if we have a single top-level AND
-            return RelOptUtil.disjunctions(input.getCondition()).size() == 1;
-          }
-        };
+        // TODO: Check for an equality predicate on the partition key
+        // Right now this just checks if we have a single top-level AND
+        filter -> RelOptUtil.disjunctions(filter.getCondition()).size() == 1;
 
     private static final CassandraFilterRule INSTANCE = new CassandraFilterRule();
 
@@ -268,28 +261,21 @@ public class CassandraRules {
    * {@link CassandraSort}.
    */
   private static class CassandraSortRule extends RelOptRule {
-    private static final Predicate<Sort> SORT_PREDICATE =
-        new PredicateImpl<Sort>() {
-          public boolean test(Sort input) {
-            // Limits are handled by CassandraLimit
-            return input.offset == null && input.fetch == null;
-          }
-        };
-    private static final Predicate<CassandraFilter> FILTER_PREDICATE =
-        new PredicateImpl<CassandraFilter>() {
-          public boolean test(CassandraFilter input) {
-            // We can only use implicit sorting within a single partition
-            return input.isSinglePartition();
-          }
-        };
+
     private static final RelOptRuleOperand CASSANDRA_OP =
         operand(CassandraToEnumerableConverter.class,
-        operand(CassandraFilter.class, null, FILTER_PREDICATE, any()));
+            operandJ(CassandraFilter.class, null,
+                // We can only use implicit sorting within a single partition
+                CassandraFilter::isSinglePartition, any()));
 
     private static final CassandraSortRule INSTANCE = new CassandraSortRule();
 
     private CassandraSortRule() {
-      super(operand(Sort.class, null, SORT_PREDICATE, CASSANDRA_OP), "CassandraSortRule");
+      super(
+          operandJ(Sort.class, null,
+              // Limits are handled by CassandraLimit
+              sort -> sort.offset == null && sort.fetch == null, CASSANDRA_OP),
+          "CassandraSortRule");
     }
 
     public RelNode convert(Sort sort, CassandraFilter filter) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraSchema.java
----------------------------------------------------------------------
diff --git a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraSchema.java b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraSchema.java
index 709c7b4..f2bcdcd 100644
--- a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraSchema.java
+++ b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraSchema.java
@@ -19,7 +19,6 @@ package org.apache.calcite.adapter.cassandra;
 import org.apache.calcite.avatica.util.Casing;
 import org.apache.calcite.jdbc.CalciteSchema;
 import org.apache.calcite.rel.RelFieldCollation;
-import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeImpl;
 import org.apache.calcite.rel.type.RelDataTypeSystem;
@@ -50,7 +49,6 @@ import com.datastax.driver.core.KeyspaceMetadata;
 import com.datastax.driver.core.MaterializedViewMetadata;
 import com.datastax.driver.core.Session;
 import com.datastax.driver.core.TableMetadata;
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
@@ -113,11 +111,8 @@ public class CassandraSchema extends AbstractSchema {
     this.parentSchema = parentSchema;
     this.name = name;
 
-    this.hook = Hook.TRIMMED.add(new Function<RelNode, Void>() {
-      public Void apply(RelNode node) {
-        CassandraSchema.this.addMaterializedViews();
-        return null;
-      }
+    this.hook = Hook.TRIMMED.add(node -> {
+      CassandraSchema.this.addMaterializedViews();
     });
   }
 
@@ -177,19 +172,19 @@ public class CassandraSchema extends AbstractSchema {
     }
 
     List<ColumnMetadata> partitionKey = table.getPartitionKey();
-    List<String> pKeyFields = new ArrayList<String>();
+    List<String> pKeyFields = new ArrayList<>();
     for (ColumnMetadata column : partitionKey) {
       pKeyFields.add(column.getName());
     }
 
     List<ColumnMetadata> clusteringKey = table.getClusteringColumns();
-    List<String> cKeyFields = new ArrayList<String>();
+    List<String> cKeyFields = new ArrayList<>();
     for (ColumnMetadata column : clusteringKey) {
       cKeyFields.add(column.getName());
     }
 
-    return Pair.of((List<String>) ImmutableList.copyOf(pKeyFields),
-        (List<String>) ImmutableList.copyOf(cKeyFields));
+    return Pair.of(ImmutableList.copyOf(pKeyFields),
+        ImmutableList.copyOf(cKeyFields));
   }
 
   /** Get the collation of all clustering key columns.
@@ -205,7 +200,7 @@ public class CassandraSchema extends AbstractSchema {
     }
 
     List<ClusteringOrder> clusteringOrder = table.getClusteringOrder();
-    List<RelFieldCollation> keyCollations = new ArrayList<RelFieldCollation>();
+    List<RelFieldCollation> keyCollations = new ArrayList<>();
 
     int i = 0;
     for (ClusteringOrder order : clusteringOrder) {
@@ -237,7 +232,7 @@ public class CassandraSchema extends AbstractSchema {
       StringBuilder queryBuilder = new StringBuilder("SELECT ");
 
       // Add all the selected columns to the query
-      List<String> columnNames = new ArrayList<String>();
+      List<String> columnNames = new ArrayList<>();
       for (ColumnMetadata column : view.getColumns()) {
         columnNames.add("\"" + column.getName() + "\"");
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraTable.java
----------------------------------------------------------------------
diff --git a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraTable.java b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraTable.java
index 57293b5..9f72116 100644
--- a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraTable.java
+++ b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraTable.java
@@ -42,8 +42,8 @@ import org.apache.calcite.util.Util;
 
 import com.datastax.driver.core.ResultSet;
 import com.datastax.driver.core.Session;
+import com.google.common.collect.ImmutableList;
 
-import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -97,9 +97,8 @@ public class CassandraTable extends AbstractQueryableTable
   }
 
   public Enumerable<Object> query(final Session session) {
-    return query(session, Collections.<Map.Entry<String, Class>>emptyList(),
-        Collections.<Map.Entry<String, String>>emptyList(),
-        Collections.<String>emptyList(), Collections.<String>emptyList(), 0, -1);
+    return query(session, ImmutableList.of(), ImmutableList.of(),
+        ImmutableList.of(), ImmutableList.of(), 0, -1);
   }
 
   /** Executes a CQL query on the underlying table.
@@ -118,12 +117,12 @@ public class CassandraTable extends AbstractQueryableTable
     final RelDataTypeFactory.Builder fieldInfo = typeFactory.builder();
     final RelDataType rowType = getRowType(typeFactory);
 
-    Function1<String, Void> addField = new Function1<String, Void>() {
-      public Void apply(String fieldName) {
-        SqlTypeName typeName = rowType.getField(fieldName, true, false).getType().getSqlTypeName();
-        fieldInfo.add(fieldName, typeFactory.createSqlType(typeName)).nullable(true);
-        return null;
-      }
+    Function1<String, Void> addField = fieldName -> {
+      SqlTypeName typeName =
+          rowType.getField(fieldName, true, false).getType().getSqlTypeName();
+      fieldInfo.add(fieldName, typeFactory.createSqlType(typeName))
+          .nullable(true);
+      return null;
     };
 
     if (selectFields.isEmpty()) {
@@ -143,26 +142,24 @@ public class CassandraTable extends AbstractQueryableTable
     if (selectFields.isEmpty()) {
       selectString = "*";
     } else {
-      selectString = Util.toString(new Iterable<String>() {
-        public Iterator<String> iterator() {
-          final Iterator<Map.Entry<String, String>> selectIterator =
-              selectFields.iterator();
+      selectString = Util.toString(() -> {
+        final Iterator<Map.Entry<String, String>> selectIterator =
+            selectFields.iterator();
 
-          return new Iterator<String>() {
-            @Override public boolean hasNext() {
-              return selectIterator.hasNext();
-            }
+        return new Iterator<String>() {
+          @Override public boolean hasNext() {
+            return selectIterator.hasNext();
+          }
 
-            @Override public String next() {
-              Map.Entry<String, String> entry = selectIterator.next();
-              return entry.getKey() + " AS " + entry.getValue();
-            }
+          @Override public String next() {
+            Map.Entry<String, String> entry = selectIterator.next();
+            return entry.getKey() + " AS " + entry.getValue();
+          }
 
-            @Override public void remove() {
-              throw new UnsupportedOperationException();
-            }
-          };
-        }
+          @Override public void remove() {
+            throw new UnsupportedOperationException();
+          }
+        };
       }, "", ", ", "");
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverter.java
----------------------------------------------------------------------
diff --git a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverter.java b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverter.java
index ab55fff..5961aed 100644
--- a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverter.java
+++ b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverter.java
@@ -39,7 +39,6 @@ import org.apache.calcite.runtime.Hook;
 import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.util.AbstractList;
@@ -144,12 +143,7 @@ public class CassandraToEnumerableConverter
   /** E.g. {@code constantList("x", "y")} returns
    * {@code {ConstantExpression("x"), ConstantExpression("y")}}. */
   private static <T> List<Expression> constantList(List<T> values) {
-    return Lists.transform(values,
-        new Function<T, Expression>() {
-          public Expression apply(T a0) {
-            return Expressions.constant(a0);
-          }
-        });
+    return Lists.transform(values, Expressions::constant);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverterRule.java
----------------------------------------------------------------------
diff --git a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverterRule.java b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverterRule.java
index abcf155..9184c30 100644
--- a/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverterRule.java
+++ b/cassandra/src/main/java/org/apache/calcite/adapter/cassandra/CassandraToEnumerableConverterRule.java
@@ -23,7 +23,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -40,7 +40,7 @@ public class CassandraToEnumerableConverterRule extends ConverterRule {
    */
   public CassandraToEnumerableConverterRule(
       RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(),
+    super(RelNode.class, (Predicate<RelNode>) r -> true,
         CassandraRel.CONVENTION, EnumerableConvention.INSTANCE,
         relBuilderFactory, "CassandraToEnumerableConverterRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/codegen/templates/Parser.jj
----------------------------------------------------------------------
diff --git a/core/src/main/codegen/templates/Parser.jj b/core/src/main/codegen/templates/Parser.jj
index 6baa30b..4096cfe 100644
--- a/core/src/main/codegen/templates/Parser.jj
+++ b/core/src/main/codegen/templates/Parser.jj
@@ -106,8 +106,6 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
 
-import com.google.common.collect.Lists;
-
 import org.slf4j.Logger;
 
 import java.io.Reader;
@@ -1010,7 +1008,7 @@ SqlNode SqlStmtEof() :
  */
 SqlSelect SqlSelect() :
 {
-    final List<SqlLiteral> keywords = Lists.newArrayList();
+    final List<SqlLiteral> keywords = new ArrayList<SqlLiteral>();
     final SqlNodeList keywordList;
     List<SqlNode> selectList;
     final SqlNode fromClause;
@@ -1261,7 +1259,7 @@ SqlNode NamedRoutineCall(
     ExprContext exprContext) :
 {
     SqlIdentifier name;
-    final List<SqlNode> list = Lists.newArrayList();
+    final List<SqlNode> list = new ArrayList<SqlNode>();
     final Span s;
 }
 {
@@ -1290,7 +1288,7 @@ SqlNode NamedRoutineCall(
  */
 SqlNode SqlInsert() :
 {
-    final List<SqlLiteral> keywords = Lists.newArrayList();
+    final List<SqlLiteral> keywords = new ArrayList<SqlLiteral>();
     final SqlNodeList keywordList;
     SqlNode table;
     SqlNodeList extendList = null;
@@ -1498,7 +1496,7 @@ SqlUpdate WhenMatchedClause(SqlNode table, SqlIdentifier alias) :
 SqlInsert WhenNotMatchedClause(SqlNode table) :
 {
     final Span insertSpan, valuesSpan;
-    final List<SqlLiteral> keywords = Lists.newArrayList();
+    final List<SqlLiteral> keywords = new ArrayList<SqlLiteral>();
     final SqlNodeList keywordList;
     SqlNodeList insertColumnList = null;
     SqlNode rowConstructor;
@@ -1981,7 +1979,7 @@ SqlNode TableRef2(boolean lateral) :
 SqlNodeList ExtendList() :
 {
     final Span s;
-    List<SqlNode> list = Lists.newArrayList();
+    List<SqlNode> list = new ArrayList<SqlNode>();
 }
 {
     <LPAREN> { s = span(); }
@@ -2205,7 +2203,7 @@ SqlNode WhereOpt() :
  */
 SqlNodeList GroupByOpt() :
 {
-    List<SqlNode> list = Lists.newArrayList();
+    List<SqlNode> list = new ArrayList<SqlNode>();
     final Span s;
 }
 {
@@ -2221,7 +2219,7 @@ SqlNodeList GroupByOpt() :
 
 List<SqlNode> GroupingElementList() :
 {
-    List<SqlNode> list = Lists.newArrayList();
+    List<SqlNode> list = new ArrayList<SqlNode>();
     SqlNode e;
 }
 {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/clone/ArrayTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/clone/ArrayTable.java b/core/src/main/java/org/apache/calcite/adapter/clone/ArrayTable.java
index c4b02d2..c4579e6 100644
--- a/core/src/main/java/org/apache/calcite/adapter/clone/ArrayTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/clone/ArrayTable.java
@@ -40,11 +40,11 @@ import org.apache.calcite.util.Pair;
 
 import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.lang.reflect.Array;
 import java.lang.reflect.Type;
 import java.util.AbstractList;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
@@ -72,7 +72,7 @@ class ArrayTable extends AbstractQueryableTable implements ScannableTable {
   }
 
   public Statistic getStatistic() {
-    final List<ImmutableBitSet> keys = Lists.newArrayList();
+    final List<ImmutableBitSet> keys = new ArrayList<>();
     final Content content = supplier.get();
     for (Ord<Column> ord : Ord.zip(content.columns)) {
       if (ord.e.cardinality == content.size) {
@@ -280,7 +280,7 @@ class ArrayTable extends AbstractQueryableTable implements ScannableTable {
     public Object freeze(ColumnLoader.ValueSet valueSet, int[] sources) {
       // We assume the values have been canonized.
       final List<Comparable> list = permuteList(valueSet.values, sources);
-      return list.toArray(new Comparable[list.size()]);
+      return list.toArray(new Comparable[0]);
     }
 
     public Object permute(Object dataSet, int[] sources) {
@@ -816,7 +816,7 @@ class ArrayTable extends AbstractQueryableTable implements ScannableTable {
       this(columns, size,
           sortField >= 0
               ? RelCollations.createSingleton(sortField)
-              : ImmutableList.<RelCollation>of());
+              : ImmutableList.of());
     }
 
     @SuppressWarnings("unchecked")

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/clone/CloneSchema.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/clone/CloneSchema.java b/core/src/main/java/org/apache/calcite/adapter/clone/CloneSchema.java
index fe7cb92..0b5bb25 100644
--- a/core/src/main/java/org/apache/calcite/adapter/clone/CloneSchema.java
+++ b/core/src/main/java/org/apache/calcite/adapter/clone/CloneSchema.java
@@ -34,7 +34,6 @@ import org.apache.calcite.schema.Schemas;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.AbstractSchema;
 
-import com.google.common.base.Supplier;
 import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;
 
@@ -85,7 +84,7 @@ public class CloneSchema extends AbstractSchema {
     final JavaTypeFactory typeFactory =
         ((CalciteConnection) queryProvider).getTypeFactory();
     return createCloneTable(typeFactory, Schemas.proto(sourceTable),
-        ImmutableList.<RelCollation>of(), null, queryable);
+        ImmutableList.of(), null, queryable);
   }
 
   @Deprecated // to be removed before 2.0
@@ -93,8 +92,8 @@ public class CloneSchema extends AbstractSchema {
       final RelProtoDataType protoRowType,
       final List<ColumnMetaData.Rep> repList,
       final Enumerable<T> source) {
-    return createCloneTable(typeFactory, protoRowType,
-        ImmutableList.<RelCollation>of(), repList, source);
+    return createCloneTable(typeFactory, protoRowType, ImmutableList.of(),
+        repList, source);
   }
 
   public static <T> Table createCloneTable(final JavaTypeFactory typeFactory,
@@ -115,21 +114,18 @@ public class CloneSchema extends AbstractSchema {
     return new ArrayTable(
         elementType,
         protoRowType,
-        Suppliers.memoize(
-            new Supplier<ArrayTable.Content>() {
-              public ArrayTable.Content get() {
-                final ColumnLoader loader =
-                    new ColumnLoader<>(typeFactory, source, protoRowType,
-                        repList);
-                final List<RelCollation> collation2 =
-                    collations.isEmpty()
-                        && loader.sortField >= 0
-                        ? RelCollations.createSingleton(loader.sortField)
-                        : collations;
-                return new ArrayTable.Content(loader.representationValues,
-                    loader.size(), collation2);
-              }
-            }));
+        Suppliers.memoize(() -> {
+          final ColumnLoader loader =
+              new ColumnLoader<>(typeFactory, source, protoRowType,
+                  repList);
+          final List<RelCollation> collation2 =
+              collations.isEmpty()
+                  && loader.sortField >= 0
+                  ? RelCollations.createSingleton(loader.sortField)
+                  : collations;
+          return new ArrayTable.Content(loader.representationValues,
+              loader.size(), collation2);
+        }));
   }
 
   /** Schema factory that creates a

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/clone/ColumnLoader.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/clone/ColumnLoader.java b/core/src/main/java/org/apache/calcite/adapter/clone/ColumnLoader.java
index acc4adc..558118f 100644
--- a/core/src/main/java/org/apache/calcite/adapter/clone/ColumnLoader.java
+++ b/core/src/main/java/org/apache/calcite/adapter/clone/ColumnLoader.java
@@ -26,7 +26,6 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rel.type.RelProtoDataType;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.lang.reflect.Type;
@@ -53,31 +52,6 @@ class ColumnLoader<T> {
       0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L};
   static final int[] LONG_S = {1, 2, 4, 8, 16, 32};
 
-  private static final Function<Timestamp, Long> TIMESTAMP_TO_LONG =
-      new Function<Timestamp, Long>() {
-        public Long apply(Timestamp a0) {
-          return a0 == null ? null : a0.getTime();
-        }
-      };
-
-  private static final Function<Time, Integer> TIME_TO_INT =
-      new Function<Time, Integer>() {
-        public Integer apply(Time a0) {
-          return a0 == null
-              ? null
-              : (int) (a0.getTime() % DateTimeUtils.MILLIS_PER_DAY);
-        }
-      };
-
-  private static final Function<Date, Integer> DATE_TO_INT =
-      new Function<Date, Integer>() {
-        public Integer apply(Date a0) {
-          return a0 == null
-              ? null
-              : (int) (a0.getTime() / DateTimeUtils.MILLIS_PER_DAY);
-        }
-      };
-
   public final List<T> list = new ArrayList<>();
   public final List<ArrayTable.Column> representationValues = new ArrayList<>();
   private final JavaTypeFactory typeFactory;
@@ -264,21 +238,26 @@ class ColumnLoader<T> {
       switch (rep) {
       case OBJECT:
       case JAVA_SQL_TIMESTAMP:
-        return Lists.transform(list, TIMESTAMP_TO_LONG);
+        return Lists.transform(list,
+            (Timestamp t) -> t == null ? null : t.getTime());
       }
       break;
     case TIME:
       switch (rep) {
       case OBJECT:
       case JAVA_SQL_TIME:
-        return Lists.transform(list, TIME_TO_INT);
+        return Lists.transform(list, (Time t) -> t == null
+            ? null
+            : (int) (t.getTime() % DateTimeUtils.MILLIS_PER_DAY));
       }
       break;
     case DATE:
       switch (rep) {
       case OBJECT:
       case JAVA_SQL_DATE:
-        return Lists.transform(list, DATE_TO_INT);
+        return Lists.transform(list, (Date d) -> d == null
+            ? null
+            : (int) (d.getTime() / DateTimeUtils.MILLIS_PER_DAY));
       }
       break;
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/clone/ListTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/clone/ListTable.java b/core/src/main/java/org/apache/calcite/adapter/clone/ListTable.java
index 3a0b9e8..d8ee05e 100644
--- a/core/src/main/java/org/apache/calcite/adapter/clone/ListTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/clone/ListTable.java
@@ -29,7 +29,6 @@ import org.apache.calcite.rel.type.RelProtoDataType;
 import org.apache.calcite.schema.SchemaPlus;
 import org.apache.calcite.schema.Statistic;
 import org.apache.calcite.schema.Statistics;
-import org.apache.calcite.util.ImmutableBitSet;
 
 import com.google.common.collect.ImmutableList;
 
@@ -64,7 +63,7 @@ class ListTable extends AbstractQueryableTable {
   }
 
   public Statistic getStatistic() {
-    return Statistics.of(list.size(), ImmutableList.<ImmutableBitSet>of());
+    return Statistics.of(list.size(), ImmutableList.of());
   }
 
   public <T> Queryable<T> asQueryable(final QueryProvider queryProvider,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchFilter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchFilter.java b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchFilter.java
index 2551556..06b39c0 100644
--- a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchFilter.java
+++ b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchFilter.java
@@ -42,7 +42,6 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 
-
 /**
  * Implementation of a {@link org.apache.calcite.rel.core.Filter}
  * relational expression in Elasticsearch.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchProject.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchProject.java b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchProject.java
index 961c8b0..63270db 100644
--- a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchProject.java
+++ b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchProject.java
@@ -28,14 +28,11 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.annotation.Nullable;
-
 /**
  * Implementation of {@link org.apache.calcite.rel.core.Project}
  * relational expression in Elasticsearch.
@@ -89,12 +86,7 @@ public class ElasticsearchProject extends Project implements ElasticsearchRel {
 
     StringBuilder query = new StringBuilder();
     if (scriptFields.isEmpty()) {
-      List<String> newList = Lists.transform(fields, new Function<String, String>() {
-        @Nullable
-        @Override public String apply(@Nullable String input) {
-          return ElasticsearchRules.quote(input);
-        }
-      });
+      List<String> newList = Lists.transform(fields, ElasticsearchRules::quote);
 
       final String findString = String.join(", ", newList);
       query.append("\"_source\" : [").append(findString).append("]");
@@ -102,11 +94,13 @@ public class ElasticsearchProject extends Project implements ElasticsearchRel {
       // if scripted fields are present, ES ignores _source attribute
       for (String field: fields) {
         scriptFields.add(ElasticsearchRules.quote(field) + ":{\"script\": "
-                // _source (ES2) vs params._source (ES5)
-                + "\"" + implementor.elasticsearchTable.scriptedFieldPrefix() + "."
-                + field + "\"}");
+            // _source (ES2) vs params._source (ES5)
+            + "\"" + implementor.elasticsearchTable.scriptedFieldPrefix() + "."
+            + field + "\"}");
       }
-      query.append("\"script_fields\": {" + String.join(", ", scriptFields) + "}");
+      query.append("\"script_fields\": {")
+          .append(String.join(", ", scriptFields))
+          .append("}");
     }
 
     for (String opfield : implementor.list) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchTableScan.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchTableScan.java b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchTableScan.java
index 33ca14f..1020faa 100644
--- a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchTableScan.java
+++ b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchTableScan.java
@@ -27,9 +27,8 @@ import org.apache.calcite.rel.core.TableScan;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Relational expression representing a scan of an Elasticsearch type.
@@ -54,7 +53,7 @@ public class ElasticsearchTableScan extends TableScan implements ElasticsearchRe
        RelOptTable table, AbstractElasticsearchTable elasticsearchTable,
        RelDataType projectRowType) {
     super(cluster, traitSet, table);
-    this.elasticsearchTable = Preconditions.checkNotNull(elasticsearchTable);
+    this.elasticsearchTable = Objects.requireNonNull(elasticsearchTable);
     this.projectRowType = projectRowType;
 
     assert getConvention() == ElasticsearchRel.CONVENTION;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverter.java b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverter.java
index 768f4e5..3cebd3c 100644
--- a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverter.java
+++ b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverter.java
@@ -21,7 +21,6 @@ import org.apache.calcite.adapter.enumerable.EnumerableRelImplementor;
 import org.apache.calcite.adapter.enumerable.JavaRowFormat;
 import org.apache.calcite.adapter.enumerable.PhysType;
 import org.apache.calcite.adapter.enumerable.PhysTypeImpl;
-
 import org.apache.calcite.linq4j.tree.BlockBuilder;
 import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
@@ -40,12 +39,10 @@ import org.apache.calcite.runtime.Hook;
 import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.util.AbstractList;
 import java.util.List;
-import javax.annotation.Nullable;
 
 /**
  * Relational expression representing a scan of a table in an Elasticsearch data source.
@@ -111,13 +108,7 @@ public class ElasticsearchToEnumerableConverter extends ConverterImpl implements
   /** E.g. {@code constantList("x", "y")} returns
    * {@code {ConstantExpression("x"), ConstantExpression("y")}}. */
   private static <T> List<Expression> constantList(List<T> values) {
-    return Lists.transform(values,
-        new Function<T, Expression>() {
-          @Nullable
-          @Override public Expression apply(@Nullable T t) {
-            return Expressions.constant(t);
-          }
-        });
+    return Lists.transform(values, Expressions::constant);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverterRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverterRule.java b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverterRule.java
index 9575d4f..756c078 100644
--- a/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverterRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchToEnumerableConverterRule.java
@@ -23,7 +23,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -40,7 +40,7 @@ public class ElasticsearchToEnumerableConverterRule extends ConverterRule {
    */
   public ElasticsearchToEnumerableConverterRule(
       RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(),
+    super(RelNode.class, (Predicate<RelNode>) r -> true,
         ElasticsearchRel.CONVENTION, EnumerableConvention.INSTANCE,
         relBuilderFactory, "ElasticsearchToEnumerableConverterRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
index 60408c6..889c8c5 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumUtils.java
@@ -31,10 +31,9 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
@@ -49,13 +48,6 @@ import java.util.List;
  */
 public class EnumUtils {
 
-  private static final Function<RexNode, Type> REX_TO_INTERNAL_TYPE =
-      new Function<RexNode, Type>() {
-        public Type apply(RexNode node) {
-          return toInternal(node.getType());
-        }
-      };
-
   private EnumUtils() {}
 
   static final boolean BRIDGE_METHODS = true;
@@ -233,7 +225,7 @@ public class EnumUtils {
   }
 
   static List<Type> internalTypes(List<? extends RexNode> operandList) {
-    return Lists.transform(operandList, REX_TO_INTERNAL_TYPE);
+    return Util.transform(operandList, node -> toInternal(node.getType()));
   }
 
   static Expression enforce(final Type storageType,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableAggregate.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableAggregate.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableAggregate.java
index 4d6fb05..56f3d95 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableAggregate.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableAggregate.java
@@ -48,7 +48,6 @@ import org.apache.calcite.util.Util;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.lang.reflect.Type;
 import java.util.ArrayList;
@@ -368,7 +367,7 @@ public class EnumerableAggregate extends Aggregate implements EnumerableRel {
     }
     resultBlock.add(physType.record(results));
     if (getGroupType() != Group.SIMPLE) {
-      final List<Expression> list = Lists.newArrayList();
+      final List<Expression> list = new ArrayList<>();
       for (ImmutableBitSet set : groupSets) {
         list.add(
             inputPhysType.generateSelector(parameter, groupSet.asList(),

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableBindable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableBindable.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableBindable.java
index 820be91..62a3b7f 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableBindable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableBindable.java
@@ -35,10 +35,10 @@ import org.apache.calcite.runtime.ArrayBindable;
 import org.apache.calcite.runtime.Bindable;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableMap;
 
 import java.util.List;
+import java.util.function.Predicate;
 
 /**
  * Relational expression that converts an enumerable input to interpretable
@@ -71,15 +71,13 @@ public class EnumerableBindable extends ConverterImpl implements BindableRel {
   }
 
   public Node implement(final InterpreterImplementor implementor) {
-    return new Node() {
-      public void run() throws InterruptedException {
-        final Sink sink =
-            implementor.relSinks.get(EnumerableBindable.this).get(0);
-        final Enumerable<Object[]> enumerable = bind(implementor.dataContext);
-        final Enumerator<Object[]> enumerator = enumerable.enumerator();
-        while (enumerator.moveNext()) {
-          sink.send(Row.asCopy(enumerator.current()));
-        }
+    return () -> {
+      final Sink sink =
+          implementor.relSinks.get(EnumerableBindable.this).get(0);
+      final Enumerable<Object[]> enumerable = bind(implementor.dataContext);
+      final Enumerator<Object[]> enumerator = enumerable.enumerator();
+      while (enumerator.moveNext()) {
+        sink.send(Row.asCopy(enumerator.current()));
       }
     };
   }
@@ -98,7 +96,7 @@ public class EnumerableBindable extends ConverterImpl implements BindableRel {
      */
     public EnumerableToBindableConverterRule(
         RelBuilderFactory relBuilderFactory) {
-      super(EnumerableRel.class, Predicates.<RelNode>alwaysTrue(),
+      super(EnumerableRel.class, (Predicate<RelNode>) r -> true,
           EnumerableConvention.INSTANCE, BindableConvention.INSTANCE,
           relBuilderFactory, "EnumerableToBindableConverterRule");
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalc.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalc.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalc.java
index 9e2018b..4b043c5 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalc.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalc.java
@@ -32,7 +32,6 @@ import org.apache.calcite.plan.RelOptPredicateList;
 import org.apache.calcite.plan.RelTraitSet;
 import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
-import org.apache.calcite.rel.RelDistribution;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Calc;
@@ -47,7 +46,6 @@ import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.lang.reflect.Modifier;
@@ -95,17 +93,9 @@ public class EnumerableCalc extends Calc implements EnumerableRel {
     final RelTraitSet traitSet = cluster.traitSet()
         .replace(EnumerableConvention.INSTANCE)
         .replaceIfs(RelCollationTraitDef.INSTANCE,
-            new Supplier<List<RelCollation>>() {
-              public List<RelCollation> get() {
-                return RelMdCollation.calc(mq, input, program);
-              }
-            })
+            () -> RelMdCollation.calc(mq, input, program))
         .replaceIf(RelDistributionTraitDef.INSTANCE,
-            new Supplier<RelDistribution>() {
-              public RelDistribution get() {
-                return RelMdDistribution.calc(mq, input, program);
-              }
-            });
+            () -> RelMdDistribution.calc(mq, input, program));
     return new EnumerableCalc(cluster, traitSet, input, program);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalcRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalcRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalcRule.java
index c85985b..35db0c9 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalcRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCalcRule.java
@@ -20,9 +20,12 @@ import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.convert.ConverterRule;
+import org.apache.calcite.rel.core.Calc;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.logical.LogicalCalc;
 
+import java.util.function.Predicate;
+
 /**
  * Rule to convert a {@link org.apache.calcite.rel.logical.LogicalCalc} to an
  * {@link EnumerableCalc}.
@@ -31,9 +34,10 @@ class EnumerableCalcRule extends ConverterRule {
   EnumerableCalcRule() {
     // The predicate ensures that if there's a multiset, FarragoMultisetSplitter
     // will work on it first.
-    super(LogicalCalc.class, RelOptUtil.CALC_PREDICATE, Convention.NONE,
-        EnumerableConvention.INSTANCE, RelFactories.LOGICAL_BUILDER,
-        "EnumerableCalcRule");
+    super(LogicalCalc.class,
+        (Predicate<Calc>) RelOptUtil::containsMultisetOrWindowedAgg,
+        Convention.NONE, EnumerableConvention.INSTANCE,
+        RelFactories.LOGICAL_BUILDER, "EnumerableCalcRule");
   }
 
   public RelNode convert(RelNode rel) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCorrelateRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCorrelateRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCorrelateRule.java
index 9c7bc71..2b543a2 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCorrelateRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableCorrelateRule.java
@@ -23,7 +23,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.logical.LogicalCorrelate;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Implementation of nested loops over enumerable inputs.
@@ -35,7 +35,7 @@ public class EnumerableCorrelateRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableCorrelateRule(RelBuilderFactory relBuilderFactory) {
-    super(LogicalCorrelate.class, Predicates.<RelNode>alwaysTrue(),
+    super(LogicalCorrelate.class, (Predicate<RelNode>) r -> true,
         Convention.NONE, EnumerableConvention.INSTANCE, relBuilderFactory,
         "EnumerableCorrelateRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilter.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilter.java
index da1cefa..514c8ad 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilter.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilter.java
@@ -18,9 +18,7 @@ package org.apache.calcite.adapter.enumerable;
 
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
-import org.apache.calcite.rel.RelDistribution;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Filter;
@@ -29,10 +27,6 @@ import org.apache.calcite.rel.metadata.RelMdDistribution;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexNode;
 
-import com.google.common.base.Supplier;
-
-import java.util.List;
-
 /** Implementation of {@link org.apache.calcite.rel.core.Filter} in
  * {@link org.apache.calcite.adapter.enumerable.EnumerableConvention enumerable calling convention}. */
 public class EnumerableFilter
@@ -59,17 +53,9 @@ public class EnumerableFilter
         cluster.traitSetOf(EnumerableConvention.INSTANCE)
             .replaceIfs(
                 RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    return RelMdCollation.filter(mq, input);
-                  }
-                })
+                () -> RelMdCollation.filter(mq, input))
             .replaceIf(RelDistributionTraitDef.INSTANCE,
-                new Supplier<RelDistribution>() {
-                  public RelDistribution get() {
-                    return RelMdDistribution.filter(mq, input);
-                  }
-                });
+                () -> RelMdDistribution.filter(mq, input));
     return new EnumerableFilter(cluster, traitSet, input, condition);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilterRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilterRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilterRule.java
index 65b80f1..e10daa6 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilterRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilterRule.java
@@ -23,15 +23,18 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.logical.LogicalFilter;
 
+import java.util.function.Predicate;
+
 /**
  * Rule to convert a {@link org.apache.calcite.rel.logical.LogicalFilter} to an
  * {@link EnumerableFilter}.
  */
 class EnumerableFilterRule extends ConverterRule {
   EnumerableFilterRule() {
-    super(LogicalFilter.class, RelOptUtil.FILTER_PREDICATE, Convention.NONE,
-        EnumerableConvention.INSTANCE, RelFactories.LOGICAL_BUILDER,
-        "EnumerableFilterRule");
+    super(LogicalFilter.class,
+        (Predicate<LogicalFilter>) RelOptUtil::containsMultisetOrWindowedAgg,
+        Convention.NONE, EnumerableConvention.INSTANCE,
+        RelFactories.LOGICAL_BUILDER, "EnumerableFilterRule");
   }
 
   public RelNode convert(RelNode rel) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableInterpreterRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableInterpreterRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableInterpreterRule.java
index 5462004..ca1ae06 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableInterpreterRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableInterpreterRule.java
@@ -22,7 +22,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Planner rule that converts {@link org.apache.calcite.interpreter.BindableRel}
@@ -39,7 +39,7 @@ public class EnumerableInterpreterRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableInterpreterRule(RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(),
+    super(RelNode.class, (Predicate<RelNode>) r -> true,
         BindableConvention.INSTANCE, EnumerableConvention.INSTANCE,
         relBuilderFactory, "EnumerableInterpreterRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableLimit.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableLimit.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableLimit.java
index 577a5a4..825aa7d 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableLimit.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableLimit.java
@@ -22,9 +22,7 @@ import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
-import org.apache.calcite.rel.RelDistribution;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.RelWriter;
@@ -37,8 +35,6 @@ import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.util.BuiltInMethod;
 
-import com.google.common.base.Supplier;
-
 import java.util.List;
 
 /** Relational expression that applies a limit and/or offset to its input. */
@@ -71,17 +67,9 @@ public class EnumerableLimit extends SingleRel implements EnumerableRel {
         cluster.traitSetOf(EnumerableConvention.INSTANCE)
             .replaceIfs(
                 RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    return RelMdCollation.limit(mq, input);
-                  }
-                })
+                () -> RelMdCollation.limit(mq, input))
             .replaceIf(RelDistributionTraitDef.INSTANCE,
-                new Supplier<RelDistribution>() {
-                  public RelDistribution get() {
-                    return RelMdDistribution.limit(mq, input);
-                  }
-                });
+                () -> RelMdDistribution.limit(mq, input));
     return new EnumerableLimit(cluster, traitSet, input, offset, fetch);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoin.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoin.java
index 975665d..7851484 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoin.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoin.java
@@ -96,7 +96,7 @@ public class EnumerableMergeJoin extends EquiJoin implements EnumerableRel {
       traitSet = traitSet.replace(collations);
     }
     return new EnumerableMergeJoin(cluster, traitSet, left, right, condition,
-        leftKeys, rightKeys, ImmutableSet.<CorrelationId>of(), joinType);
+        leftKeys, rightKeys, ImmutableSet.of(), joinType);
   }
 
   @Override public EnumerableMergeJoin copy(RelTraitSet traitSet,


[11/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/jdbc/CalciteRemoteDriverTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/jdbc/CalciteRemoteDriverTest.java b/core/src/test/java/org/apache/calcite/jdbc/CalciteRemoteDriverTest.java
index 801caa9..862b26e 100644
--- a/core/src/test/java/org/apache/calcite/jdbc/CalciteRemoteDriverTest.java
+++ b/core/src/test/java/org/apache/calcite/jdbc/CalciteRemoteDriverTest.java
@@ -25,20 +25,15 @@ import org.apache.calcite.avatica.remote.Service;
 import org.apache.calcite.avatica.server.AvaticaJsonHandler;
 import org.apache.calcite.avatica.server.HttpServer;
 import org.apache.calcite.avatica.server.Main;
-import org.apache.calcite.avatica.server.Main.HandlerFactory;
 import org.apache.calcite.prepare.CalcitePrepareImpl;
 import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.test.JdbcFrontLinqBackTest;
 import org.apache.calcite.test.JdbcTest;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
 import org.hamcrest.CoreMatchers;
-
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -71,9 +66,11 @@ import java.text.ParseException;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
@@ -100,53 +97,47 @@ public class CalciteRemoteDriverTest {
       };
 
   private static final Function<Connection, ResultSet> GET_SCHEMAS =
-      new Function<Connection, ResultSet>() {
-        public ResultSet apply(Connection input) {
-          try {
-            return input.getMetaData().getSchemas();
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
+      connection -> {
+        try {
+          return connection.getMetaData().getSchemas();
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
         }
       };
+
   private static final Function<Connection, ResultSet> GET_CATALOGS =
-      new Function<Connection, ResultSet>() {
-        public ResultSet apply(Connection input) {
-          try {
-            return input.getMetaData().getCatalogs();
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
+      connection -> {
+        try {
+          return connection.getMetaData().getCatalogs();
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
         }
       };
+
   private static final Function<Connection, ResultSet> GET_COLUMNS =
-      new Function<Connection, ResultSet>() {
-        public ResultSet apply(Connection input) {
-          try {
-            return input.getMetaData().getColumns(null, null, null, null);
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
+      connection -> {
+        try {
+          return connection.getMetaData().getColumns(null, null, null, null);
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
         }
       };
+
   private static final Function<Connection, ResultSet> GET_TYPEINFO =
-      new Function<Connection, ResultSet>() {
-        public ResultSet apply(Connection input) {
-          try {
-            return input.getMetaData().getTypeInfo();
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
+      connection -> {
+        try {
+          return connection.getMetaData().getTypeInfo();
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
         }
       };
+
   private static final Function<Connection, ResultSet> GET_TABLE_TYPES =
-      new Function<Connection, ResultSet>() {
-        public ResultSet apply(Connection input) {
-          try {
-            return input.getMetaData().getTableTypes();
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
+      connection -> {
+        try {
+          return connection.getMetaData().getTableTypes();
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
         }
       };
 
@@ -157,11 +148,8 @@ public class CalciteRemoteDriverTest {
     localConnection = CalciteAssert.hr().connect();
 
     // Make sure we pick an ephemeral port for the server
-    start = Main.start(new String[]{Factory.class.getName()}, 0, new HandlerFactory() {
-      public AvaticaJsonHandler createHandler(Service service) {
-        return new AvaticaJsonHandler(service);
-      }
-    });
+    start = Main.start(new String[]{Factory.class.getName()}, 0,
+        AvaticaJsonHandler::new);
   }
 
   protected static Connection getRemoteConnection() throws SQLException {
@@ -311,7 +299,7 @@ public class CalciteRemoteDriverTest {
    * variables. */
   @Test public void testParameterConvert() throws Exception {
     final StringBuilder sql = new StringBuilder("select 1");
-    final Map<SqlType, Integer> map = Maps.newHashMap();
+    final Map<SqlType, Integer> map = new HashMap<>();
     for (Map.Entry<Class, SqlType> entry : SqlType.getSetConversions()) {
       final SqlType sqlType = entry.getValue();
       switch (sqlType) {
@@ -629,7 +617,7 @@ public class CalciteRemoteDriverTest {
 
   /** A bunch of sample values of various types. */
   private static final List<Object> SAMPLE_VALUES =
-      ImmutableList.<Object>of(false, true,
+      ImmutableList.of(false, true,
           // byte
           (byte) 0, (byte) 1, Byte.MIN_VALUE, Byte.MAX_VALUE,
           // short
@@ -664,7 +652,7 @@ public class CalciteRemoteDriverTest {
           new byte[0], "hello".getBytes(StandardCharsets.UTF_8));
 
   private static List<Object> values(Class clazz) {
-    final List<Object> list = Lists.newArrayList();
+    final List<Object> list = new ArrayList<>();
     for (Object sampleValue : SAMPLE_VALUES) {
       if (sampleValue.getClass() == clazz) {
         list.add(sampleValue);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/plan/RelOptUtilTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/plan/RelOptUtilTest.java b/core/src/test/java/org/apache/calcite/plan/RelOptUtilTest.java
index 03bd725..2d2d67b 100644
--- a/core/src/test/java/org/apache/calcite/plan/RelOptUtilTest.java
+++ b/core/src/test/java/org/apache/calcite/plan/RelOptUtilTest.java
@@ -39,6 +39,7 @@ import com.google.common.collect.Lists;
 
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
@@ -189,9 +190,9 @@ public class RelOptUtilTest {
 
   private static void splitJoinConditionHelper(RexNode joinCond, List<Integer> expLeftKeys,
       List<Integer> expRightKeys, List<Boolean> expFilterNulls, RexNode expRemaining) {
-    List<Integer> actLeftKeys = Lists.newArrayList();
-    List<Integer> actRightKeys = Lists.newArrayList();
-    List<Boolean> actFilterNulls = Lists.newArrayList();
+    List<Integer> actLeftKeys = new ArrayList<>();
+    List<Integer> actRightKeys = new ArrayList<>();
+    List<Boolean> actFilterNulls = new ArrayList<>();
 
     RexNode actRemaining = RelOptUtil.splitJoinCondition(EMP_SCAN, DEPT_SCAN, joinCond, actLeftKeys,
         actRightKeys, actFilterNulls);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java b/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java
index 2ceea23..c411888 100644
--- a/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java
+++ b/core/src/test/java/org/apache/calcite/plan/RelWriterTest.java
@@ -116,41 +116,37 @@ public class RelWriterTest {
    */
   @Test public void testWriter() {
     String s =
-        Frameworks.withPlanner(
-            new Frameworks.PlannerAction<String>() {
-              public String apply(RelOptCluster cluster,
-                  RelOptSchema relOptSchema, SchemaPlus rootSchema) {
-                rootSchema.add("hr",
-                    new ReflectiveSchema(new JdbcTest.HrSchema()));
-                LogicalTableScan scan =
-                    LogicalTableScan.create(cluster,
-                        relOptSchema.getTableForMember(
-                            Arrays.asList("hr", "emps")));
-                final RexBuilder rexBuilder = cluster.getRexBuilder();
-                LogicalFilter filter =
-                    LogicalFilter.create(scan,
-                        rexBuilder.makeCall(
-                            SqlStdOperatorTable.EQUALS,
-                            rexBuilder.makeFieldAccess(
-                                rexBuilder.makeRangeReference(scan),
-                                "deptno", true),
-                            rexBuilder.makeExactLiteral(BigDecimal.TEN)));
-                final RelJsonWriter writer = new RelJsonWriter();
-                final RelDataType bigIntType =
-                    cluster.getTypeFactory().createSqlType(SqlTypeName.BIGINT);
-                LogicalAggregate aggregate =
-                    LogicalAggregate.create(filter, ImmutableBitSet.of(0), null,
-                        ImmutableList.of(
-                            AggregateCall.create(SqlStdOperatorTable.COUNT,
-                                true, false, ImmutableList.of(1), -1,
-                                bigIntType, "c"),
-                            AggregateCall.create(SqlStdOperatorTable.COUNT,
-                                false, false, ImmutableList.<Integer>of(), -1,
-                                bigIntType, "d")));
-                aggregate.explain(writer);
-                return writer.asString();
-              }
-            });
+        Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+          rootSchema.add("hr",
+              new ReflectiveSchema(new JdbcTest.HrSchema()));
+          LogicalTableScan scan =
+              LogicalTableScan.create(cluster,
+                  relOptSchema.getTableForMember(
+                      Arrays.asList("hr", "emps")));
+          final RexBuilder rexBuilder = cluster.getRexBuilder();
+          LogicalFilter filter =
+              LogicalFilter.create(scan,
+                  rexBuilder.makeCall(
+                      SqlStdOperatorTable.EQUALS,
+                      rexBuilder.makeFieldAccess(
+                          rexBuilder.makeRangeReference(scan),
+                          "deptno", true),
+                      rexBuilder.makeExactLiteral(BigDecimal.TEN)));
+          final RelJsonWriter writer = new RelJsonWriter();
+          final RelDataType bigIntType =
+              cluster.getTypeFactory().createSqlType(SqlTypeName.BIGINT);
+          LogicalAggregate aggregate =
+              LogicalAggregate.create(filter, ImmutableBitSet.of(0), null,
+                  ImmutableList.of(
+                      AggregateCall.create(SqlStdOperatorTable.COUNT,
+                          true, false, ImmutableList.of(1), -1,
+                          bigIntType, "c"),
+                      AggregateCall.create(SqlStdOperatorTable.COUNT,
+                          false, false, ImmutableList.of(), -1,
+                          bigIntType, "d")));
+          aggregate.explain(writer);
+          return writer.asString();
+        });
     assertThat(s, is(XX));
   }
 
@@ -159,25 +155,21 @@ public class RelWriterTest {
    */
   @Test public void testReader() {
     String s =
-        Frameworks.withPlanner(
-            new Frameworks.PlannerAction<String>() {
-              public String apply(RelOptCluster cluster,
-                  RelOptSchema relOptSchema, SchemaPlus rootSchema) {
-                SchemaPlus schema =
-                    rootSchema.add("hr",
-                        new ReflectiveSchema(new JdbcTest.HrSchema()));
-                final RelJsonReader reader =
-                    new RelJsonReader(cluster, relOptSchema, schema);
-                RelNode node;
-                try {
-                  node = reader.read(XX);
-                } catch (IOException e) {
-                  throw new RuntimeException(e);
-                }
-                return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
-                    SqlExplainLevel.EXPPLAN_ATTRIBUTES);
-              }
-            });
+        Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+          SchemaPlus schema =
+              rootSchema.add("hr",
+                  new ReflectiveSchema(new JdbcTest.HrSchema()));
+          final RelJsonReader reader =
+              new RelJsonReader(cluster, relOptSchema, schema);
+          RelNode node;
+          try {
+            node = reader.read(XX);
+          } catch (IOException e) {
+            throw new RuntimeException(e);
+          }
+          return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
+              SqlExplainLevel.EXPPLAN_ATTRIBUTES);
+        });
 
     assertThat(s,
         isLinux("LogicalAggregate(group=[{0}], agg#0=[COUNT(DISTINCT $1)], agg#1=[COUNT()])\n"

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/plan/volcano/ComboRuleTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/plan/volcano/ComboRuleTest.java b/core/src/test/java/org/apache/calcite/plan/volcano/ComboRuleTest.java
index 3cd8195..e8dc2c9 100644
--- a/core/src/test/java/org/apache/calcite/plan/volcano/ComboRuleTest.java
+++ b/core/src/test/java/org/apache/calcite/plan/volcano/ComboRuleTest.java
@@ -45,7 +45,6 @@ import static org.apache.calcite.plan.volcano.PlannerTests.newCluster;
 
 import static org.junit.Assert.assertTrue;
 
-
 /**
  * Unit test for {@link VolcanoPlanner}
  */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/plan/volcano/TraitConversionTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/plan/volcano/TraitConversionTest.java b/core/src/test/java/org/apache/calcite/plan/volcano/TraitConversionTest.java
index b3ae329..2396f53 100644
--- a/core/src/test/java/org/apache/calcite/plan/volcano/TraitConversionTest.java
+++ b/core/src/test/java/org/apache/calcite/plan/volcano/TraitConversionTest.java
@@ -41,7 +41,6 @@ import static org.apache.calcite.plan.volcano.PlannerTests.newCluster;
 
 import static org.junit.Assert.assertTrue;
 
-
 /**
  * Unit test for {@link org.apache.calcite.rel.RelDistributionTraitDef}.
  */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/plan/volcano/TraitPropagationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/plan/volcano/TraitPropagationTest.java b/core/src/test/java/org/apache/calcite/plan/volcano/TraitPropagationTest.java
index 8847f93..2822c1c 100644
--- a/core/src/test/java/org/apache/calcite/plan/volcano/TraitPropagationTest.java
+++ b/core/src/test/java/org/apache/calcite/plan/volcano/TraitPropagationTest.java
@@ -71,7 +71,6 @@ import org.apache.calcite.tools.RuleSet;
 import org.apache.calcite.tools.RuleSets;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import org.junit.Test;
@@ -140,7 +139,7 @@ public class TraitPropagationTest {
         }
 
         @Override public Statistic getStatistic() {
-          return Statistics.of(100d, ImmutableList.<ImmutableBitSet>of(),
+          return Statistics.of(100d, ImmutableList.of(),
               ImmutableList.of(COLLATION));
         }
       };
@@ -329,11 +328,7 @@ public class TraitPropagationTest {
           cluster.traitSet().replace(PHYSICAL)
               .replaceIfs(
                   RelCollationTraitDef.INSTANCE,
-                  new Supplier<List<RelCollation>>() {
-                    public List<RelCollation> get() {
-                      return RelMdCollation.project(mq, input, projects);
-                    }
-                  });
+                  () -> RelMdCollation.project(mq, input, projects));
       return new PhysProj(cluster, traitSet, input, projects, rowType);
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/prepare/LookupOperatorOverloadsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/prepare/LookupOperatorOverloadsTest.java b/core/src/test/java/org/apache/calcite/prepare/LookupOperatorOverloadsTest.java
index f36372b..69a4c1d 100644
--- a/core/src/test/java/org/apache/calcite/prepare/LookupOperatorOverloadsTest.java
+++ b/core/src/test/java/org/apache/calcite/prepare/LookupOperatorOverloadsTest.java
@@ -144,7 +144,7 @@ public class LookupOperatorOverloadsTest {
       final JavaTypeFactory typeFactory = prepareContext.getTypeFactory();
       CalciteCatalogReader reader =
           new CalciteCatalogReader(prepareContext.getRootSchema(),
-              ImmutableList.<String>of(), typeFactory, prepareContext.config());
+              ImmutableList.of(), typeFactory, prepareContext.config());
 
       final List<SqlOperator> operatorList = new ArrayList<>();
       SqlIdentifier myFuncIdentifier =

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/profile/ProfilerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/profile/ProfilerTest.java b/core/src/test/java/org/apache/calcite/profile/ProfilerTest.java
index 9e8de90..c31187a 100644
--- a/core/src/test/java/org/apache/calcite/profile/ProfilerTest.java
+++ b/core/src/test/java/org/apache/calcite/profile/ProfilerTest.java
@@ -16,27 +16,18 @@
  */
 package org.apache.calcite.profile;
 
-import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.linq4j.AbstractEnumerable;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Enumerator;
 import org.apache.calcite.rel.metadata.NullSentinel;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.test.Matchers;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.JsonBuilder;
-import org.apache.calcite.util.Pair;
+import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.base.Supplier;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Ordering;
 
@@ -53,8 +44,12 @@ import java.util.Collection;
 import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.SortedSet;
 import java.util.TreeSet;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
 
 import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertThat;
@@ -114,84 +109,82 @@ public class ProfilerTest {
     final String sql = "select * from \"scott\".emp\n"
         + "join \"scott\".dept on emp.deptno = dept.deptno";
     sql(sql)
-        .where(new PredicateImpl<Profiler.Statistic>() {
-          public boolean test(Profiler.Statistic statistic) {
-            return !(statistic instanceof Profiler.Distribution)
+        .where(statistic ->
+            !(statistic instanceof Profiler.Distribution)
                 || ((Profiler.Distribution) statistic).cardinality < 14
-                && ((Profiler.Distribution) statistic).minimal;
-          }
-        }).unordered(
-        "{type:distribution,columns:[COMM,DEPTNO0],cardinality:5.0}",
-        "{type:distribution,columns:[COMM,DEPTNO],cardinality:5.0}",
-        "{type:distribution,columns:[COMM,DNAME],cardinality:5.0}",
-        "{type:distribution,columns:[COMM,LOC],cardinality:5.0}",
-        "{type:distribution,columns:[COMM],values:[0.00,300.00,500.00,1400.00],cardinality:5.0,nullCount:10}",
-        "{type:distribution,columns:[DEPTNO,DEPTNO0],cardinality:3.0}",
-        "{type:distribution,columns:[DEPTNO,DNAME],cardinality:3.0}",
-        "{type:distribution,columns:[DEPTNO,LOC],cardinality:3.0}",
-        "{type:distribution,columns:[DEPTNO0,DNAME],cardinality:3.0}",
-        "{type:distribution,columns:[DEPTNO0,LOC],cardinality:3.0}",
-        "{type:distribution,columns:[DEPTNO0],values:[10,20,30],cardinality:3.0}",
-        "{type:distribution,columns:[DEPTNO],values:[10,20,30],cardinality:3.0}",
-        "{type:distribution,columns:[DNAME,LOC],cardinality:3.0}",
-        "{type:distribution,columns:[DNAME],values:[ACCOUNTING,RESEARCH,SALES],cardinality:3.0}",
-        "{type:distribution,columns:[HIREDATE,COMM],cardinality:5.0}",
-        "{type:distribution,columns:[HIREDATE],values:[1980-12-17,1981-01-05,1981-02-04,1981-02-20,1981-02-22,1981-06-09,1981-09-08,1981-09-28,1981-11-17,1981-12-03,1982-01-23,1987-04-19,1987-05-23],cardinality:13.0}",
-        "{type:distribution,columns:[JOB,COMM],cardinality:5.0}",
-        "{type:distribution,columns:[JOB,DEPTNO0],cardinality:9.0}",
-        "{type:distribution,columns:[JOB,DEPTNO],cardinality:9.0}",
-        "{type:distribution,columns:[JOB,DNAME],cardinality:9.0}",
-        "{type:distribution,columns:[JOB,LOC],cardinality:9.0}",
-        "{type:distribution,columns:[JOB,MGR,DEPTNO0],cardinality:10.0}",
-        "{type:distribution,columns:[JOB,MGR,DEPTNO],cardinality:10.0}",
-        "{type:distribution,columns:[JOB,MGR,DNAME],cardinality:10.0}",
-        "{type:distribution,columns:[JOB,MGR,LOC],cardinality:10.0}",
-        "{type:distribution,columns:[JOB,MGR],cardinality:8.0}",
-        "{type:distribution,columns:[JOB,SAL],cardinality:12.0}",
-        "{type:distribution,columns:[JOB],values:[ANALYST,CLERK,MANAGER,PRESIDENT,SALESMAN],cardinality:5.0}",
-        "{type:distribution,columns:[LOC],values:[CHICAGO,DALLAS,NEWYORK],cardinality:3.0}",
-        "{type:distribution,columns:[MGR,COMM],cardinality:5.0}",
-        "{type:distribution,columns:[MGR,DEPTNO0],cardinality:9.0}",
-        "{type:distribution,columns:[MGR,DEPTNO],cardinality:9.0}",
-        "{type:distribution,columns:[MGR,DNAME],cardinality:9.0}",
-        "{type:distribution,columns:[MGR,LOC],cardinality:9.0}",
-        "{type:distribution,columns:[MGR,SAL],cardinality:12.0}",
-        "{type:distribution,columns:[MGR],values:[7566,7698,7782,7788,7839,7902],cardinality:7.0,nullCount:1}",
-        "{type:distribution,columns:[SAL,COMM],cardinality:5.0}",
-        "{type:distribution,columns:[SAL,DEPTNO0],cardinality:12.0}",
-        "{type:distribution,columns:[SAL,DEPTNO],cardinality:12.0}",
-        "{type:distribution,columns:[SAL,DNAME],cardinality:12.0}",
-        "{type:distribution,columns:[SAL,LOC],cardinality:12.0}",
-        "{type:distribution,columns:[SAL],values:[800.00,950.00,1100.00,1250.00,1300.00,1500.00,1600.00,2450.00,2850.00,2975.00,3000.00,5000.00],cardinality:12.0}",
-        "{type:distribution,columns:[],cardinality:1.0}",
-        "{type:fd,columns:[DEPTNO0],dependentColumn:DEPTNO}",
-        "{type:fd,columns:[DEPTNO0],dependentColumn:DNAME}",
-        "{type:fd,columns:[DEPTNO0],dependentColumn:LOC}",
-        "{type:fd,columns:[DEPTNO],dependentColumn:DEPTNO0}",
-        "{type:fd,columns:[DEPTNO],dependentColumn:DNAME}",
-        "{type:fd,columns:[DEPTNO],dependentColumn:LOC}",
-        "{type:fd,columns:[DNAME],dependentColumn:DEPTNO0}",
-        "{type:fd,columns:[DNAME],dependentColumn:DEPTNO}",
-        "{type:fd,columns:[DNAME],dependentColumn:LOC}",
-        "{type:fd,columns:[JOB],dependentColumn:COMM}",
-        "{type:fd,columns:[LOC],dependentColumn:DEPTNO0}",
-        "{type:fd,columns:[LOC],dependentColumn:DEPTNO}",
-        "{type:fd,columns:[LOC],dependentColumn:DNAME}",
-        "{type:fd,columns:[SAL],dependentColumn:DEPTNO0}",
-        "{type:fd,columns:[SAL],dependentColumn:DEPTNO}",
-        "{type:fd,columns:[SAL],dependentColumn:DNAME}",
-        "{type:fd,columns:[SAL],dependentColumn:JOB}",
-        "{type:fd,columns:[SAL],dependentColumn:LOC}",
-        "{type:fd,columns:[SAL],dependentColumn:MGR}",
-        "{type:rowCount,rowCount:14}",
-        "{type:unique,columns:[EMPNO]}",
-        "{type:unique,columns:[ENAME]}",
-        "{type:unique,columns:[HIREDATE,DEPTNO0]}",
-        "{type:unique,columns:[HIREDATE,DEPTNO]}",
-        "{type:unique,columns:[HIREDATE,DNAME]}",
-        "{type:unique,columns:[HIREDATE,LOC]}",
-        "{type:unique,columns:[HIREDATE,SAL]}",
-        "{type:unique,columns:[JOB,HIREDATE]}");
+                && ((Profiler.Distribution) statistic).minimal)
+        .unordered(
+            "{type:distribution,columns:[COMM,DEPTNO0],cardinality:5.0}",
+            "{type:distribution,columns:[COMM,DEPTNO],cardinality:5.0}",
+            "{type:distribution,columns:[COMM,DNAME],cardinality:5.0}",
+            "{type:distribution,columns:[COMM,LOC],cardinality:5.0}",
+            "{type:distribution,columns:[COMM],values:[0.00,300.00,500.00,1400.00],cardinality:5.0,nullCount:10}",
+            "{type:distribution,columns:[DEPTNO,DEPTNO0],cardinality:3.0}",
+            "{type:distribution,columns:[DEPTNO,DNAME],cardinality:3.0}",
+            "{type:distribution,columns:[DEPTNO,LOC],cardinality:3.0}",
+            "{type:distribution,columns:[DEPTNO0,DNAME],cardinality:3.0}",
+            "{type:distribution,columns:[DEPTNO0,LOC],cardinality:3.0}",
+            "{type:distribution,columns:[DEPTNO0],values:[10,20,30],cardinality:3.0}",
+            "{type:distribution,columns:[DEPTNO],values:[10,20,30],cardinality:3.0}",
+            "{type:distribution,columns:[DNAME,LOC],cardinality:3.0}",
+            "{type:distribution,columns:[DNAME],values:[ACCOUNTING,RESEARCH,SALES],cardinality:3.0}",
+            "{type:distribution,columns:[HIREDATE,COMM],cardinality:5.0}",
+            "{type:distribution,columns:[HIREDATE],values:[1980-12-17,1981-01-05,1981-02-04,1981-02-20,1981-02-22,1981-06-09,1981-09-08,1981-09-28,1981-11-17,1981-12-03,1982-01-23,1987-04-19,1987-05-23],cardinality:13.0}",
+            "{type:distribution,columns:[JOB,COMM],cardinality:5.0}",
+            "{type:distribution,columns:[JOB,DEPTNO0],cardinality:9.0}",
+            "{type:distribution,columns:[JOB,DEPTNO],cardinality:9.0}",
+            "{type:distribution,columns:[JOB,DNAME],cardinality:9.0}",
+            "{type:distribution,columns:[JOB,LOC],cardinality:9.0}",
+            "{type:distribution,columns:[JOB,MGR,DEPTNO0],cardinality:10.0}",
+            "{type:distribution,columns:[JOB,MGR,DEPTNO],cardinality:10.0}",
+            "{type:distribution,columns:[JOB,MGR,DNAME],cardinality:10.0}",
+            "{type:distribution,columns:[JOB,MGR,LOC],cardinality:10.0}",
+            "{type:distribution,columns:[JOB,MGR],cardinality:8.0}",
+            "{type:distribution,columns:[JOB,SAL],cardinality:12.0}",
+            "{type:distribution,columns:[JOB],values:[ANALYST,CLERK,MANAGER,PRESIDENT,SALESMAN],cardinality:5.0}",
+            "{type:distribution,columns:[LOC],values:[CHICAGO,DALLAS,NEWYORK],cardinality:3.0}",
+            "{type:distribution,columns:[MGR,COMM],cardinality:5.0}",
+            "{type:distribution,columns:[MGR,DEPTNO0],cardinality:9.0}",
+            "{type:distribution,columns:[MGR,DEPTNO],cardinality:9.0}",
+            "{type:distribution,columns:[MGR,DNAME],cardinality:9.0}",
+            "{type:distribution,columns:[MGR,LOC],cardinality:9.0}",
+            "{type:distribution,columns:[MGR,SAL],cardinality:12.0}",
+            "{type:distribution,columns:[MGR],values:[7566,7698,7782,7788,7839,7902],cardinality:7.0,nullCount:1}",
+            "{type:distribution,columns:[SAL,COMM],cardinality:5.0}",
+            "{type:distribution,columns:[SAL,DEPTNO0],cardinality:12.0}",
+            "{type:distribution,columns:[SAL,DEPTNO],cardinality:12.0}",
+            "{type:distribution,columns:[SAL,DNAME],cardinality:12.0}",
+            "{type:distribution,columns:[SAL,LOC],cardinality:12.0}",
+            "{type:distribution,columns:[SAL],values:[800.00,950.00,1100.00,1250.00,1300.00,1500.00,1600.00,2450.00,2850.00,2975.00,3000.00,5000.00],cardinality:12.0}",
+            "{type:distribution,columns:[],cardinality:1.0}",
+            "{type:fd,columns:[DEPTNO0],dependentColumn:DEPTNO}",
+            "{type:fd,columns:[DEPTNO0],dependentColumn:DNAME}",
+            "{type:fd,columns:[DEPTNO0],dependentColumn:LOC}",
+            "{type:fd,columns:[DEPTNO],dependentColumn:DEPTNO0}",
+            "{type:fd,columns:[DEPTNO],dependentColumn:DNAME}",
+            "{type:fd,columns:[DEPTNO],dependentColumn:LOC}",
+            "{type:fd,columns:[DNAME],dependentColumn:DEPTNO0}",
+            "{type:fd,columns:[DNAME],dependentColumn:DEPTNO}",
+            "{type:fd,columns:[DNAME],dependentColumn:LOC}",
+            "{type:fd,columns:[JOB],dependentColumn:COMM}",
+            "{type:fd,columns:[LOC],dependentColumn:DEPTNO0}",
+            "{type:fd,columns:[LOC],dependentColumn:DEPTNO}",
+            "{type:fd,columns:[LOC],dependentColumn:DNAME}",
+            "{type:fd,columns:[SAL],dependentColumn:DEPTNO0}",
+            "{type:fd,columns:[SAL],dependentColumn:DEPTNO}",
+            "{type:fd,columns:[SAL],dependentColumn:DNAME}",
+            "{type:fd,columns:[SAL],dependentColumn:JOB}",
+            "{type:fd,columns:[SAL],dependentColumn:LOC}",
+            "{type:fd,columns:[SAL],dependentColumn:MGR}",
+            "{type:rowCount,rowCount:14}",
+            "{type:unique,columns:[EMPNO]}",
+            "{type:unique,columns:[ENAME]}",
+            "{type:unique,columns:[HIREDATE,DEPTNO0]}",
+            "{type:unique,columns:[HIREDATE,DEPTNO]}",
+            "{type:unique,columns:[HIREDATE,DNAME]}",
+            "{type:unique,columns:[HIREDATE,LOC]}",
+            "{type:unique,columns:[HIREDATE,SAL]}",
+            "{type:unique,columns:[JOB,HIREDATE]}");
   }
 
   /** As {@link #testProfileScott()}, but prints only the most surprising
@@ -400,27 +393,15 @@ public class ProfilerTest {
 
   private static Fluid sql(String sql) {
     return new Fluid(CalciteAssert.Config.SCOTT, sql, Fluid.SIMPLE_FACTORY,
-        Predicates.<Profiler.Statistic>alwaysTrue(), null, -1,
-        Fluid.DEFAULT_COLUMNS);
+        s -> true, null, -1, Fluid.DEFAULT_COLUMNS);
   }
 
   /** Fluid interface for writing profiler test cases. */
   private static class Fluid {
-    static final Supplier<Profiler> SIMPLE_FACTORY =
-        new Supplier<Profiler>() {
-          public Profiler get() {
-            return new SimpleProfiler();
-          }
-        };
+    static final Supplier<Profiler> SIMPLE_FACTORY = SimpleProfiler::new;
 
     static final Supplier<Profiler> BETTER_FACTORY =
-        new Supplier<Profiler>() {
-          public Profiler get() {
-            final Predicate<Pair<ProfilerImpl.Space, Profiler.Column>>
-                predicate = Predicates.alwaysTrue();
-            return new ProfilerImpl(600, 200, predicate);
-          }
-        };
+        () -> new ProfilerImpl(600, 200, p -> true);
 
     static final Ordering<Profiler.Statistic> ORDERING =
         new Ordering<Profiler.Statistic>() {
@@ -443,18 +424,10 @@ public class ProfilerTest {
         };
 
     static final Predicate<Profiler.Statistic> STATISTIC_PREDICATE =
-        new PredicateImpl<Profiler.Statistic>() {
-          public boolean test(Profiler.Statistic statistic) {
-            // Include distributions of zero columns (the grand total)
-            // and singleton columns, plus "surprising" distributions
-            // (with significantly higher NDVs than predicted from their
-            // constituent columns).
-            return statistic instanceof Profiler.Distribution
-                && (((Profiler.Distribution) statistic).columns.size() < 2
-                || ((Profiler.Distribution) statistic).surprise() > 0.4D)
-                && ((Profiler.Distribution) statistic).minimal;
-          }
-        };
+        statistic -> statistic instanceof Profiler.Distribution
+            && (((Profiler.Distribution) statistic).columns.size() < 2
+            || ((Profiler.Distribution) statistic).surprise() > 0.4D)
+            && ((Profiler.Distribution) statistic).minimal;
 
     static final List<String> DEFAULT_COLUMNS =
         ImmutableList.of("type", "distribution", "columns", "cardinality",
@@ -465,34 +438,20 @@ public class ProfilerTest {
             .add("expectedCardinality", "surprise")
             .build();
 
-    private static final Supplier<Profiler> PROFILER_FACTORY =
-        new Supplier<Profiler>() {
-          public Profiler get() {
-            return new ProfilerImpl(7500, 100,
-                new PredicateImpl<Pair<ProfilerImpl.Space, Profiler.Column>>() {
-                  public boolean test(
-                      Pair<ProfilerImpl.Space, Profiler.Column> p) {
-                    final Profiler.Distribution distribution =
-                        p.left.distribution();
-                    if (distribution == null) {
-                      // We don't have a distribution yet, because this space
-                      // has not yet been evaluated. Let's do it anyway.
-                      return true;
-                    }
-                    return distribution.surprise() >= 0.3D;
-                  }
-                });
+    private static final Supplier<Profiler> PROFILER_FACTORY = () ->
+        new ProfilerImpl(7500, 100, p -> {
+          final Profiler.Distribution distribution =
+              p.left.distribution();
+          if (distribution == null) {
+            // We don't have a distribution yet, because this space
+            // has not yet been evaluated. Let's do it anyway.
+            return true;
           }
-        };
+          return distribution.surprise() >= 0.3D;
+        });
 
     private static final Supplier<Profiler> INCURIOUS_PROFILER_FACTORY =
-        new Supplier<Profiler>() {
-          public Profiler get() {
-            final Predicate<Pair<ProfilerImpl.Space, Profiler.Column>> p =
-                Predicates.alwaysFalse();
-            return new ProfilerImpl(10, 200, p);
-          }
-        };
+        () -> new ProfilerImpl(10, 200, p -> false);
 
     private final String sql;
     private final List<String> columns;
@@ -506,10 +465,10 @@ public class ProfilerTest {
         Predicate<Profiler.Statistic> predicate,
         Comparator<Profiler.Statistic> comparator, int limit,
         List<String> columns) {
-      this.sql = Preconditions.checkNotNull(sql);
-      this.factory = Preconditions.checkNotNull(factory);
+      this.sql = Objects.requireNonNull(sql);
+      this.factory = Objects.requireNonNull(factory);
       this.columns = ImmutableList.copyOf(columns);
-      this.predicate = Preconditions.checkNotNull(predicate);
+      this.predicate = Objects.requireNonNull(predicate);
       this.comparator = comparator; // null means sort on JSON representation
       this.limit = limit;
       this.config = config;
@@ -552,80 +511,58 @@ public class ProfilerTest {
     public Fluid check(final Matcher<Iterable<String>> matcher)
         throws Exception {
       CalciteAssert.that(config)
-          .doWithConnection(new Function<CalciteConnection, Void>() {
-            public Void apply(CalciteConnection c) {
-              try (PreparedStatement s = c.prepareStatement(sql)) {
-                final ResultSetMetaData m = s.getMetaData();
-                final List<Profiler.Column> columns = new ArrayList<>();
-                final int columnCount = m.getColumnCount();
-                for (int i = 0; i < columnCount; i++) {
-                  columns.add(new Profiler.Column(i, m.getColumnLabel(i + 1)));
-                }
-
-                // Create an initial group for each table in the query.
-                // Columns in the same table will tend to have the same
-                // cardinality as the table, and as the table's primary key.
-                final Multimap<String, Integer> groups = HashMultimap.create();
-                for (int i = 0; i < m.getColumnCount(); i++) {
-                  groups.put(m.getTableName(i + 1), i);
-                }
-                final SortedSet<ImmutableBitSet> initialGroups =
-                    new TreeSet<>();
-                for (Collection<Integer> integers : groups.asMap().values()) {
-                  initialGroups.add(ImmutableBitSet.of(integers));
-                }
-                final Profiler p = factory.get();
-                final Enumerable<List<Comparable>> rows = getRows(s);
-                final Profiler.Profile profile =
-                    p.profile(rows, columns, initialGroups);
-                final List<Profiler.Statistic> statistics =
-                    ImmutableList.copyOf(
-                        Iterables.filter(profile.statistics(), predicate));
-
-                // If no comparator specified, use the function that converts to
-                // JSON strings
-                final Function<Profiler.Statistic, String> toJson =
-                    toJsonFunction();
-                Ordering<Profiler.Statistic> comp = comparator != null
-                    ? Ordering.from(comparator)
-                    : Ordering.natural().onResultOf(toJson);
-                ImmutableList<Profiler.Statistic> statistics2 =
-                    comp.immutableSortedCopy(statistics);
-                if (limit >= 0 && limit < statistics2.size()) {
-                  statistics2 = statistics2.subList(0, limit);
-                }
-
-                final List<String> strings =
-                    Lists.transform(statistics2, toJson);
-                assertThat(strings, matcher);
-              } catch (SQLException e) {
-                throw new RuntimeException(e);
+          .doWithConnection(c -> {
+            try (PreparedStatement s = c.prepareStatement(sql)) {
+              final ResultSetMetaData m = s.getMetaData();
+              final List<Profiler.Column> columns = new ArrayList<>();
+              final int columnCount = m.getColumnCount();
+              for (int i = 0; i < columnCount; i++) {
+                columns.add(new Profiler.Column(i, m.getColumnLabel(i + 1)));
+              }
+
+              // Create an initial group for each table in the query.
+              // Columns in the same table will tend to have the same
+              // cardinality as the table, and as the table's primary key.
+              final Multimap<String, Integer> groups = HashMultimap.create();
+              for (int i = 0; i < m.getColumnCount(); i++) {
+                groups.put(m.getTableName(i + 1), i);
+              }
+              final SortedSet<ImmutableBitSet> initialGroups =
+                  new TreeSet<>();
+              for (Collection<Integer> integers : groups.asMap().values()) {
+                initialGroups.add(ImmutableBitSet.of(integers));
               }
-              return null;
+              final Profiler p = factory.get();
+              final Enumerable<List<Comparable>> rows = getRows(s);
+              final Profiler.Profile profile =
+                  p.profile(rows, columns, initialGroups);
+              final List<Profiler.Statistic> statistics =
+                  profile.statistics().stream().filter(predicate)
+                      .collect(Util.toImmutableList());
+
+              // If no comparator specified, use the function that converts to
+              // JSON strings
+              final StatisticToJson toJson = new StatisticToJson();
+              Ordering<Profiler.Statistic> comp = comparator != null
+                  ? Ordering.from(comparator)
+                  : Ordering.natural().onResultOf(toJson::apply);
+              ImmutableList<Profiler.Statistic> statistics2 =
+                  comp.immutableSortedCopy(statistics);
+              if (limit >= 0 && limit < statistics2.size()) {
+                statistics2 = statistics2.subList(0, limit);
+              }
+
+              final List<String> strings =
+                  statistics2.stream().map(toJson::apply)
+                      .collect(Collectors.toList());
+              assertThat(strings, matcher);
+            } catch (SQLException e) {
+              throw new RuntimeException(e);
             }
           });
       return this;
     }
 
-    /** Returns a function that converts a statistic to a JSON string. */
-    Function<Profiler.Statistic, String> toJsonFunction() {
-      return new Function<Profiler.Statistic, String>() {
-        final JsonBuilder jb = new JsonBuilder();
-
-        public String apply(Profiler.Statistic statistic) {
-          Object map = statistic.toMap(jb);
-          if (map instanceof Map) {
-            @SuppressWarnings("unchecked")
-            final Map<String, Object> map1 = (Map) map;
-            map1.keySet().retainAll(Fluid.this.columns);
-          }
-          final String json = jb.toJsonString(map);
-          return json.replaceAll("\n", "").replaceAll(" ", "")
-              .replaceAll("\"", "");
-        }
-      };
-    }
-
     private Enumerable<List<Comparable>> getRows(final PreparedStatement s) {
       return new AbstractEnumerable<List<Comparable>>() {
         public Enumerator<List<Comparable>> enumerator() {
@@ -676,6 +613,23 @@ public class ProfilerTest {
         }
       };
     }
+
+    /** Returns a function that converts a statistic to a JSON string. */
+    private class StatisticToJson {
+      final JsonBuilder jb = new JsonBuilder();
+
+      public String apply(Profiler.Statistic statistic) {
+        Object map = statistic.toMap(jb);
+        if (map instanceof Map) {
+          @SuppressWarnings("unchecked")
+          final Map<String, Object> map1 = (Map) map;
+          map1.keySet().retainAll(Fluid.this.columns);
+        }
+        final String json = jb.toJsonString(map);
+        return json.replaceAll("\n", "").replaceAll(" ", "")
+            .replaceAll("\"", "");
+      }
+    }
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/rel/RelCollationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/rel/RelCollationTest.java b/core/src/test/java/org/apache/calcite/rel/RelCollationTest.java
index 84c816b..552c183 100644
--- a/core/src/test/java/org/apache/calcite/rel/RelCollationTest.java
+++ b/core/src/test/java/org/apache/calcite/rel/RelCollationTest.java
@@ -16,10 +16,9 @@
  */
 package org.apache.calcite.rel;
 
-import com.google.common.collect.Lists;
-
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
@@ -49,7 +48,7 @@ public class RelCollationTest {
         is(false));
     assertThat(RelCollations.contains(collation21, Arrays.asList(2, 1, 3)),
         is(false));
-    assertThat(RelCollations.contains(collation21, Arrays.<Integer>asList()),
+    assertThat(RelCollations.contains(collation21, Arrays.asList()),
         is(true));
 
     // if there are duplicates in keys, later occurrences are ignored
@@ -73,7 +72,7 @@ public class RelCollationTest {
         is(false));
     assertThat(RelCollations.contains(collation1, Arrays.asList(1, 2, 1)),
         is(false));
-    assertThat(RelCollations.contains(collation1, Arrays.<Integer>asList()),
+    assertThat(RelCollations.contains(collation1, Arrays.asList()),
         is(true));
   }
 
@@ -90,7 +89,7 @@ public class RelCollationTest {
   }
 
   private static RelCollation collation(int... ordinals) {
-    final List<RelFieldCollation> list = Lists.newArrayList();
+    final List<RelFieldCollation> list = new ArrayList<>();
     for (int ordinal : ordinals) {
       list.add(new RelFieldCollation(ordinal));
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
index 6673fac..53ba8a9 100644
--- a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
+++ b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
@@ -17,8 +17,6 @@
 package org.apache.calcite.rel.rel2sql;
 
 import org.apache.calcite.config.NullCollation;
-import org.apache.calcite.plan.RelOptLattice;
-import org.apache.calcite.plan.RelOptMaterialization;
 import org.apache.calcite.plan.RelOptPlanner;
 import org.apache.calcite.plan.RelTraitDef;
 import org.apache.calcite.plan.hep.HepPlanner;
@@ -46,14 +44,12 @@ import org.apache.calcite.tools.Programs;
 import org.apache.calcite.tools.RuleSet;
 import org.apache.calcite.tools.RuleSets;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 
 import org.junit.Test;
 
 import java.util.List;
-
-import junit.framework.AssertionFailedError;
+import java.util.function.Function;
 
 import static org.apache.calcite.test.Matchers.isLinux;
 
@@ -81,7 +77,7 @@ public class RelToSqlConverterTest {
   private Sql sql(String sql) {
     return new Sql(CalciteAssert.SchemaSpec.JDBC_FOODMART, sql,
         CalciteSqlDialect.DEFAULT, DEFAULT_REL_CONFIG,
-        ImmutableList.<Function<RelNode, RelNode>>of());
+        ImmutableList.of());
   }
 
   private static Planner getPlanner(List<RelTraitDef> traitDefs,
@@ -2578,13 +2574,10 @@ public class RelToSqlConverterTest {
 
     Sql optimize(final RuleSet ruleSet, final RelOptPlanner relOptPlanner) {
       return new Sql(schemaSpec, sql, dialect, config,
-          FlatLists.append(transforms, new Function<RelNode, RelNode>() {
-            public RelNode apply(RelNode r) {
-              Program program = Programs.of(ruleSet);
-              return program.run(relOptPlanner, r, r.getTraitSet(),
-                  ImmutableList.<RelOptMaterialization>of(),
-                  ImmutableList.<RelOptLattice>of());
-            }
+          FlatLists.append(transforms, r -> {
+            Program program = Programs.of(ruleSet);
+            return program.run(relOptPlanner, r, r.getTraitSet(),
+                ImmutableList.of(), ImmutableList.of());
           }));
     }
 
@@ -2596,7 +2589,7 @@ public class RelToSqlConverterTest {
     Sql throws_(String errorMessage) {
       try {
         final String s = exec();
-        throw new AssertionFailedError("Expected exception with message `"
+        throw new AssertionError("Expected exception with message `"
             + errorMessage + "` but nothing was thrown; got " + s);
       } catch (Exception e) {
         assertThat(e.getMessage(), is(errorMessage));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/rel/rules/DateRangeRulesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/rel/rules/DateRangeRulesTest.java b/core/src/test/java/org/apache/calcite/rel/rules/DateRangeRulesTest.java
index 01fe9bc..88312fe 100644
--- a/core/src/test/java/org/apache/calcite/rel/rules/DateRangeRulesTest.java
+++ b/core/src/test/java/org/apache/calcite/rel/rules/DateRangeRulesTest.java
@@ -745,26 +745,26 @@ public class DateRangeRulesTest {
           ImmutableList.of(rexBuilder.makeFlag(TimeUnitRange.DAY), d));
 
       floorYear = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.FLOOR,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.YEAR)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.YEAR)));
       floorMonth = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.FLOOR,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.MONTH)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.MONTH)));
       floorDay = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.FLOOR,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.DAY)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.DAY)));
       floorHour = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.FLOOR,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.HOUR)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.HOUR)));
       floorMinute = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.FLOOR,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.MINUTE)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.MINUTE)));
 
       ceilYear = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.CEIL,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.YEAR)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.YEAR)));
       ceilMonth = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.CEIL,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.MONTH)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.MONTH)));
       ceilDay = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.CEIL,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.DAY)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.DAY)));
       ceilHour = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.CEIL,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.HOUR)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.HOUR)));
       ceilMinute = rexBuilder.makeCall(intRelDataType, SqlStdOperatorTable.CEIL,
-          ImmutableList.<RexNode>of(ts, rexBuilder.makeFlag(TimeUnitRange.MINUTE)));
+          ImmutableList.of(ts, rexBuilder.makeFlag(TimeUnitRange.MINUTE)));
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/rex/RexExecutorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/rex/RexExecutorTest.java b/core/src/test/java/org/apache/calcite/rex/RexExecutorTest.java
index d421033..4e20d2c 100644
--- a/core/src/test/java/org/apache/calcite/rex/RexExecutorTest.java
+++ b/core/src/test/java/org/apache/calcite/rex/RexExecutorTest.java
@@ -40,7 +40,6 @@ import org.apache.calcite.util.DateString;
 import org.apache.calcite.util.NlsString;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 
 import org.junit.Assert;
@@ -50,6 +49,7 @@ import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Random;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.instanceOf;
@@ -84,56 +84,51 @@ public class RexExecutorTest {
   /** Tests an executor that uses variables stored in a {@link DataContext}.
    * Can change the value of the variable and execute again. */
   @Test public void testVariableExecution() throws Exception {
-    check(
-        new Action() {
-          public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-            Object[] values = new Object[1];
-            final DataContext testContext = new TestDataContext(values);
-            final RelDataTypeFactory typeFactory = rexBuilder.getTypeFactory();
-            final RelDataType varchar =
-                typeFactory.createSqlType(SqlTypeName.VARCHAR);
-            final RelDataType integer =
-                typeFactory.createSqlType(SqlTypeName.INTEGER);
-            // Calcite is internally creating the input ref via a RexRangeRef
-            // which eventually leads to a RexInputRef. So we are good.
-            final RexInputRef input = rexBuilder.makeInputRef(varchar, 0);
-            final RexNode lengthArg = rexBuilder.makeLiteral(3, integer, true);
-            final RexNode substr =
-                rexBuilder.makeCall(SqlStdOperatorTable.SUBSTRING, input,
-                    lengthArg);
-            ImmutableList<RexNode> constExps = ImmutableList.of(substr);
+    check((rexBuilder, executor) -> {
+      Object[] values = new Object[1];
+      final DataContext testContext = new TestDataContext(values);
+      final RelDataTypeFactory typeFactory = rexBuilder.getTypeFactory();
+      final RelDataType varchar =
+          typeFactory.createSqlType(SqlTypeName.VARCHAR);
+      final RelDataType integer =
+          typeFactory.createSqlType(SqlTypeName.INTEGER);
+      // Calcite is internally creating the input ref via a RexRangeRef
+      // which eventually leads to a RexInputRef. So we are good.
+      final RexInputRef input = rexBuilder.makeInputRef(varchar, 0);
+      final RexNode lengthArg = rexBuilder.makeLiteral(3, integer, true);
+      final RexNode substr =
+          rexBuilder.makeCall(SqlStdOperatorTable.SUBSTRING, input,
+              lengthArg);
+      ImmutableList<RexNode> constExps = ImmutableList.of(substr);
 
-            final RelDataType rowType = typeFactory.builder()
-                .add("someStr", varchar)
-                .build();
+      final RelDataType rowType = typeFactory.builder()
+          .add("someStr", varchar)
+          .build();
 
-            final RexExecutable exec = executor.getExecutable(rexBuilder,
-                constExps, rowType);
-            exec.setDataContext(testContext);
-            values[0] = "Hello World";
-            Object[] result = exec.execute();
-            assertTrue(result[0] instanceof String);
-            assertThat((String) result[0], equalTo("llo World"));
-            values[0] = "Calcite";
-            result = exec.execute();
-            assertTrue(result[0] instanceof String);
-            assertThat((String) result[0], equalTo("lcite"));
-          }
-        });
+      final RexExecutable exec = executor.getExecutable(rexBuilder,
+          constExps, rowType);
+      exec.setDataContext(testContext);
+      values[0] = "Hello World";
+      Object[] result = exec.execute();
+      assertTrue(result[0] instanceof String);
+      assertThat((String) result[0], equalTo("llo World"));
+      values[0] = "Calcite";
+      result = exec.execute();
+      assertTrue(result[0] instanceof String);
+      assertThat((String) result[0], equalTo("lcite"));
+    });
   }
 
   @Test public void testConstant() throws Exception {
-    check(new Action() {
-      public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-        final List<RexNode> reducedValues = new ArrayList<>();
-        final RexLiteral ten = rexBuilder.makeExactLiteral(BigDecimal.TEN);
-        executor.reduce(rexBuilder, ImmutableList.<RexNode>of(ten),
-            reducedValues);
-        assertThat(reducedValues.size(), equalTo(1));
-        assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
-        assertThat(((RexLiteral) reducedValues.get(0)).getValue2(),
-            equalTo((Object) 10L));
-      }
+    check((rexBuilder, executor) -> {
+      final List<RexNode> reducedValues = new ArrayList<>();
+      final RexLiteral ten = rexBuilder.makeExactLiteral(BigDecimal.TEN);
+      executor.reduce(rexBuilder, ImmutableList.of(ten),
+          reducedValues);
+      assertThat(reducedValues.size(), equalTo(1));
+      assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
+      assertThat(((RexLiteral) reducedValues.get(0)).getValue2(),
+          equalTo((Object) 10L));
     });
   }
 
@@ -141,154 +136,127 @@ public class RexExecutorTest {
   @Test public void testConstant2() throws Exception {
     // Same as testConstant; 10 -> 10
     checkConstant(10L,
-        new Function<RexBuilder, RexNode>() {
-          public RexNode apply(RexBuilder rexBuilder) {
-            return rexBuilder.makeExactLiteral(BigDecimal.TEN);
-          }
-        });
+        rexBuilder -> rexBuilder.makeExactLiteral(BigDecimal.TEN));
     // 10 + 1 -> 11
     checkConstant(11L,
-        new Function<RexBuilder, RexNode>() {
-          public RexNode apply(RexBuilder rexBuilder) {
-            return rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
-                rexBuilder.makeExactLiteral(BigDecimal.TEN),
-                rexBuilder.makeExactLiteral(BigDecimal.ONE));
-          }
-        });
+        rexBuilder -> rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
+            rexBuilder.makeExactLiteral(BigDecimal.TEN),
+            rexBuilder.makeExactLiteral(BigDecimal.ONE)));
     // date 'today' <= date 'today' -> true
-    checkConstant(true,
-        new Function<RexBuilder, RexNode>() {
-          public RexNode apply(RexBuilder rexBuilder) {
-            final DateString d =
-                DateString.fromCalendarFields(Util.calendar());
-            return rexBuilder.makeCall(SqlStdOperatorTable.LESS_THAN_OR_EQUAL,
-                rexBuilder.makeDateLiteral(d),
-                rexBuilder.makeDateLiteral(d));
-          }
-        });
+    checkConstant(true, rexBuilder -> {
+      final DateString d =
+          DateString.fromCalendarFields(Util.calendar());
+      return rexBuilder.makeCall(SqlStdOperatorTable.LESS_THAN_OR_EQUAL,
+          rexBuilder.makeDateLiteral(d),
+          rexBuilder.makeDateLiteral(d));
+    });
     // date 'today' < date 'today' -> false
-    checkConstant(false,
-        new Function<RexBuilder, RexNode>() {
-          public RexNode apply(RexBuilder rexBuilder) {
-            final DateString d =
-                DateString.fromCalendarFields(Util.calendar());
-            return rexBuilder.makeCall(SqlStdOperatorTable.LESS_THAN,
-                rexBuilder.makeDateLiteral(d),
-                rexBuilder.makeDateLiteral(d));
-          }
-        });
+    checkConstant(false, rexBuilder -> {
+      final DateString d =
+          DateString.fromCalendarFields(Util.calendar());
+      return rexBuilder.makeCall(SqlStdOperatorTable.LESS_THAN,
+          rexBuilder.makeDateLiteral(d),
+          rexBuilder.makeDateLiteral(d));
+    });
   }
 
   private void checkConstant(final Object operand,
       final Function<RexBuilder, RexNode> function) throws Exception {
-    check(
-        new Action() {
-          public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-            final List<RexNode> reducedValues = new ArrayList<>();
-            final RexNode expression = function.apply(rexBuilder);
-            assert expression != null;
-            executor.reduce(rexBuilder, ImmutableList.of(expression),
-                reducedValues);
-            assertThat(reducedValues.size(), equalTo(1));
-            assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
-            assertThat(((RexLiteral) reducedValues.get(0)).getValue2(),
-                equalTo(operand));
-          }
-        });
+    check((rexBuilder, executor) -> {
+      final List<RexNode> reducedValues = new ArrayList<>();
+      final RexNode expression = function.apply(rexBuilder);
+      assert expression != null;
+      executor.reduce(rexBuilder, ImmutableList.of(expression),
+          reducedValues);
+      assertThat(reducedValues.size(), equalTo(1));
+      assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
+      assertThat(((RexLiteral) reducedValues.get(0)).getValue2(),
+          equalTo(operand));
+    });
   }
 
   @Test public void testSubstring() throws Exception {
-    check(new Action() {
-      public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-        final List<RexNode> reducedValues = new ArrayList<>();
-        final RexLiteral hello =
-            rexBuilder.makeCharLiteral(
-                new NlsString("Hello world!", null, null));
-        final RexNode plus =
-            rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
-                rexBuilder.makeExactLiteral(BigDecimal.ONE),
-                rexBuilder.makeExactLiteral(BigDecimal.ONE));
-        RexLiteral four = rexBuilder.makeExactLiteral(BigDecimal.valueOf(4));
-        final RexNode substring =
-            rexBuilder.makeCall(SqlStdOperatorTable.SUBSTRING,
-                hello, plus, four);
-        executor.reduce(rexBuilder, ImmutableList.of(substring, plus),
-            reducedValues);
-        assertThat(reducedValues.size(), equalTo(2));
-        assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
-        assertThat(((RexLiteral) reducedValues.get(0)).getValue2(),
-            equalTo((Object) "ello")); // substring('Hello world!, 2, 4)
-        assertThat(reducedValues.get(1), instanceOf(RexLiteral.class));
-        assertThat(((RexLiteral) reducedValues.get(1)).getValue2(),
-            equalTo((Object) 2L));
-      }
+    check((rexBuilder, executor) -> {
+      final List<RexNode> reducedValues = new ArrayList<>();
+      final RexLiteral hello =
+          rexBuilder.makeCharLiteral(
+              new NlsString("Hello world!", null, null));
+      final RexNode plus =
+          rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
+              rexBuilder.makeExactLiteral(BigDecimal.ONE),
+              rexBuilder.makeExactLiteral(BigDecimal.ONE));
+      RexLiteral four = rexBuilder.makeExactLiteral(BigDecimal.valueOf(4));
+      final RexNode substring =
+          rexBuilder.makeCall(SqlStdOperatorTable.SUBSTRING,
+              hello, plus, four);
+      executor.reduce(rexBuilder, ImmutableList.of(substring, plus),
+          reducedValues);
+      assertThat(reducedValues.size(), equalTo(2));
+      assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
+      assertThat(((RexLiteral) reducedValues.get(0)).getValue2(),
+          equalTo((Object) "ello")); // substring('Hello world!, 2, 4)
+      assertThat(reducedValues.get(1), instanceOf(RexLiteral.class));
+      assertThat(((RexLiteral) reducedValues.get(1)).getValue2(),
+          equalTo((Object) 2L));
     });
   }
 
   @Test public void testBinarySubstring() throws Exception {
-    check(new Action() {
-      public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-        final List<RexNode> reducedValues = new ArrayList<>();
-        // hello world! -> 48656c6c6f20776f726c6421
-        final RexLiteral binaryHello =
-            rexBuilder.makeBinaryLiteral(
-                new ByteString("Hello world!".getBytes(UTF_8)));
-        final RexNode plus =
-            rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
-                rexBuilder.makeExactLiteral(BigDecimal.ONE),
-                rexBuilder.makeExactLiteral(BigDecimal.ONE));
-        RexLiteral four = rexBuilder.makeExactLiteral(BigDecimal.valueOf(4));
-        final RexNode substring =
-            rexBuilder.makeCall(SqlStdOperatorTable.SUBSTRING,
-                binaryHello, plus, four);
-        executor.reduce(rexBuilder, ImmutableList.of(substring, plus),
-            reducedValues);
-        assertThat(reducedValues.size(), equalTo(2));
-        assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
-        assertThat(((RexLiteral) reducedValues.get(0)).getValue2().toString(),
-            equalTo((Object) "656c6c6f")); // substring('Hello world!, 2, 4)
-        assertThat(reducedValues.get(1), instanceOf(RexLiteral.class));
-        assertThat(((RexLiteral) reducedValues.get(1)).getValue2(),
-            equalTo((Object) 2L));
-      }
+    check((rexBuilder, executor) -> {
+      final List<RexNode> reducedValues = new ArrayList<>();
+      // hello world! -> 48656c6c6f20776f726c6421
+      final RexLiteral binaryHello =
+          rexBuilder.makeBinaryLiteral(
+              new ByteString("Hello world!".getBytes(UTF_8)));
+      final RexNode plus =
+          rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
+              rexBuilder.makeExactLiteral(BigDecimal.ONE),
+              rexBuilder.makeExactLiteral(BigDecimal.ONE));
+      RexLiteral four = rexBuilder.makeExactLiteral(BigDecimal.valueOf(4));
+      final RexNode substring =
+          rexBuilder.makeCall(SqlStdOperatorTable.SUBSTRING,
+              binaryHello, plus, four);
+      executor.reduce(rexBuilder, ImmutableList.of(substring, plus),
+          reducedValues);
+      assertThat(reducedValues.size(), equalTo(2));
+      assertThat(reducedValues.get(0), instanceOf(RexLiteral.class));
+      assertThat(((RexLiteral) reducedValues.get(0)).getValue2().toString(),
+          equalTo((Object) "656c6c6f")); // substring('Hello world!, 2, 4)
+      assertThat(reducedValues.get(1), instanceOf(RexLiteral.class));
+      assertThat(((RexLiteral) reducedValues.get(1)).getValue2(),
+          equalTo((Object) 2L));
     });
   }
 
   @Test public void testDeterministic1() throws Exception {
-    check(new Action() {
-      public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-        final RexNode plus =
-            rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
-                rexBuilder.makeExactLiteral(BigDecimal.ONE),
-                rexBuilder.makeExactLiteral(BigDecimal.ONE));
-        assertThat(RexUtil.isDeterministic(plus), equalTo(true));
-      }
+    check((rexBuilder, executor) -> {
+      final RexNode plus =
+          rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
+              rexBuilder.makeExactLiteral(BigDecimal.ONE),
+              rexBuilder.makeExactLiteral(BigDecimal.ONE));
+      assertThat(RexUtil.isDeterministic(plus), equalTo(true));
     });
   }
 
   @Test public void testDeterministic2() throws Exception {
-    check(new Action() {
-      public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-        final RexNode plus =
-            rexBuilder.makeCall(PLUS_RANDOM,
-                rexBuilder.makeExactLiteral(BigDecimal.ONE),
-                rexBuilder.makeExactLiteral(BigDecimal.ONE));
-        assertThat(RexUtil.isDeterministic(plus), equalTo(false));
-      }
+    check((rexBuilder, executor) -> {
+      final RexNode plus =
+          rexBuilder.makeCall(PLUS_RANDOM,
+              rexBuilder.makeExactLiteral(BigDecimal.ONE),
+              rexBuilder.makeExactLiteral(BigDecimal.ONE));
+      assertThat(RexUtil.isDeterministic(plus), equalTo(false));
     });
   }
 
   @Test public void testDeterministic3() throws Exception {
-    check(new Action() {
-      public void check(RexBuilder rexBuilder, RexExecutorImpl executor) {
-        final RexNode plus =
-            rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
-                rexBuilder.makeCall(PLUS_RANDOM,
-                    rexBuilder.makeExactLiteral(BigDecimal.ONE),
-                    rexBuilder.makeExactLiteral(BigDecimal.ONE)),
-                rexBuilder.makeExactLiteral(BigDecimal.ONE));
-        assertThat(RexUtil.isDeterministic(plus), equalTo(false));
-      }
+    check((rexBuilder, executor) -> {
+      final RexNode plus =
+          rexBuilder.makeCall(SqlStdOperatorTable.PLUS,
+              rexBuilder.makeCall(PLUS_RANDOM,
+                  rexBuilder.makeExactLiteral(BigDecimal.ONE),
+                  rexBuilder.makeExactLiteral(BigDecimal.ONE)),
+              rexBuilder.makeExactLiteral(BigDecimal.ONE));
+      assertThat(RexUtil.isDeterministic(plus), equalTo(false));
     });
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/runtime/BinarySearchTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/runtime/BinarySearchTest.java b/core/src/test/java/org/apache/calcite/runtime/BinarySearchTest.java
index 345a324..15b34a9 100644
--- a/core/src/test/java/org/apache/calcite/runtime/BinarySearchTest.java
+++ b/core/src/test/java/org/apache/calcite/runtime/BinarySearchTest.java
@@ -30,10 +30,10 @@ public class BinarySearchTest {
   private void search(int key, int lower, int upper, Integer... array) {
     Assert.assertEquals(
         "lower bound of " + key + " in " + Arrays.toString(array), lower,
-        BinarySearch.lowerBound(array, key, Ordering.<Integer>natural()));
+        BinarySearch.lowerBound(array, key, Ordering.natural()));
     Assert.assertEquals(
         "upper bound of " + key + " in " + Arrays.toString(array), upper,
-        BinarySearch.upperBound(array, key, Ordering.<Integer>natural()));
+        BinarySearch.upperBound(array, key, Ordering.natural()));
   }
 
   @Test

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/runtime/EnumerablesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/runtime/EnumerablesTest.java b/core/src/test/java/org/apache/calcite/runtime/EnumerablesTest.java
index 5e76578..aab9520 100644
--- a/core/src/test/java/org/apache/calcite/runtime/EnumerablesTest.java
+++ b/core/src/test/java/org/apache/calcite/runtime/EnumerablesTest.java
@@ -19,7 +19,6 @@ package org.apache.calcite.runtime;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.EnumerableDefaults;
 import org.apache.calcite.linq4j.Linq4j;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.linq4j.function.Function2;
 import org.apache.calcite.linq4j.function.Functions;
 import org.apache.calcite.linq4j.function.Predicate2;
@@ -28,9 +27,12 @@ import com.google.common.collect.Lists;
 
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
+import static com.google.common.collect.Lists.newArrayList;
+
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.junit.Assert.assertThat;
 
@@ -51,37 +53,19 @@ public class EnumerablesTest {
           new Dept(15, "Marketing")));
 
   private static final Function2<Emp, Dept, String> EMP_DEPT_TO_STRING =
-      new Function2<Emp, Dept, String>() {
-        public String apply(Emp v0, Dept v1) {
-          return "{" + (v0 == null ? null : v0.name)
-              + ", " + (v0 == null ? null : v0.deptno)
-              + ", " + (v1 == null ? null : v1.deptno)
-              + ", " + (v1 == null ? null : v1.name)
-              + "}";
-        }
-      };
+      (v0, v1) -> "{" + (v0 == null ? null : v0.name)
+          + ", " + (v0 == null ? null : v0.deptno)
+          + ", " + (v1 == null ? null : v1.deptno)
+          + ", " + (v1 == null ? null : v1.name)
+          + "}";
 
   private static final Predicate2<Emp, Dept> EQUAL_DEPTNO =
-      new Predicate2<Emp, Dept>() {
-        public boolean apply(Emp v0, Dept v1) {
-          return v0.deptno == v1.deptno;
-        }
-      };
+      (e, d) -> e.deptno == d.deptno;
 
   @Test public void testSemiJoin() {
     assertThat(
-        EnumerableDefaults.semiJoin(EMPS, DEPTS,
-            new Function1<Emp, Integer>() {
-              public Integer apply(Emp a0) {
-                return a0.deptno;
-              }
-            },
-            new Function1<Dept, Integer>() {
-              public Integer apply(Dept a0) {
-                return a0.deptno;
-              }
-            },
-            Functions.<Integer>identityComparer()).toList().toString(),
+        EnumerableDefaults.semiJoin(EMPS, DEPTS, e -> e.deptno, d -> d.deptno,
+            Functions.identityComparer()).toList().toString(),
         equalTo("[Emp(20, Theodore), Emp(20, Sebastian)]"));
   }
 
@@ -101,21 +85,9 @@ public class EnumerablesTest {
                     new Dept(20, "Sales"),
                     new Dept(30, "Research"),
                     new Dept(30, "Development"))),
-            new Function1<Emp, Integer>() {
-              public Integer apply(Emp a0) {
-                return a0.deptno;
-              }
-            },
-            new Function1<Dept, Integer>() {
-              public Integer apply(Dept a0) {
-                return a0.deptno;
-              }
-            },
-            new Function2<Emp, Dept, String>() {
-              public String apply(Emp v0, Dept v1) {
-                return v0 + ", " + v1;
-              }
-            }, false, false).toList().toString(),
+            e -> e.deptno,
+            d -> d.deptno,
+            (v0, v1) -> v0 + ", " + v1, false, false).toList().toString(),
         equalTo("[Emp(20, Theodore), Dept(20, Sales),"
             + " Emp(20, Sebastian), Dept(20, Sales),"
             + " Emp(30, Joe), Dept(30, Research),"
@@ -155,18 +127,18 @@ public class EnumerablesTest {
         equalTo("[]"));
     // Left empty
     assertThat(
-        intersect(Lists.<Integer>newArrayList(),
-            Lists.newArrayList(1, 3, 4, 6)).toList().toString(),
+        intersect(new ArrayList<>(),
+            newArrayList(1, 3, 4, 6)).toList().toString(),
         equalTo("[]"));
     // Right empty
     assertThat(
-        intersect(Lists.newArrayList(3, 7),
-            Lists.<Integer>newArrayList()).toList().toString(),
+        intersect(newArrayList(3, 7),
+            new ArrayList<>()).toList().toString(),
         equalTo("[]"));
     // Both empty
     assertThat(
-        intersect(Lists.<Integer>newArrayList(),
-            Lists.<Integer>newArrayList()).toList().toString(),
+        intersect(new ArrayList<Integer>(),
+            new ArrayList<>()).toList().toString(),
         equalTo("[]"));
   }
 
@@ -175,13 +147,8 @@ public class EnumerablesTest {
     return EnumerableDefaults.mergeJoin(
         Linq4j.asEnumerable(list0),
         Linq4j.asEnumerable(list1),
-        Functions.<T>identitySelector(),
-        Functions.<T>identitySelector(),
-        new Function2<T, T, T>() {
-          public T apply(T v0, T v1) {
-            return v0;
-          }
-        }, false, false);
+        Functions.identitySelector(),
+        Functions.identitySelector(), (v0, v1) -> v0, false, false);
   }
 
   @Test public void testThetaJoin() {
@@ -220,7 +187,7 @@ public class EnumerablesTest {
     assertThat(
         EnumerableDefaults.thetaJoin(EMPS.take(0), DEPTS, EQUAL_DEPTNO,
             EMP_DEPT_TO_STRING, true, true)
-            .orderBy(Functions.<String>identitySelector()).toList().toString(),
+            .orderBy(Functions.identitySelector()).toList().toString(),
         equalTo("[{null, null, 15, Marketing}, {null, null, 20, Sales}]"));
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java b/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
index c3c1920..822c136 100644
--- a/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/parser/SqlParserTest.java
@@ -550,11 +550,7 @@ public class SqlParserTest {
   private static final String ANY = "(?s).*";
 
   private static final ThreadLocal<boolean[]> LINUXIFY =
-      new ThreadLocal<boolean[]>() {
-        @Override protected boolean[] initialValue() {
-          return new boolean[] {true};
-        }
-      };
+      ThreadLocal.withInitial(() -> new boolean[] {true});
 
   Quoting quoting = Quoting.DOUBLE_QUOTE;
   Casing unquotedCasing = Casing.TO_UPPER;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/sql/test/DefaultSqlTestFactory.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/test/DefaultSqlTestFactory.java b/core/src/test/java/org/apache/calcite/sql/test/DefaultSqlTestFactory.java
index ffdf886..e2667d5 100644
--- a/core/src/test/java/org/apache/calcite/sql/test/DefaultSqlTestFactory.java
+++ b/core/src/test/java/org/apache/calcite/sql/test/DefaultSqlTestFactory.java
@@ -73,30 +73,7 @@ public class DefaultSqlTestFactory implements SqlTestFactory {
    * Caching improves SqlValidatorTest from 23s to 8s,
    * and CalciteSqlOperatorTest from 65s to 43s. */
   private final LoadingCache<SqlTestFactory, Xyz> cache =
-      CacheBuilder.newBuilder()
-          .build(
-              new CacheLoader<SqlTestFactory, Xyz>() {
-                public Xyz load(@Nonnull SqlTestFactory factory)
-                    throws Exception {
-                  final SqlOperatorTable operatorTable =
-                      factory.createOperatorTable(factory);
-                  RelDataTypeSystem typeSystem = RelDataTypeSystem.DEFAULT;
-                  final SqlConformance conformance =
-                      (SqlConformance) factory.get("conformance");
-                  if (conformance.shouldConvertRaggedUnionTypesToVarying()) {
-                    typeSystem = new DelegatingTypeSystem(typeSystem) {
-                      public boolean shouldConvertRaggedUnionTypesToVarying() {
-                        return true;
-                      }
-                    };
-                  }
-                  final JavaTypeFactory typeFactory =
-                      new JavaTypeFactoryImpl(typeSystem);
-                  final MockCatalogReader catalogReader =
-                      factory.createCatalogReader(factory, typeFactory);
-                  return new Xyz(operatorTable, typeFactory, catalogReader);
-                }
-              });
+      CacheBuilder.newBuilder().build(CacheLoader.from(Xyz::from));
 
   public static final DefaultSqlTestFactory INSTANCE =
       new DefaultSqlTestFactory();
@@ -157,16 +134,24 @@ public class DefaultSqlTestFactory implements SqlTestFactory {
       this.catalogReader = catalogReader;
     }
 
-    public SqlOperatorTable getOperatorTable() {
-      return operatorTable;
-    }
-
-    public JavaTypeFactory getTypeFactory() {
-      return typeFactory;
-    }
-
-    public MockCatalogReader getCatalogReader() {
-      return catalogReader;
+    static Xyz from(@Nonnull SqlTestFactory factory) {
+      final SqlOperatorTable operatorTable =
+          factory.createOperatorTable(factory);
+      RelDataTypeSystem typeSystem = RelDataTypeSystem.DEFAULT;
+      final SqlConformance conformance =
+          (SqlConformance) factory.get("conformance");
+      if (conformance.shouldConvertRaggedUnionTypesToVarying()) {
+        typeSystem = new DelegatingTypeSystem(typeSystem) {
+          public boolean shouldConvertRaggedUnionTypesToVarying() {
+            return true;
+          }
+        };
+      }
+      final JavaTypeFactory typeFactory =
+          new JavaTypeFactoryImpl(typeSystem);
+      final MockCatalogReader catalogReader =
+          factory.createCatalogReader(factory, typeFactory);
+      return new Xyz(operatorTable, typeFactory, catalogReader);
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java b/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
index afb60c1..e8b163a 100644
--- a/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/test/SqlOperatorBaseTest.java
@@ -57,9 +57,7 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.TimestampString;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
 
 import org.junit.Before;
 import org.junit.Ignore;
@@ -79,6 +77,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
 import java.util.TimeZone;
+import java.util.function.Consumer;
 import java.util.regex.Pattern;
 
 import static org.hamcrest.CoreMatchers.equalTo;
@@ -5083,9 +5082,7 @@ public abstract class SqlOperatorBaseTest {
     final Hook.Closeable closeable;
     if (CalciteAssert.ENABLE_SLOW) {
       calendar = getCalendarNotTooNear(Calendar.HOUR_OF_DAY);
-      closeable = new Hook.Closeable() {
-        public void close() {}
-      };
+      closeable = () -> { };
     } else {
       calendar = Util.calendar();
       calendar.set(Calendar.YEAR, 2014);
@@ -5097,12 +5094,7 @@ public abstract class SqlOperatorBaseTest {
       calendar.set(Calendar.MILLISECOND, 15);
       final long timeInMillis = calendar.getTimeInMillis();
       closeable = Hook.CURRENT_TIME.addThread(
-          new Function<Holder<Long>, Void>() {
-            public Void apply(Holder<Long> o) {
-              o.set(timeInMillis);
-              return null;
-            }
-          });
+          (Consumer<Holder<Long>>) o -> o.set(timeInMillis));
     }
 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:", Locale.ROOT);
@@ -5530,7 +5522,8 @@ public abstract class SqlOperatorBaseTest {
         "Invalid number of arguments to function 'COLLECT'. Was expecting 1 arguments",
         false);
     final String[] values = {"0", "CAST(null AS INTEGER)", "2", "2"};
-    tester.checkAgg("collect(x)", values, Arrays.asList("[0, 2, 2]"), (double) 0);
+    tester.checkAgg("collect(x)", values,
+        Collections.singletonList("[0, 2, 2]"), (double) 0);
     Object result1 = -3;
     if (!enable) {
       return;
@@ -7470,7 +7463,7 @@ public abstract class SqlOperatorBaseTest {
                 query = SqlTesterImpl.buildQuery(s);
               }
               tester.check(query, SqlTests.ANY_TYPE_CHECKER,
-                  SqlTests.ANY_PARAMETER_CHECKER, SqlTests.ANY_RESULT_CHECKER);
+                  SqlTests.ANY_PARAMETER_CHECKER, result -> { });
             }
           } catch (Error e) {
             System.out.println(s + ": " + e.getMessage());
@@ -7674,8 +7667,8 @@ public abstract class SqlOperatorBaseTest {
   /** Builds lists of types and sample values. */
   static class Builder {
     final RelDataTypeFactory typeFactory;
-    final List<RelDataType> types = Lists.newArrayList();
-    final List<ValueType> values = Lists.newArrayList();
+    final List<RelDataType> types = new ArrayList<>();
+    final List<ValueType> values = new ArrayList<>();
 
     Builder(RelDataTypeFactory typeFactory) {
       this.typeFactory = typeFactory;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/sql/test/SqlTesterImpl.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/test/SqlTesterImpl.java b/core/src/test/java/org/apache/calcite/sql/test/SqlTesterImpl.java
index c4eba51..d215b45 100644
--- a/core/src/test/java/org/apache/calcite/sql/test/SqlTesterImpl.java
+++ b/core/src/test/java/org/apache/calcite/sql/test/SqlTesterImpl.java
@@ -56,8 +56,6 @@ import com.google.common.collect.ImmutableList;
 import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -598,21 +596,15 @@ public class SqlTesterImpl implements SqlTester, AutoCloseable {
           }
         });
     final List<SqlNode> nodes = new ArrayList<>(literalSet);
-    Collections.sort(
-        nodes,
-        new Comparator<SqlNode>() {
-          public int compare(SqlNode o1, SqlNode o2) {
-            final SqlParserPos pos0 = o1.getParserPosition();
-            final SqlParserPos pos1 = o2.getParserPosition();
-            int c = -Utilities.compare(
-                pos0.getLineNum(), pos1.getLineNum());
-            if (c != 0) {
-              return c;
-            }
-            return -Utilities.compare(
-                pos0.getColumnNum(), pos1.getColumnNum());
-          }
-        });
+    nodes.sort((o1, o2) -> {
+      final SqlParserPos pos0 = o1.getParserPosition();
+      final SqlParserPos pos1 = o2.getParserPosition();
+      int c = -Utilities.compare(pos0.getLineNum(), pos1.getLineNum());
+      if (c != 0) {
+        return c;
+      }
+      return -Utilities.compare(pos0.getColumnNum(), pos1.getColumnNum());
+    });
     String sql2 = sql;
     final List<Pair<String, String>> values = new ArrayList<>();
     int p = 0;
@@ -655,30 +647,26 @@ public class SqlTesterImpl implements SqlTester, AutoCloseable {
     // Why an explicit iterable rather than a list? If there is
     // a syntax error in the expression, the calling code discovers it
     // before we try to parse it to do substitutions on the parse tree.
-    return new Iterable<String>() {
-      public Iterator<String> iterator() {
-        return new Iterator<String>() {
-          int i = 0;
+    return () -> new Iterator<String>() {
+      int i = 0;
 
-          public void remove() {
-            throw new UnsupportedOperationException();
-          }
+      public void remove() {
+        throw new UnsupportedOperationException();
+      }
 
-          public String next() {
-            switch (i++) {
-            case 0:
-              return buildQuery(expression);
-            case 1:
-              return buildQuery2(expression);
-            default:
-              throw new NoSuchElementException();
-            }
-          }
+      public String next() {
+        switch (i++) {
+        case 0:
+          return buildQuery(expression);
+        case 1:
+          return buildQuery2(expression);
+        default:
+          throw new NoSuchElementException();
+        }
+      }
 
-          public boolean hasNext() {
-            return i < 2;
-          }
-        };
+      public boolean hasNext() {
+        return i < 2;
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/sql/test/SqlTests.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/test/SqlTests.java b/core/src/test/java/org/apache/calcite/sql/test/SqlTests.java
index d2162de..e0c4bb1 100644
--- a/core/src/test/java/org/apache/calcite/sql/test/SqlTests.java
+++ b/core/src/test/java/org/apache/calcite/sql/test/SqlTests.java
@@ -52,20 +52,14 @@ public abstract class SqlTests {
   /**
    * Checker which allows any type.
    */
-  public static final TypeChecker ANY_TYPE_CHECKER =
-      new TypeChecker() {
-        public void checkType(RelDataType type) {
-        }
-      };
+  public static final TypeChecker ANY_TYPE_CHECKER = type -> {
+  };
 
   /**
    * Checker that allows any number or type of parameters.
    */
-  public static final ParameterChecker ANY_PARAMETER_CHECKER =
-      new ParameterChecker() {
-        public void checkParameters(RelDataType parameterRowType) {
-        }
-      };
+  public static final ParameterChecker ANY_PARAMETER_CHECKER = parameterRowType -> {
+  };
 
   /**
    * Helper function to get the string representation of a RelDataType
@@ -389,13 +383,6 @@ public abstract class SqlTests {
       compareResultSet(resultSet, expected);
     }
   }
-
-  /** Result checker that accepts any result. */
-  public static final ResultChecker ANY_RESULT_CHECKER =
-      new ResultChecker() {
-        public void checkResult(ResultSet result) {
-        }
-      };
 }
 
 // End SqlTests.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/sql/type/SqlTypeFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/type/SqlTypeFactoryTest.java b/core/src/test/java/org/apache/calcite/sql/type/SqlTypeFactoryTest.java
index f3c5209..60e3325 100644
--- a/core/src/test/java/org/apache/calcite/sql/type/SqlTypeFactoryTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/type/SqlTypeFactoryTest.java
@@ -26,7 +26,6 @@ import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
-
 /**
  * Test for {@link SqlTypeFactoryImpl}.
  */


[05/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/src/test/java/org/apache/calcite/test/Elasticsearch5AdapterIT.java
----------------------------------------------------------------------
diff --git a/elasticsearch5/src/test/java/org/apache/calcite/test/Elasticsearch5AdapterIT.java b/elasticsearch5/src/test/java/org/apache/calcite/test/Elasticsearch5AdapterIT.java
new file mode 100644
index 0000000..c727441
--- /dev/null
+++ b/elasticsearch5/src/test/java/org/apache/calcite/test/Elasticsearch5AdapterIT.java
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.test;
+
+import org.apache.calcite.util.Util;
+
+import com.google.common.collect.ImmutableMap;
+
+import org.junit.Test;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+/**
+ * Tests for the {@code org.apache.calcite.adapter.elasticsearch} package.
+ *
+ * <p>Before calling this test, you need to populate Elasticsearch, as follows:
+ *
+ * <blockquote><code>
+ * git clone https://github.com/vlsi/calcite-test-dataset<br>
+ * cd calcite-test-dataset<br>
+ * mvn install
+ * </code></blockquote>
+ *
+ * <p>This will create a virtual machine with Elasticsearch and the "zips" test
+ * dataset.
+ */
+public class Elasticsearch5AdapterIT {
+  /**
+   * Whether to run Elasticsearch tests. Enabled by default, however test is only
+   * included if "it" profile is activated ({@code -Pit}). To disable,
+   * specify {@code -Dcalcite.test.elasticsearch=false} on the Java command line.
+   */
+  private static final boolean ENABLED = Util.getBooleanProperty("calcite.test.elasticsearch",
+      true);
+
+  /** Connection factory based on the "zips-es" model. */
+  private static final ImmutableMap<String, String> ZIPS = ImmutableMap.of("model",
+      Elasticsearch5AdapterIT.class.getResource("/elasticsearch-zips-model.json").getPath());
+
+  /** Whether to run this test. */
+  private boolean enabled() {
+    return ENABLED;
+  }
+
+  /** Returns a function that checks that a particular Elasticsearch pipeline is
+   * generated to implement a query. */
+  private static Consumer<List> elasticsearchChecker(final String... strings) {
+    return actual -> {
+      Object[] actualArray = actual == null || actual.isEmpty() ? null
+          : ((List) actual.get(0)).toArray();
+      CalciteAssert.assertArrayEqual("expected Elasticsearch query not found", strings,
+          actualArray);
+    };
+  }
+
+  @Test public void testSort() {
+    final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
+        + "  ElasticsearchSort(sort0=[$4], dir0=[ASC])\n"
+        + "    ElasticsearchProject(city=[CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], longitude=[CAST(ITEM(ITEM($0, 'loc'), 0)):FLOAT], latitude=[CAST(ITEM(ITEM($0, 'loc'), 1)):FLOAT], pop=[CAST(ITEM($0, 'pop')):INTEGER], state=[CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], id=[CAST(ITEM($0, 'id')):VARCHAR(5) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"])\n"
+        + "      ElasticsearchTableScan(table=[[elasticsearch_raw, zips]])";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select * from zips order by \"state\"")
+        .returnsCount(10)
+        .explainContains(explain);
+  }
+
+  @Test public void testSortLimit() {
+    final String sql = "select \"state\", \"id\" from zips\n"
+        + "order by \"state\", \"id\" offset 2 rows fetch next 3 rows only";
+    CalciteAssert.that()
+        .with(ZIPS)
+        .query(sql)
+        .returnsUnordered("state=AK; id=99503",
+            "state=AK; id=99504",
+            "state=AK; id=99505")
+        .queryContains(
+            elasticsearchChecker(
+                "\"fields\" : [\"state\", \"id\"], \"script_fields\": {}",
+                "\"sort\": [ {\"state\": \"asc\"}, {\"id\": \"asc\"}]",
+                "\"from\": 2",
+                "\"size\": 3"));
+  }
+
+  @Test public void testOffsetLimit() {
+    final String sql = "select \"state\", \"id\" from zips\n"
+        + "offset 2 fetch next 3 rows only";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .runs()
+        .queryContains(
+            elasticsearchChecker(
+                "\"from\": 2",
+                "\"size\": 3",
+                "\"fields\" : [\"state\", \"id\"], \"script_fields\": {}"));
+  }
+
+  @Test public void testLimit() {
+    final String sql = "select \"state\", \"id\" from zips\n"
+        + "fetch next 3 rows only";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .runs()
+        .queryContains(
+            elasticsearchChecker(
+                "\"size\": 3",
+                "\"fields\" : [\"state\", \"id\"], \"script_fields\": {}"));
+  }
+
+  @Test public void testFilterSort() {
+    final String sql = "select * from zips\n"
+        + "where \"city\" = 'SPRINGFIELD' and \"id\" >= '70000'\n"
+        + "order by \"state\", \"id\"";
+    final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
+        + "  ElasticsearchSort(sort0=[$4], sort1=[$5], dir0=[ASC], dir1=[ASC])\n"
+        + "    ElasticsearchProject(city=[CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], longitude=[CAST(ITEM(ITEM($0, 'loc'), 0)):FLOAT], latitude=[CAST(ITEM(ITEM($0, 'loc'), 1)):FLOAT], pop=[CAST(ITEM($0, 'pop')):INTEGER], state=[CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], id=[CAST(ITEM($0, 'id')):VARCHAR(5) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"])\n"
+        + "      ElasticsearchFilter(condition=[AND(=(CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\", 'SPRINGFIELD'), >=(CAST(ITEM($0, 'id')):VARCHAR(5) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\", '70000'))])\n"
+        + "        ElasticsearchTableScan(table=[[elasticsearch_raw, zips]])";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .returnsOrdered(
+            "city=SPRINGFIELD; longitude=-92.54567; latitude=35.274879; pop=752; state=AR; id=72157",
+            "city=SPRINGFIELD; longitude=-102.617322; latitude=37.406727; pop=1992; state=CO; id=81073",
+            "city=SPRINGFIELD; longitude=-90.577479; latitude=30.415738; pop=5597; state=LA; id=70462",
+            "city=SPRINGFIELD; longitude=-123.015259; latitude=44.06106; pop=32384; state=OR; id=97477",
+            "city=SPRINGFIELD; longitude=-122.917108; latitude=44.056056; pop=27521; state=OR; id=97478")
+        .queryContains(
+            elasticsearchChecker("\"query\" : {\"constant_score\":{\"filter\":{\"bool\":"
+                    + "{\"must\":[{\"term\":{\"city\":\"springfield\"}},{\"range\":{\"id\":{\"gte\":\"70000\"}}}]}}}}",
+                "\"fields\" : [\"city\", \"pop\", \"state\", \"id\"], \"script_fields\": {\"longitude\":{\"script\":\"_source.loc[0]\"}, \"latitude\":{\"script\":\"_source.loc[1]\"}}",
+                "\"sort\": [ {\"state\": \"asc\"}, {\"id\": \"asc\"}]"))
+        .explainContains(explain);
+  }
+
+  @Test public void testFilterSortDesc() {
+    final String sql = "select * from zips\n"
+        + "where \"pop\" BETWEEN 20000 AND 20100\n"
+        + "order by \"state\" desc, \"pop\"";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .limit(4)
+        .returnsOrdered(
+            "city=SHERIDAN; longitude=-106.964795; latitude=44.78486; pop=20025; state=WY; id=82801",
+            "city=MOUNTLAKE TERRAC; longitude=-122.304036; latitude=47.793061; pop=20059; state=WA; id=98043",
+            "city=FALMOUTH; longitude=-77.404537; latitude=38.314557; pop=20039; state=VA; id=22405",
+            "city=FORT WORTH; longitude=-97.318409; latitude=32.725551; pop=20012; state=TX; id=76104");
+  }
+
+  @Test public void testFilterRedundant() {
+    final String sql = "select * from zips\n"
+        + "where \"state\" > 'CA' and \"state\" < 'AZ' and \"state\" = 'OK'";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .runs()
+        .queryContains(
+            elasticsearchChecker(""
+                + "\"query\" : {\"constant_score\":{\"filter\":{\"bool\":"
+                + "{\"must\":[{\"term\":{\"state\":\"ok\"}}]}}}}",
+                "\"fields\" : [\"city\", \"pop\", \"state\", \"id\"], \"script_fields\": {\"longitude\":{\"script\":\"_source.loc[0]\"}, \"latitude\":{\"script\":\"_source.loc[1]\"}}"));
+  }
+
+  @Test public void testInPlan() {
+    final String[] searches = {
+        "\"query\" : {\"constant_score\":{\"filter\":{\"bool\":{\"should\":"
+          + "[{\"bool\":{\"must\":[{\"term\":{\"pop\":20012}}]}},{\"bool\":{\"must\":[{\"term\":"
+          + "{\"pop\":15590}}]}}]}}}}",
+        "\"fields\" : [\"city\", \"pop\", \"state\", \"id\"], \"script_fields\": {\"longitude\":{\"script\":\"_source.loc[0]\"}, \"latitude\":{\"script\":\"_source.loc[1]\"}}"
+    };
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select * from zips where \"pop\" in (20012, 15590)")
+        .returnsUnordered(
+            "city=COVINA; longitude=-117.884285; latitude=34.08596; pop=15590; state=CA; id=91723",
+            "city=ARLINGTON; longitude=-97.091987; latitude=32.654752; pop=15590; state=TX; id=76018",
+            "city=CROFTON; longitude=-76.680166; latitude=39.011163; pop=15590; state=MD; id=21114",
+            "city=FORT WORTH; longitude=-97.318409; latitude=32.725551; pop=20012; state=TX; id=76104",
+            "city=DINUBA; longitude=-119.39087; latitude=36.534931; pop=20012; state=CA; id=93618")
+        .queryContains(elasticsearchChecker(searches));
+  }
+
+  @Test public void testZips() {
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips")
+        .returnsCount(10);
+  }
+
+  @Test public void testProject() {
+    final String sql = "select \"state\", \"city\", 0 as \"zero\"\n"
+        + "from zips\n"
+        + "order by \"state\", \"city\"";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .limit(2)
+        .returnsUnordered("state=AK; city=ELMENDORF AFB; zero=0",
+            "state=AK; city=EIELSON AFB; zero=0")
+        .queryContains(
+            elasticsearchChecker("\"sort\": [ {\"state\": \"asc\"}, {\"city\": \"asc\"}]",
+                "\"fields\" : [\"state\", \"city\"], \"script_fields\": {\"zero\":{\"script\": \"0\"}}"));
+  }
+
+  @Test public void testFilter() {
+    final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
+        + "  ElasticsearchProject(state=[CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], city=[CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"])\n"
+        + "    ElasticsearchFilter(condition=[=(CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\", 'CA')])\n"
+        + "      ElasticsearchTableScan(table=[[elasticsearch_raw, zips]])";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips where \"state\" = 'CA'")
+        .limit(2)
+        .returnsUnordered("state=CA; city=LOS ANGELES",
+            "state=CA; city=LOS ANGELES")
+        .explainContains(explain);
+  }
+
+  @Test public void testFilterReversed() {
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips where 'WI' < \"state\"")
+        .limit(2)
+        .returnsUnordered("state=WV; city=WELCH",
+            "state=WV; city=HANOVER");
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips where \"state\" > 'WI'")
+        .limit(2)
+        .returnsUnordered("state=WV; city=WELCH",
+            "state=WV; city=HANOVER");
+  }
+}
+
+// End Elasticsearch5AdapterIT.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
----------------------------------------------------------------------
diff --git a/elasticsearch5/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java b/elasticsearch5/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
index 550c04c..be236ed 100644
--- a/elasticsearch5/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
+++ b/elasticsearch5/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
@@ -16,11 +16,8 @@
  */
 package org.apache.calcite.test;
 
-import com.google.common.base.Function;
-
 import java.util.List;
-
-import javax.annotation.Nullable;
+import java.util.function.Consumer;
 
 /**
  * Utility methods for Elasticsearch tests.
@@ -29,23 +26,18 @@ public class ElasticsearchChecker {
 
   private ElasticsearchChecker() {}
 
-  /**
-   * Returns a function that checks that a particular Elasticsearch pipeline is
+  /** Returns a function that checks that a particular Elasticsearch pipeline is
    * generated to implement a query.
    *
-   * @param strings expected expressions
-   * @return validation function
+   * @param strings list of expected queries
+   * @return function to perform the check
    */
-  public static Function<List, Void> elasticsearchChecker(final String... strings) {
-    return new Function<List, Void>() {
-      @Nullable
-      @Override public Void apply(@Nullable List actual) {
-        Object[] actualArray = actual == null || actual.isEmpty() ? null
-            : ((List) actual.get(0)).toArray();
-        CalciteAssert.assertArrayEqual("expected Elasticsearch query not found", strings,
-            actualArray);
-        return null;
-      }
+  public static Consumer<List> elasticsearchChecker(final String... strings) {
+    return actual -> {
+      Object[] actualArray = actual == null || actual.isEmpty() ? null
+          : ((List) actual.get(0)).toArray();
+      CalciteAssert.assertArrayEqual("expected Elasticsearch query not found", strings,
+          actualArray);
     };
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvEnumerator.java
----------------------------------------------------------------------
diff --git a/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvEnumerator.java b/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvEnumerator.java
index afc3601..d42a979 100644
--- a/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvEnumerator.java
+++ b/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvEnumerator.java
@@ -331,13 +331,13 @@ class CsvEnumerator<E> implements Enumerator<E> {
     private final boolean stream;
 
     ArrayRowConverter(List<CsvFieldType> fieldTypes, int[] fields) {
-      this.fieldTypes = fieldTypes.toArray(new CsvFieldType[fieldTypes.size()]);
+      this.fieldTypes = fieldTypes.toArray(new CsvFieldType[0]);
       this.fields = fields;
       this.stream = false;
     }
 
     ArrayRowConverter(List<CsvFieldType> fieldTypes, int[] fields, boolean stream) {
-      this.fieldTypes = fieldTypes.toArray(new CsvFieldType[fieldTypes.size()]);
+      this.fieldTypes = fieldTypes.toArray(new CsvFieldType[0]);
       this.fields = fields;
       this.stream = stream;
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvSchema.java
----------------------------------------------------------------------
diff --git a/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvSchema.java b/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvSchema.java
index 7c971f5..8744966 100644
--- a/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvSchema.java
+++ b/example/csv/src/main/java/org/apache/calcite/adapter/csv/CsvSchema.java
@@ -24,7 +24,6 @@ import org.apache.calcite.util.Sources;
 import com.google.common.collect.ImmutableMap;
 
 import java.io.File;
-import java.io.FilenameFilter;
 import java.util.Map;
 
 /**
@@ -77,14 +76,11 @@ public class CsvSchema extends AbstractSchema {
     // Look for files in the directory ending in ".csv", ".csv.gz", ".json",
     // ".json.gz".
     final Source baseSource = Sources.of(directoryFile);
-    File[] files = directoryFile.listFiles(
-        new FilenameFilter() {
-          public boolean accept(File dir, String name) {
-            final String nameSansGz = trim(name, ".gz");
-            return nameSansGz.endsWith(".csv")
-                || nameSansGz.endsWith(".json");
-          }
-        });
+    File[] files = directoryFile.listFiles((dir, name) -> {
+      final String nameSansGz = trim(name, ".gz");
+      return nameSansGz.endsWith(".csv")
+          || nameSansGz.endsWith(".json");
+    });
     if (files == null) {
       System.out.println("directory " + directoryFile + " not found");
       files = new File[0];

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/example/csv/src/test/java/org/apache/calcite/test/CsvTest.java
----------------------------------------------------------------------
diff --git a/example/csv/src/test/java/org/apache/calcite/test/CsvTest.java b/example/csv/src/test/java/org/apache/calcite/test/CsvTest.java
index b739a9d..f3f5432 100644
--- a/example/csv/src/test/java/org/apache/calcite/test/CsvTest.java
+++ b/example/csv/src/test/java/org/apache/calcite/test/CsvTest.java
@@ -23,7 +23,6 @@ import org.apache.calcite.schema.Schema;
 import org.apache.calcite.sql2rel.SqlToRelConverter;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Ordering;
 
@@ -54,6 +53,7 @@ import java.util.Properties;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.Callable;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.anyOf;
 import static org.hamcrest.CoreMatchers.equalTo;
@@ -194,17 +194,14 @@ public class CsvTest {
     final String sql = "select empno * 3 as e3\n"
         + "from long_emps where empno = 100";
 
-    sql("bug", sql).checking(new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          assertThat(resultSet.next(), is(true));
-          Long o = (Long) resultSet.getObject(1);
-          assertThat(o, is(300L));
-          assertThat(resultSet.next(), is(false));
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    sql("bug", sql).checking(resultSet -> {
+      try {
+        assertThat(resultSet.next(), is(true));
+        Long o = (Long) resultSet.getObject(1);
+        assertThat(o, is(300L));
+        assertThat(resultSet.next(), is(false));
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     }).ok();
   }
@@ -313,60 +310,41 @@ public class CsvTest {
   }
 
   private Fluent sql(String model, String sql) {
-    return new Fluent(model, sql, output());
-  }
-
-  private Function<ResultSet, Void> output() {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          output(resultSet, System.out);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
-      }
-    };
+    return new Fluent(model, sql, this::output);
   }
 
   /** Returns a function that checks the contents of a result set against an
    * expected string. */
-  private static Function<ResultSet, Void> expect(final String... expected) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final List<String> lines = new ArrayList<>();
-          CsvTest.collect(lines, resultSet);
-          Assert.assertEquals(Arrays.asList(expected), lines);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
+  private static Consumer<ResultSet> expect(final String... expected) {
+    return resultSet -> {
+      try {
+        final List<String> lines = new ArrayList<>();
+        CsvTest.collect(lines, resultSet);
+        Assert.assertEquals(Arrays.asList(expected), lines);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
   /** Returns a function that checks the contents of a result set against an
    * expected string. */
-  private static Function<ResultSet, Void> expectUnordered(String... expected) {
+  private static Consumer<ResultSet> expectUnordered(String... expected) {
     final List<String> expectedLines =
         Ordering.natural().immutableSortedCopy(Arrays.asList(expected));
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final List<String> lines = new ArrayList<>();
-          CsvTest.collect(lines, resultSet);
-          Collections.sort(lines);
-          Assert.assertEquals(expectedLines, lines);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
+    return resultSet -> {
+      try {
+        final List<String> lines = new ArrayList<>();
+        CsvTest.collect(lines, resultSet);
+        Collections.sort(lines);
+        Assert.assertEquals(expectedLines, lines);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  private void checkSql(String sql, String model, Function<ResultSet, Void> fn)
+  private void checkSql(String sql, String model, Consumer<ResultSet> fn)
       throws SQLException {
     Connection connection = null;
     Statement statement = null;
@@ -378,7 +356,7 @@ public class CsvTest {
       final ResultSet resultSet =
           statement.executeQuery(
               sql);
-      fn.apply(resultSet);
+      fn.accept(resultSet);
     } finally {
       close(connection, statement);
     }
@@ -703,7 +681,7 @@ public class CsvTest {
       final Schema schema =
           CsvSchemaFactory.INSTANCE
               .create(calciteConnection.getRootSchema(), null,
-                  ImmutableMap.<String, Object>of("directory",
+                  ImmutableMap.of("directory",
                       resourcePath("sales"), "flavor", "scannable"));
       calciteConnection.getRootSchema().add("TEST", schema);
       final String sql = "select * from \"TEST\".\"DEPTS\" where \"NAME\" = ?";
@@ -712,8 +690,8 @@ public class CsvTest {
 
       statement2.setString(1, "Sales");
       final ResultSet resultSet1 = statement2.executeQuery();
-      Function<ResultSet, Void> expect = expect("DEPTNO=10; NAME=Sales");
-      expect.apply(resultSet1);
+      Consumer<ResultSet> expect = expect("DEPTNO=10; NAME=Sales");
+      expect.accept(resultSet1);
     }
   }
 
@@ -957,35 +935,38 @@ public class CsvTest {
 
   /** Creates a command that appends a line to the CSV file. */
   private Callable<Void> writeLine(final PrintWriter pw, final String line) {
-    return new Callable<Void>() {
-      @Override public Void call() throws Exception {
-        pw.println(line);
-        pw.flush();
-        return null;
-      }
+    return () -> {
+      pw.println(line);
+      pw.flush();
+      return null;
     };
   }
 
   /** Creates a command that sleeps. */
   private Callable<Void> sleep(final long millis) {
-    return new Callable<Void>() {
-      @Override public Void call() throws Exception {
-        Thread.sleep(millis);
-        return null;
-      }
+    return () -> {
+      Thread.sleep(millis);
+      return null;
     };
   }
 
   /** Creates a command that cancels a statement. */
   private Callable<Void> cancel(final Statement statement) {
-    return new Callable<Void>() {
-      @Override public Void call() throws Exception {
-        statement.cancel();
-        return null;
-      }
+    return () -> {
+      statement.cancel();
+      return null;
     };
   }
 
+  private Void output(ResultSet resultSet) {
+    try {
+      output(resultSet, System.out);
+    } catch (SQLException e) {
+      throw new RuntimeException(e);
+    }
+    return null;
+  }
+
   /** Receives commands on a queue and executes them on its own thread.
    * Call {@link #close} to terminate.
    *
@@ -1003,12 +984,7 @@ public class CsvTest {
     private Exception e;
 
     /** The poison pill command. */
-    final Callable<E> end =
-        new Callable<E>() {
-          public E call() {
-            return null;
-          }
-        };
+    final Callable<E> end = () -> null;
 
     public void run() {
       try {
@@ -1037,9 +1013,9 @@ public class CsvTest {
   private class Fluent {
     private final String model;
     private final String sql;
-    private final Function<ResultSet, Void> expect;
+    private final Consumer<ResultSet> expect;
 
-    Fluent(String model, String sql, Function<ResultSet, Void> expect) {
+    Fluent(String model, String sql, Consumer<ResultSet> expect) {
       this.model = model;
       this.sql = sql;
       this.expect = expect;
@@ -1056,7 +1032,7 @@ public class CsvTest {
     }
 
     /** Assigns a function to call to test whether output is correct. */
-    Fluent checking(Function<ResultSet, Void> expect) {
+    Fluent checking(Consumer<ResultSet> expect) {
       return new Fluent(model, sql, expect);
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/example/function/src/main/java/org/apache/calcite/example/maze/Maze.java
----------------------------------------------------------------------
diff --git a/example/function/src/main/java/org/apache/calcite/example/maze/Maze.java b/example/function/src/main/java/org/apache/calcite/example/maze/Maze.java
index eb738fa..d0ee05e 100644
--- a/example/function/src/main/java/org/apache/calcite/example/maze/Maze.java
+++ b/example/function/src/main/java/org/apache/calcite/example/maze/Maze.java
@@ -80,17 +80,11 @@ class Maze {
     final StringBuilder b2 = new StringBuilder();
     final CellContent cellContent;
     if (space) {
-      cellContent = new CellContent() {
-        public String get(int c) {
-          return "  ";
-        }
-      };
+      cellContent = c -> "  ";
     } else {
-      cellContent = new CellContent() {
-        public String get(int c) {
-          String s = region(c) + "";
-          return s.length() == 1 ? " " + s : s;
-        }
+      cellContent = c -> {
+        String s = region(c) + "";
+        return s.length() == 1 ? " " + s : s;
       };
     }
     for (int y = 0; y < height; y++) {
@@ -113,11 +107,7 @@ class Maze {
     if (solutionSet == null) {
       cellContent = CellContent.SPACE;
     } else {
-      cellContent = new CellContent() {
-        public String get(int c) {
-          return solutionSet.contains(c) ? "* " : "  ";
-        }
-      };
+      cellContent = c -> solutionSet.contains(c) ? "* " : "  ";
     }
     return new Enumerator<String>() {
       int i = -1;
@@ -352,11 +342,7 @@ class Maze {
   /** Callback to get what to print in a particular cell. Must be two characters
    * long, usually two spaces. */
   interface CellContent {
-    CellContent SPACE = new CellContent() {
-      public String get(int c) {
-        return "  ";
-      }
-    };
+    CellContent SPACE = c -> "  ";
 
     String get(int c);
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/example/function/src/main/java/org/apache/calcite/example/maze/MazeTable.java
----------------------------------------------------------------------
diff --git a/example/function/src/main/java/org/apache/calcite/example/maze/MazeTable.java b/example/function/src/main/java/org/apache/calcite/example/maze/MazeTable.java
index a08b366..767dbb0 100644
--- a/example/function/src/main/java/org/apache/calcite/example/maze/MazeTable.java
+++ b/example/function/src/main/java/org/apache/calcite/example/maze/MazeTable.java
@@ -21,7 +21,6 @@ import org.apache.calcite.linq4j.AbstractEnumerable;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Enumerator;
 import org.apache.calcite.linq4j.Linq4j;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.schema.ScannableTable;
@@ -103,11 +102,7 @@ public class MazeTable extends AbstractTable implements ScannableTable {
           solutionSet = null;
         }
         return Linq4j.transform(maze.enumerator(solutionSet),
-            new Function1<String, Object[]>() {
-              public Object[] apply(String s) {
-                return new Object[] {s};
-              }
-            });
+            s -> new Object[] {s});
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/file/src/main/java/org/apache/calcite/adapter/file/FileRowConverter.java
----------------------------------------------------------------------
diff --git a/file/src/main/java/org/apache/calcite/adapter/file/FileRowConverter.java b/file/src/main/java/org/apache/calcite/adapter/file/FileRowConverter.java
index 3a635e4..3f19e4b 100644
--- a/file/src/main/java/org/apache/calcite/adapter/file/FileRowConverter.java
+++ b/file/src/main/java/org/apache/calcite/adapter/file/FileRowConverter.java
@@ -21,8 +21,6 @@ import org.apache.calcite.avatica.util.DateTimeUtils;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Joiner;
-
 import com.joestelmach.natty.DateGroup;
 import com.joestelmach.natty.Parser;
 
@@ -31,7 +29,6 @@ import org.jsoup.select.Elements;
 
 import java.text.NumberFormat;
 import java.text.ParseException;
-
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -42,7 +39,6 @@ import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-
 /**
  * FileRowConverter.
  */
@@ -267,7 +263,7 @@ class FileRowConverter {
         }
       }
 
-      String cellString = Joiner.on(" ").join(cellText).trim();
+      String cellString = String.join(" ", cellText).trim();
 
       // replace
       if (this.replacePattern != null) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/file/src/main/java/org/apache/calcite/adapter/file/FileSchema.java
----------------------------------------------------------------------
diff --git a/file/src/main/java/org/apache/calcite/adapter/file/FileSchema.java b/file/src/main/java/org/apache/calcite/adapter/file/FileSchema.java
index 97c5cb4..29f3b9a 100644
--- a/file/src/main/java/org/apache/calcite/adapter/file/FileSchema.java
+++ b/file/src/main/java/org/apache/calcite/adapter/file/FileSchema.java
@@ -29,7 +29,6 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
 import java.io.File;
-import java.io.FilenameFilter;
 import java.net.MalformedURLException;
 import java.util.List;
 import java.util.Map;
@@ -89,14 +88,11 @@ class FileSchema extends AbstractSchema {
     // Look for files in the directory ending in ".csv", ".csv.gz", ".json",
     // ".json.gz".
     final Source baseSource = Sources.of(baseDirectory);
-    File[] files = baseDirectory.listFiles(
-        new FilenameFilter() {
-          public boolean accept(File dir, String name) {
-            final String nameSansGz = trim(name, ".gz");
-            return nameSansGz.endsWith(".csv")
-                || nameSansGz.endsWith(".json");
-          }
-        });
+    File[] files = baseDirectory.listFiles((dir, name) -> {
+      final String nameSansGz = trim(name, ".gz");
+      return nameSansGz.endsWith(".csv")
+          || nameSansGz.endsWith(".json");
+    });
     if (files == null) {
       System.out.println("directory " + baseDirectory + " not found");
       files = new File[0];

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/file/src/test/java/org/apache/calcite/adapter/file/SqlTest.java
----------------------------------------------------------------------
diff --git a/file/src/test/java/org/apache/calcite/adapter/file/SqlTest.java b/file/src/test/java/org/apache/calcite/adapter/file/SqlTest.java
index 8d31770..3437b69 100644
--- a/file/src/test/java/org/apache/calcite/adapter/file/SqlTest.java
+++ b/file/src/test/java/org/apache/calcite/adapter/file/SqlTest.java
@@ -18,7 +18,6 @@ package org.apache.calcite.adapter.file;
 
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Ordering;
 
 import org.junit.Assert;
@@ -37,6 +36,7 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Properties;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.assertEquals;
@@ -50,34 +50,30 @@ public class SqlTest {
   // helper functions
 
   private Fluent sql(String model, String sql) {
-    return new Fluent(model, sql, new Function<ResultSet, Void>() {
-      public Void apply(ResultSet input) {
-        throw new AssertionError();
-      }
+    return new Fluent(model, sql, input -> {
+      throw new AssertionError();
     });
   }
 
-  private Function<ResultSet, Void> expect(String... expectedLines) {
+  private static Function<ResultSet, Void> expect(String... expectedLines) {
     final StringBuilder b = new StringBuilder();
     for (String s : expectedLines) {
       b.append(s).append('\n');
     }
     final String expected = b.toString();
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          String actual = SqlTest.toString(resultSet);
-          if (!expected.equals(actual)) {
-            System.out.println("Assertion failure:");
-            System.out.println("\tExpected: '" + expected + "'");
-            System.out.println("\tActual: '" + actual + "'");
-          }
-          assertEquals(expected, actual);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+    return resultSet -> {
+      try {
+        String actual = toString(resultSet);
+        if (!expected.equals(actual)) {
+          System.out.println("Assertion failure:");
+          System.out.println("\tExpected: '" + expected + "'");
+          System.out.println("\tActual: '" + actual + "'");
         }
-        return null;
+        assertEquals(expected, actual);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
+      return null;
     };
   }
 
@@ -86,18 +82,16 @@ public class SqlTest {
   private static Function<ResultSet, Void> expectUnordered(String... expected) {
     final List<String> expectedLines =
         Ordering.natural().immutableSortedCopy(Arrays.asList(expected));
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final List<String> lines = new ArrayList<>();
-          SqlTest.collect(lines, resultSet);
-          Collections.sort(lines);
-          Assert.assertEquals(expectedLines, lines);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
+    return resultSet -> {
+      try {
+        final List<String> lines = new ArrayList<>();
+        SqlTest.collect(lines, resultSet);
+        Collections.sort(lines);
+        Assert.assertEquals(expectedLines, lines);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
+      return null;
     };
   }
 
@@ -259,21 +253,19 @@ public class SqlTest {
    * "EmptyFileHasNoColumns". */
   @Test public void testCsvSalesEmpty() throws SQLException {
     final String sql = "select * from sales.\"EMPTY\"";
-    checkSql(sql, "sales-csv", new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          assertThat(resultSet.getMetaData().getColumnCount(), is(1));
-          assertThat(resultSet.getMetaData().getColumnName(1),
-              is("EmptyFileHasNoColumns"));
-          assertThat(resultSet.getMetaData().getColumnType(1),
-              is(Types.BOOLEAN));
-          String actual = SqlTest.toString(resultSet);
-          assertThat(actual, is(""));
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
+    checkSql(sql, "sales-csv", resultSet -> {
+      try {
+        assertThat(resultSet.getMetaData().getColumnCount(), is(1));
+        assertThat(resultSet.getMetaData().getColumnName(1),
+            is("EmptyFileHasNoColumns"));
+        assertThat(resultSet.getMetaData().getColumnType(1),
+            is(Types.BOOLEAN));
+        String actual = toString(resultSet);
+        assertThat(actual, is(""));
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
+      return null;
     });
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeRules.java
----------------------------------------------------------------------
diff --git a/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeRules.java b/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeRules.java
index bfac3f0..0e006eb 100644
--- a/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeRules.java
+++ b/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeRules.java
@@ -39,11 +39,10 @@ import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 
-import com.google.common.base.Predicate;
-
 import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.function.Predicate;
 
 /**
  * Rules and relational operators for {@link GeodeRel#CONVENTION} calling convention.
@@ -208,15 +207,11 @@ public class GeodeRules {
 
     private static final GeodeSortLimitRule INSTANCE =
         new GeodeSortLimitRule(
-          new Predicate<Sort>() {
-            public boolean apply(Sort input) {
-              // OQL doesn't support for offsets (e.g. LIMIT 10 OFFSET 500)
-              return input.offset == null;
-            }
-          });
+            // OQL doesn't support for offsets (e.g. LIMIT 10 OFFSET 500)
+            sort -> sort.offset == null);
 
     GeodeSortLimitRule(Predicate<Sort> predicate) {
-      super(operand(Sort.class, null, predicate, any()), "GeodeSortLimitRule");
+      super(operandJ(Sort.class, null, predicate, any()), "GeodeSortLimitRule");
     }
 
     @Override public void onMatch(RelOptRuleCall call) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeSchemaFactory.java
----------------------------------------------------------------------
diff --git a/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeSchemaFactory.java b/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeSchemaFactory.java
index 8052925..0348a0d 100644
--- a/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeSchemaFactory.java
+++ b/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeSchemaFactory.java
@@ -57,7 +57,7 @@ public class GeodeSchemaFactory implements SchemaFactory {
     }
 
     if (allowSpatialFunctions) {
-      ModelHandler.addFunctions(parentSchema, null, ImmutableList.<String>of(),
+      ModelHandler.addFunctions(parentSchema, null, ImmutableList.of(),
           GeoFunctions.class.getName(), "*", true);
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeToEnumerableConverter.java
----------------------------------------------------------------------
diff --git a/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeToEnumerableConverter.java b/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeToEnumerableConverter.java
index 5f85907..4b44573 100644
--- a/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeToEnumerableConverter.java
+++ b/geode/src/main/java/org/apache/calcite/adapter/geode/rel/GeodeToEnumerableConverter.java
@@ -39,7 +39,6 @@ import org.apache.calcite.runtime.Hook;
 import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.lang.reflect.Method;
@@ -152,12 +151,7 @@ public class GeodeToEnumerableConverter extends ConverterImpl implements Enumera
    * {@code {ConstantExpression("x"), ConstantExpression("y")}}.
    */
   private static <T> List<Expression> constantList(List<T> values) {
-    return Lists.transform(values,
-        new Function<T, Expression>() {
-          public Expression apply(T a0) {
-            return Expressions.constant(a0);
-          }
-        });
+    return Lists.transform(values, Expressions::constant);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/geode/src/main/java/org/apache/calcite/adapter/geode/util/JavaTypeFactoryExtImpl.java
----------------------------------------------------------------------
diff --git a/geode/src/main/java/org/apache/calcite/adapter/geode/util/JavaTypeFactoryExtImpl.java b/geode/src/main/java/org/apache/calcite/adapter/geode/util/JavaTypeFactoryExtImpl.java
index ca17342..90f57d4 100644
--- a/geode/src/main/java/org/apache/calcite/adapter/geode/util/JavaTypeFactoryExtImpl.java
+++ b/geode/src/main/java/org/apache/calcite/adapter/geode/util/JavaTypeFactoryExtImpl.java
@@ -33,7 +33,6 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
-
 /**
  * Implementation of {@link JavaTypeFactory}.
  *

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/geode/src/test/java/org/apache/calcite/adapter/geode/rel/BaseGeodeAdapterIT.java
----------------------------------------------------------------------
diff --git a/geode/src/test/java/org/apache/calcite/adapter/geode/rel/BaseGeodeAdapterIT.java b/geode/src/test/java/org/apache/calcite/adapter/geode/rel/BaseGeodeAdapterIT.java
index cdec337..5e99119 100644
--- a/geode/src/test/java/org/apache/calcite/adapter/geode/rel/BaseGeodeAdapterIT.java
+++ b/geode/src/test/java/org/apache/calcite/adapter/geode/rel/BaseGeodeAdapterIT.java
@@ -43,17 +43,15 @@ public class BaseGeodeAdapterIT {
    * expected string.
    */
   private static Function1<ResultSet, Void> expect(final String... expected) {
-    return new Function1<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final List<String> lines = new ArrayList<>();
-          BaseGeodeAdapterIT.collect(lines, resultSet);
-          Assert.assertEquals(Arrays.asList(expected), lines);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
+    return resultSet -> {
+      try {
+        final List<String> lines = new ArrayList<>();
+        BaseGeodeAdapterIT.collect(lines, resultSet);
+        Assert.assertEquals(Arrays.asList(expected), lines);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
+      return null;
     };
   }
 
@@ -84,15 +82,13 @@ public class BaseGeodeAdapterIT {
   }
 
   protected Function1<ResultSet, Void> output() {
-    return new Function1<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          output(resultSet, System.out);
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
-        return null;
+    return resultSet -> {
+      try {
+        output(resultSet, System.out);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
+      return null;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/DefaultQueryable.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/DefaultQueryable.java b/linq4j/src/main/java/org/apache/calcite/linq4j/DefaultQueryable.java
index 82d2c9f..7e8b5dd 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/DefaultQueryable.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/DefaultQueryable.java
@@ -51,7 +51,7 @@ abstract class DefaultQueryable<T> extends DefaultEnumerable<T>
    * Creates a DefaultQueryable using a factory that records events.
    */
   protected DefaultQueryable() {
-    this(QueryableRecorder.<T>instance());
+    this(QueryableRecorder.instance());
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java b/linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
index 646d95b..9b3dbba 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/EnumerableDefaults.java
@@ -35,7 +35,6 @@ import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.linq4j.function.Predicate2;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
 import java.math.BigDecimal;
@@ -370,7 +369,7 @@ public abstract class EnumerableDefaults {
    * sequence.
    */
   public static <TSource> int count(Enumerable<TSource> enumerable) {
-    return (int) longCount(enumerable, Functions.<TSource>truePredicate1());
+    return (int) longCount(enumerable, Functions.truePredicate1());
   }
 
   /**
@@ -402,36 +401,31 @@ public abstract class EnumerableDefaults {
       TSource value) {
     try (Enumerator<TSource> os = enumerable.enumerator()) {
       if (os.moveNext()) {
-        return Linq4j.asEnumerable(
-            new Iterable<TSource>() {
-              public Iterator<TSource> iterator() {
-                return new Iterator<TSource>() {
+        return Linq4j.asEnumerable(() -> new Iterator<TSource>() {
 
-                  private boolean nonFirst;
+          private boolean nonFirst;
 
-                  private Iterator<TSource> rest;
+          private Iterator<TSource> rest;
 
-                  public boolean hasNext() {
-                    return !nonFirst || rest.hasNext();
-                  }
+          public boolean hasNext() {
+            return !nonFirst || rest.hasNext();
+          }
 
-                  public TSource next() {
-                    if (nonFirst) {
-                      return rest.next();
-                    } else {
-                      final TSource first = os.current();
-                      nonFirst = true;
-                      rest = Linq4j.enumeratorIterator(os);
-                      return first;
-                    }
-                  }
+          public TSource next() {
+            if (nonFirst) {
+              return rest.next();
+            } else {
+              final TSource first = os.current();
+              nonFirst = true;
+              rest = Linq4j.enumeratorIterator(os);
+              return first;
+            }
+          }
 
-                  public void remove() {
-                    throw new UnsupportedOperationException("remove");
-                  }
-                };
-              }
-            });
+          public void remove() {
+            throw new UnsupportedOperationException("remove");
+          }
+        });
       } else {
         return Linq4j.singletonEnumerable(value);
       }
@@ -683,11 +677,7 @@ public abstract class EnumerableDefaults {
       Enumerable<TSource> enumerable, Function1<TSource, TKey> keySelector,
       final Function2<TKey, Enumerable<TSource>, TResult> resultSelector) {
     return enumerable.toLookup(keySelector)
-        .select(new Function1<Grouping<TKey, TSource>, TResult>() {
-          public TResult apply(Grouping<TKey, TSource> group) {
-            return resultSelector.apply(group.getKey(), group);
-          }
-        });
+        .select(group -> resultSelector.apply(group.getKey(), group));
   }
 
   /**
@@ -701,11 +691,7 @@ public abstract class EnumerableDefaults {
       final Function2<TKey, Enumerable<TSource>, TResult> resultSelector,
       EqualityComparer<TKey> comparer) {
     return enumerable.toLookup(keySelector, comparer)
-        .select(new Function1<Grouping<TKey, TSource>, TResult>() {
-          public TResult apply(Grouping<TKey, TSource> group) {
-            return resultSelector.apply(group.getKey(), group);
-          }
-        });
+        .select(group -> resultSelector.apply(group.getKey(), group));
   }
 
   /**
@@ -719,11 +705,7 @@ public abstract class EnumerableDefaults {
       Function1<TSource, TElement> elementSelector,
       final Function2<TKey, Enumerable<TElement>, TResult> resultSelector) {
     return enumerable.toLookup(keySelector, elementSelector)
-        .select(new Function1<Grouping<TKey, TElement>, TResult>() {
-          public TResult apply(Grouping<TKey, TElement> group) {
-            return resultSelector.apply(group.getKey(), group);
-          }
-        });
+        .select(group -> resultSelector.apply(group.getKey(), group));
   }
 
   /**
@@ -739,11 +721,7 @@ public abstract class EnumerableDefaults {
       final Function2<TKey, Enumerable<TElement>, TResult> resultSelector,
       EqualityComparer<TKey> comparer) {
     return enumerable.toLookup(keySelector, elementSelector, comparer)
-        .select(new Function1<Grouping<TKey, TElement>, TResult>() {
-          public TResult apply(Grouping<TKey, TElement> group) {
-            return resultSelector.apply(group.getKey(), group);
-          }
-        });
+        .select(group -> resultSelector.apply(group.getKey(), group));
   }
 
   /**
@@ -907,7 +885,7 @@ public abstract class EnumerableDefaults {
             final Map.Entry<TKey, TSource> entry = entries.current();
             final Enumerable<TInner> inners = innerLookup.get(entry.getKey());
             return resultSelector.apply(entry.getValue(),
-                inners == null ? Linq4j.<TInner>emptyEnumerable() : inners);
+                inners == null ? Linq4j.emptyEnumerable() : inners);
           }
 
           public boolean moveNext() {
@@ -948,7 +926,7 @@ public abstract class EnumerableDefaults {
             final Map.Entry<TKey, TSource> entry = entries.current();
             final Enumerable<TInner> inners = innerLookup.get(entry.getKey());
             return resultSelector.apply(entry.getValue(),
-                inners == null ? Linq4j.<TInner>emptyEnumerable() : inners);
+                inners == null ? Linq4j.emptyEnumerable() : inners);
           }
 
           public boolean moveNext() {
@@ -1327,13 +1305,10 @@ public abstract class EnumerableDefaults {
                 ? inner.select(innerKeySelector).distinct()
                 : inner.select(innerKeySelector).distinct(comparer);
 
-        return EnumerableDefaults.where(outer.enumerator(),
-            new Predicate1<TSource>() {
-              public boolean apply(TSource v0) {
-                final TKey key = outerKeySelector.apply(v0);
-                return innerLookup.contains(key);
-              }
-            });
+        return EnumerableDefaults.where(outer.enumerator(), v0 -> {
+          final TKey key = outerKeySelector.apply(v0);
+          return innerLookup.contains(key);
+        });
       }
     };
   }
@@ -1348,7 +1323,7 @@ public abstract class EnumerableDefaults {
       final boolean generateNullsOnLeft,
       final boolean generateNullsOnRight) {
     // Building the result as a list is easy but hogs memory. We should iterate.
-    final List<TResult> result = Lists.newArrayList();
+    final List<TResult> result = new ArrayList<>();
     final Enumerator<TSource> lefts = outer.enumerator();
     final List<TInner> rightList = inner.toList();
     final Set<TInner> rightUnmatched;
@@ -1516,7 +1491,7 @@ public abstract class EnumerableDefaults {
    * of elements in a sequence.
    */
   public static <TSource> long longCount(Enumerable<TSource> source) {
-    return longCount(source, Functions.<TSource>truePredicate1());
+    return longCount(source, Functions.truePredicate1());
   }
 
   /**
@@ -1675,13 +1650,13 @@ public abstract class EnumerableDefaults {
   @SuppressWarnings("unchecked")
   private static <TSource extends Comparable<TSource>> Function2<TSource, TSource, TSource>
       minFunction() {
-    return (Function2<TSource, TSource, TSource>) Extensions.COMPARABLE_MIN;
+    return (Function2<TSource, TSource, TSource>) (Function2) Extensions.COMPARABLE_MIN;
   }
 
   @SuppressWarnings("unchecked")
   private static <TSource extends Comparable<TSource>> Function2<TSource, TSource, TSource>
       maxFunction() {
-    return (Function2<TSource, TSource, TSource>) Extensions.COMPARABLE_MAX;
+    return (Function2<TSource, TSource, TSource>) (Function2) Extensions.COMPARABLE_MAX;
   }
 
   /**
@@ -1810,7 +1785,7 @@ public abstract class EnumerableDefaults {
       Enumerable<TSource> enumerable, Class<TResult> clazz) {
     //noinspection unchecked
     return (Enumerable) where(enumerable,
-        Functions.<TSource, TResult>ofTypePredicate(clazz));
+        Functions.ofTypePredicate(clazz));
   }
 
   /**
@@ -1834,7 +1809,7 @@ public abstract class EnumerableDefaults {
     // Otherwise there will be a ClassCastException while retrieving.
     final Map<TKey, List<TSource>> map = new TreeMap<>(comparator);
     LookupImpl<TKey, TSource> lookup = toLookup_(map, source, keySelector,
-        Functions.<TSource>identitySelector());
+        Functions.identitySelector());
     return lookup.valuesEnumerable();
   }
 
@@ -1844,7 +1819,7 @@ public abstract class EnumerableDefaults {
    */
   public static <TSource, TKey extends Comparable> Enumerable<TSource> orderByDescending(
       Enumerable<TSource> source, Function1<TSource, TKey> keySelector) {
-    return orderBy(source, keySelector, Collections.<TKey>reverseOrder());
+    return orderBy(source, keySelector, Collections.reverseOrder());
   }
 
   /**
@@ -2307,11 +2282,9 @@ public abstract class EnumerableDefaults {
    */
   public static <TSource> Enumerable<TSource> skip(Enumerable<TSource> source,
       final int count) {
-    return skipWhile(source, new Predicate2<TSource, Integer>() {
-      public boolean apply(TSource v1, Integer v2) {
-        // Count is 1-based
-        return v2 < count;
-      }
+    return skipWhile(source, (v1, v2) -> {
+      // Count is 1-based
+      return v2 < count;
     });
   }
 
@@ -2323,7 +2296,7 @@ public abstract class EnumerableDefaults {
   public static <TSource> Enumerable<TSource> skipWhile(
       Enumerable<TSource> source, Predicate1<TSource> predicate) {
     return skipWhile(source,
-        Functions.<TSource, Integer>toPredicate2(predicate));
+        Functions.toPredicate2(predicate));
   }
 
   /**
@@ -2451,11 +2424,9 @@ public abstract class EnumerableDefaults {
   public static <TSource> Enumerable<TSource> take(Enumerable<TSource> source,
       final int count) {
     return takeWhile(
-        source, new Predicate2<TSource, Integer>() {
-          public boolean apply(TSource v1, Integer v2) {
-            // Count is 1-based
-            return v2 < count;
-          }
+        source, (v1, v2) -> {
+          // Count is 1-based
+          return v2 < count;
         });
   }
 
@@ -2466,11 +2437,9 @@ public abstract class EnumerableDefaults {
   public static <TSource> Enumerable<TSource> take(Enumerable<TSource> source,
       final long count) {
     return takeWhileLong(
-        source, new Predicate2<TSource, Long>() {
-          public boolean apply(TSource v1, Long v2) {
-            // Count is 1-based
-            return v2 < count;
-          }
+        source, (v1, v2) -> {
+          // Count is 1-based
+          return v2 < count;
         });
   }
 
@@ -2481,7 +2450,7 @@ public abstract class EnumerableDefaults {
   public static <TSource> Enumerable<TSource> takeWhile(
       Enumerable<TSource> source, final Predicate1<TSource> predicate) {
     return takeWhile(source,
-        Functions.<TSource, Integer>toPredicate2(predicate));
+        Functions.toPredicate2(predicate));
   }
 
   /**
@@ -2531,7 +2500,7 @@ public abstract class EnumerableDefaults {
   public static <TSource, TKey extends Comparable<TKey>> OrderedEnumerable<TSource> thenBy(
       OrderedEnumerable<TSource> source, Function1<TSource, TKey> keySelector) {
     return createOrderedEnumerable(source, keySelector,
-        Extensions.<TKey>comparableComparator(), false);
+        Extensions.comparableComparator(), false);
   }
 
   /**
@@ -2552,7 +2521,7 @@ public abstract class EnumerableDefaults {
       OrderedEnumerable<TSource> thenByDescending(
       OrderedEnumerable<TSource> source, Function1<TSource, TKey> keySelector) {
     return createOrderedEnumerable(source, keySelector,
-        Extensions.<TKey>comparableComparator(), true);
+        Extensions.comparableComparator(), true);
   }
 
   /**
@@ -2574,7 +2543,7 @@ public abstract class EnumerableDefaults {
    */
   public static <TSource, TKey> Map<TKey, TSource> toMap(
       Enumerable<TSource> source, Function1<TSource, TKey> keySelector) {
-    return toMap(source, keySelector, Functions.<TSource>identitySelector());
+    return toMap(source, keySelector, Functions.identitySelector());
   }
 
   /**
@@ -2585,7 +2554,7 @@ public abstract class EnumerableDefaults {
   public static <TSource, TKey> Map<TKey, TSource> toMap(
       Enumerable<TSource> source, Function1<TSource, TKey> keySelector,
       EqualityComparer<TKey> comparer) {
-    return toMap(source, keySelector, Functions.<TSource>identitySelector(), comparer);
+    return toMap(source, keySelector, Functions.identitySelector(), comparer);
   }
 
   /**
@@ -2656,7 +2625,7 @@ public abstract class EnumerableDefaults {
    */
   public static <TSource, TKey> Lookup<TKey, TSource> toLookup(
       Enumerable<TSource> source, Function1<TSource, TKey> keySelector) {
-    return toLookup(source, keySelector, Functions.<TSource>identitySelector());
+    return toLookup(source, keySelector, Functions.identitySelector());
   }
 
   /**
@@ -2668,7 +2637,7 @@ public abstract class EnumerableDefaults {
       Enumerable<TSource> source, Function1<TSource, TKey> keySelector,
       EqualityComparer<TKey> comparer) {
     return toLookup(
-        source, keySelector, Functions.<TSource>identitySelector(), comparer);
+        source, keySelector, Functions.identitySelector(), comparer);
   }
 
   /**
@@ -2762,20 +2731,12 @@ public abstract class EnumerableDefaults {
   }
 
   private static <TSource> Function1<Wrapped<TSource>, TSource> unwrapper() {
-    return new Function1<Wrapped<TSource>, TSource>() {
-      public TSource apply(Wrapped<TSource> a0) {
-        return a0.element;
-      }
-    };
+    return a0 -> a0.element;
   }
 
   private static <TSource> Function1<TSource, Wrapped<TSource>> wrapperFor(
       final EqualityComparer<TSource> comparer) {
-    return new Function1<TSource, Wrapped<TSource>>() {
-      public Wrapped<TSource> apply(TSource a0) {
-        return Wrapped.upAs(comparer, a0);
-      }
-    };
+    return a0 -> Wrapped.upAs(comparer, a0);
   }
 
   /**
@@ -3324,8 +3285,8 @@ public abstract class EnumerableDefaults {
         rights.add(right);
       }
       cartesians = Linq4j.product(
-          ImmutableList.of(Linq4j.<Object>enumerator(lefts),
-              Linq4j.<Object>enumerator(rights)));
+          ImmutableList.of(Linq4j.enumerator(lefts),
+              Linq4j.enumerator(rights)));
       return true;
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/Extensions.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/Extensions.java b/linq4j/src/main/java/org/apache/calcite/linq4j/Extensions.java
index c72e88c..7f288da 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/Extensions.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/Extensions.java
@@ -111,109 +111,51 @@ public abstract class Extensions {
   private Extensions() {}
 
   static final Function2<BigDecimal, BigDecimal, BigDecimal> BIG_DECIMAL_SUM =
-      new Function2<BigDecimal, BigDecimal, BigDecimal>() {
-        public BigDecimal apply(BigDecimal v1, BigDecimal v2) {
-          return v1.add(v2);
-        }
-      };
+      BigDecimal::add;
 
   static final Function2<Float, Float, Float> FLOAT_SUM =
-      new Function2<Float, Float, Float>() {
-        public Float apply(Float v1, Float v2) {
-          return v1 + v2;
-        }
-      };
+      (v1, v2) -> v1 + v2;
 
   static final Function2<Double, Double, Double> DOUBLE_SUM =
-      new Function2<Double, Double, Double>() {
-        public Double apply(Double v1, Double v2) {
-          return v1 + v2;
-        }
-      };
+      (v1, v2) -> v1 + v2;
 
   static final Function2<Integer, Integer, Integer> INTEGER_SUM =
-      new Function2<Integer, Integer, Integer>() {
-        public Integer apply(Integer v1, Integer v2) {
-          return v1 + v2;
-        }
-      };
+      (v1, v2) -> v1 + v2;
 
   static final Function2<Long, Long, Long> LONG_SUM =
-      new Function2<Long, Long, Long>() {
-        public Long apply(Long v1, Long v2) {
-          return v1 + v2;
-        }
-      };
-
-  static final Function2 COMPARABLE_MIN =
-      new Function2<Comparable, Comparable, Comparable>() {
-        public Comparable apply(Comparable v1, Comparable v2) {
-          return v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
-        }
-      };
-
-  static final Function2 COMPARABLE_MAX =
-      new Function2<Comparable, Comparable, Comparable>() {
-        public Comparable apply(Comparable v1, Comparable v2) {
-          return v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 + v2;
+
+  @SuppressWarnings("unchecked")
+  static final Function2<Comparable, Comparable, Comparable> COMPARABLE_MIN =
+      (v1, v2) -> v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
+
+  @SuppressWarnings("unchecked")
+  static final Function2<Comparable, Comparable, Comparable> COMPARABLE_MAX =
+      (v1, v2) -> v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
 
   static final Function2<Float, Float, Float> FLOAT_MIN =
-      new Function2<Float, Float, Float>() {
-        public Float apply(Float v1, Float v2) {
-          return v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
 
   static final Function2<Float, Float, Float> FLOAT_MAX =
-      new Function2<Float, Float, Float>() {
-        public Float apply(Float v1, Float v2) {
-          return v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
 
   static final Function2<Double, Double, Double> DOUBLE_MIN =
-      new Function2<Double, Double, Double>() {
-        public Double apply(Double v1, Double v2) {
-          return v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
 
   static final Function2<Double, Double, Double> DOUBLE_MAX =
-      new Function2<Double, Double, Double>() {
-        public Double apply(Double v1, Double v2) {
-          return v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
 
   static final Function2<Integer, Integer, Integer> INTEGER_MIN =
-      new Function2<Integer, Integer, Integer>() {
-        public Integer apply(Integer v1, Integer v2) {
-          return v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
 
   static final Function2<Integer, Integer, Integer> INTEGER_MAX =
-      new Function2<Integer, Integer, Integer>() {
-        public Integer apply(Integer v1, Integer v2) {
-          return v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
 
   static final Function2<Long, Long, Long> LONG_MIN =
-      new Function2<Long, Long, Long>() {
-        public Long apply(Long v1, Long v2) {
-          return v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) > 0 ? v2 : v1;
 
   static final Function2<Long, Long, Long> LONG_MAX =
-      new Function2<Long, Long, Long>() {
-        public Long apply(Long v1, Long v2) {
-          return v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
-        }
-      };
+      (v1, v2) -> v1 == null || v1.compareTo(v2) < 0 ? v2 : v1;
 
   // flags a piece of code we're yet to implement
   public static RuntimeException todo() {
@@ -228,17 +170,8 @@ public abstract class Extensions {
             Linq4j.DEFAULT_PROVIDER, (Class) Object.class, null, source);
   }
 
-  private static final Comparator<Comparable> COMPARABLE_COMPARATOR =
-      new Comparator<Comparable>() {
-        public int compare(Comparable o1, Comparable o2) {
-          //noinspection unchecked
-          return o1.compareTo(o2);
-        }
-      };
-
   static <T extends Comparable<T>> Comparator<T> comparableComparator() {
-    //noinspection unchecked
-    return (Comparator<T>) (Comparator) COMPARABLE_COMPARATOR;
+    return Comparable::compareTo;
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/GroupingImpl.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/GroupingImpl.java b/linq4j/src/main/java/org/apache/calcite/linq4j/GroupingImpl.java
index 65af763..15aaf1f 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/GroupingImpl.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/GroupingImpl.java
@@ -16,10 +16,9 @@
  */
 package org.apache.calcite.linq4j;
 
-import com.google.common.base.Preconditions;
-
 import java.util.Collection;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Implementation of {@link Grouping}.
@@ -33,8 +32,8 @@ class GroupingImpl<K, V> extends AbstractEnumerable<V>
   private final Collection<V> values;
 
   GroupingImpl(K key, Collection<V> values) {
-    this.key = Preconditions.checkNotNull(key);
-    this.values = Preconditions.checkNotNull(values);
+    this.key = Objects.requireNonNull(key);
+    this.values = Objects.requireNonNull(values);
   }
 
   @Override public String toString() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java b/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java
index 5e58a44..11fc069 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java
@@ -18,8 +18,6 @@ package org.apache.calcite.linq4j;
 
 import org.apache.calcite.linq4j.function.Function1;
 
-import com.google.common.collect.Lists;
-
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -390,15 +388,13 @@ public abstract class Linq4j {
   /** Returns the cartesian product of an iterable of iterables. */
   public static <T> Iterable<List<T>> product(
       final Iterable<? extends Iterable<T>> iterables) {
-    return new Iterable<List<T>>() {
-      public Iterator<List<T>> iterator() {
-        final List<Enumerator<T>> enumerators = Lists.newArrayList();
-        for (Iterable<T> iterable : iterables) {
-          enumerators.add(iterableEnumerator(iterable));
-        }
-        return enumeratorIterator(
-            new CartesianProductListEnumerator<>(enumerators));
+    return () -> {
+      final List<Enumerator<T>> enumerators = new ArrayList<>();
+      for (Iterable<T> iterable : iterables) {
+        enumerators.add(iterableEnumerator(iterable));
       }
+      return enumeratorIterator(
+          new CartesianProductListEnumerator<>(enumerators));
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/Ord.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/Ord.java b/linq4j/src/main/java/org/apache/calcite/linq4j/Ord.java
index c0e4192..4f5192f 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/Ord.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/Ord.java
@@ -52,11 +52,7 @@ public class Ord<E> implements Map.Entry<Integer, E> {
    * Creates an iterable of {@code Ord}s over an iterable.
    */
   public static <E> Iterable<Ord<E>> zip(final Iterable<? extends E> iterable) {
-    return new Iterable<Ord<E>>() {
-      public Iterator<Ord<E>> iterator() {
-        return zip(iterable.iterator());
-      }
-    };
+    return () -> zip(iterable.iterator());
   }
 
   /**
@@ -114,23 +110,19 @@ public class Ord<E> implements Map.Entry<Integer, E> {
    */
   public static <E> Iterable<Ord<E>> reverse(Iterable<? extends E> elements) {
     final ImmutableList<E> elementList = ImmutableList.copyOf(elements);
-    return new Iterable<Ord<E>>() {
-      public Iterator<Ord<E>> iterator() {
-        return new Iterator<Ord<E>>() {
-          int i = elementList.size() - 1;
-
-          public boolean hasNext() {
-            return i >= 0;
-          }
-
-          public Ord<E> next() {
-            return Ord.of(i, elementList.get(i--));
-          }
-
-          public void remove() {
-            throw new UnsupportedOperationException("remove");
-          }
-        };
+    return () -> new Iterator<Ord<E>>() {
+      int i = elementList.size() - 1;
+
+      public boolean hasNext() {
+        return i >= 0;
+      }
+
+      public Ord<E> next() {
+        return Ord.of(i, elementList.get(i--));
+      }
+
+      public void remove() {
+        throw new UnsupportedOperationException("remove");
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableDefaults.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableDefaults.java b/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableDefaults.java
index 328e9e6..8a21331 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableDefaults.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableDefaults.java
@@ -897,7 +897,7 @@ public abstract class QueryableDefaults {
       FunctionExpression<Predicate1<T>> predicate) {
     return skipWhileN(source,
         Expressions.lambda(
-            Functions.<T, Integer>toPredicate2(predicate.getFunction())));
+            Functions.toPredicate2(predicate.getFunction())));
   }
 
   /**
@@ -1033,7 +1033,7 @@ public abstract class QueryableDefaults {
       FunctionExpression<Predicate1<T>> predicate) {
     return takeWhileN(source,
         Expressions.lambda(
-            Functions.<T, Integer>toPredicate2(predicate.getFunction())));
+            Functions.toPredicate2(predicate.getFunction())));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableRecorder.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableRecorder.java b/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableRecorder.java
index 065962b..513a42c 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableRecorder.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/QueryableRecorder.java
@@ -71,7 +71,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.aggregate(source, seed, func);
       }
-    }.<TAccumulate>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public <TAccumulate, TResult> TResult aggregate(final Queryable<T> source,
@@ -82,7 +82,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.aggregate(source, seed, func, selector);
       }
-    }.<TResult>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public boolean all(final Queryable<T> source,
@@ -291,7 +291,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.elementAt(source, index);
       }
-    }.<T>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public T elementAtOrDefault(final Queryable<T> source, final int index) {
@@ -299,7 +299,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.elementAtOrDefault(source, index);
       }
-    }.<T>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public Queryable<T> except(final Queryable<T> source,
@@ -572,7 +572,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.max(source);
       }
-    }.<T>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public <TResult extends Comparable<TResult>> TResult max(
@@ -582,7 +582,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.max(source, selector);
       }
-    }.<TResult>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public T min(final Queryable<T> source) {
@@ -590,7 +590,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.min(source);
       }
-    }.<T>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public <TResult extends Comparable<TResult>> TResult min(
@@ -600,7 +600,7 @@ public class QueryableRecorder<T> implements QueryableFactory<T> {
       public void replay(QueryableFactory<T> factory) {
         factory.min(source, selector);
       }
-    }.<TResult>castSingle(); // CHECKSTYLE: IGNORE 0
+    }.castSingle(); // CHECKSTYLE: IGNORE 0
   }
 
   public <TResult> Queryable<TResult> ofType(final Queryable<T> source,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/function/Function1.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Function1.java b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Function1.java
index 9181a02..faad8c6 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Function1.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Function1.java
@@ -28,11 +28,7 @@ public interface Function1<T0, R> extends Function<R> {
    *
    * @see Functions#identitySelector()
    */
-  Function1<Object, Object> IDENTITY = new Function1<Object, Object>() {
-    public Object apply(Object v0) {
-      return v0;
-    }
-  };
+  Function1<Object, Object> IDENTITY = v0 -> v0;
 
   R apply(T0 a0);
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/function/Functions.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Functions.java b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Functions.java
index f903422..b8f1caa 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Functions.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Functions.java
@@ -37,7 +37,7 @@ public abstract class Functions {
   private Functions() {}
 
   public static final Map<Class<? extends Function>, Class> FUNCTION_RESULT_TYPES =
-      Collections.<Class<? extends Function>, Class>unmodifiableMap(
+      Collections.unmodifiableMap(
           map(Function0.class, Object.class,
               Function1.class, Object.class,
               Function2.class, Object.class,
@@ -74,19 +74,10 @@ public abstract class Functions {
   private static final EqualityComparer<Object[]> ARRAY_COMPARER =
       new ArrayEqualityComparer();
 
-  private static final Function1 CONSTANT_NULL_FUNCTION1 =
-      new Function1() {
-        public Object apply(Object s) {
-          return null;
-        }
-      };
+  private static final Function1 CONSTANT_NULL_FUNCTION1 = s -> null;
 
   private static final Function1 TO_STRING_FUNCTION1 =
-      new Function1<Object, String>() {
-        public String apply(Object a0) {
-          return a0.toString();
-        }
-      };
+      (Function1<Object, String>) Object::toString;
 
   @SuppressWarnings("unchecked")
   private static <K, V> Map<K, V> map(K k, V v, Object... rest) {
@@ -108,11 +99,7 @@ public abstract class Functions {
 
   /** Returns a 1-parameter function that always returns the same value. */
   public static <T, R> Function1<T, R> constant(final R r) {
-    return new Function1<T, R>() {
-      public R apply(T s) {
-        return r;
-      }
-    };
+    return s -> r;
   }
 
   /** Returns a 1-parameter function that always returns null. */
@@ -194,20 +181,12 @@ public abstract class Functions {
    * @return Predicate that tests for desired type
    */
   public static <T, T2> Predicate1<T> ofTypePredicate(final Class<T2> clazz) {
-    return new Predicate1<T>() {
-      public boolean apply(T v1) {
-        return v1 == null || clazz.isInstance(v1);
-      }
-    };
+    return v1 -> v1 == null || clazz.isInstance(v1);
   }
 
   public static <T1, T2> Predicate2<T1, T2> toPredicate2(
       final Predicate1<T1> p1) {
-    return new Predicate2<T1, T2>() {
-      public boolean apply(T1 v1, T2 v2) {
-        return p1.apply(v1);
-      }
-    };
+    return (v1, v2) -> p1.apply(v1);
   }
 
   /**
@@ -215,11 +194,7 @@ public abstract class Functions {
    */
   public static <T1, T2> Predicate2<T1, T2> toPredicate(
       final Function2<T1, T2, Boolean> function) {
-    return new Predicate2<T1, T2>() {
-      public boolean apply(T1 v1, T2 v2) {
-        return function.apply(v1, v2);
-      }
-    };
+    return function::apply;
   }
 
   /**
@@ -227,11 +202,7 @@ public abstract class Functions {
    */
   private static <T> Predicate1<T> toPredicate(
       final Function1<T, Boolean> function) {
-    return new Predicate1<T>() {
-      public boolean apply(T v1) {
-        return function.apply(v1);
-      }
-    };
+    return function::apply;
   }
 
   /**
@@ -260,11 +231,7 @@ public abstract class Functions {
    */
   public static <T1> Function1<T1, Integer> adapt(
       final IntegerFunction1<T1> f) {
-    return new Function1<T1, Integer>() {
-      public Integer apply(T1 a0) {
-        return f.apply(a0);
-      }
-    };
+    return f::apply;
   }
 
   /**
@@ -272,11 +239,7 @@ public abstract class Functions {
    * an {@link Function1} returning a {@link Double}.
    */
   public static <T1> Function1<T1, Double> adapt(final DoubleFunction1<T1> f) {
-    return new Function1<T1, Double>() {
-      public Double apply(T1 a0) {
-        return f.apply(a0);
-      }
-    };
+    return f::apply;
   }
 
   /**
@@ -284,11 +247,7 @@ public abstract class Functions {
    * an {@link Function1} returning a {@link Long}.
    */
   public static <T1> Function1<T1, Long> adapt(final LongFunction1<T1> f) {
-    return new Function1<T1, Long>() {
-      public Long apply(T1 a0) {
-        return f.apply(a0);
-      }
-    };
+    return f::apply;
   }
 
   /**
@@ -296,11 +255,7 @@ public abstract class Functions {
    * an {@link Function1} returning a {@link Float}.
    */
   public static <T1> Function1<T1, Float> adapt(final FloatFunction1<T1> f) {
-    return new Function1<T1, Float>() {
-      public Float apply(T1 a0) {
-        return f.apply(a0);
-      }
-    };
+    return f::apply;
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate1.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate1.java b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate1.java
index 062a8f0..b8ccaa6 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate1.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate1.java
@@ -27,22 +27,14 @@ public interface Predicate1<T0> extends Function<Boolean> {
    *
    * @see Functions#truePredicate1()
    */
-  Predicate1<Object> TRUE = new Predicate1<Object>() {
-    public boolean apply(Object v0) {
-      return true;
-    }
-  };
+  Predicate1<Object> TRUE = v0 -> true;
 
   /**
    * Predicate that always evaluates to {@code false}.
    *
    * @see Functions#falsePredicate1()
    */
-  Predicate1<Object> FALSE = new Predicate1<Object>() {
-    public boolean apply(Object v0) {
-      return false;
-    }
-  };
+  Predicate1<Object> FALSE = v0 -> false;
 
   boolean apply(T0 v0);
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate2.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate2.java b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate2.java
index c0cbe79..a3f661d 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate2.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/function/Predicate2.java
@@ -28,22 +28,14 @@ public interface Predicate2<T0, T1> extends Function<Boolean> {
    *
    * @see org.apache.calcite.linq4j.function.Functions#truePredicate1()
    */
-  Predicate2<Object, Object> TRUE = new Predicate2<Object, Object>() {
-    public boolean apply(Object v0, Object v1) {
-      return true;
-    }
-  };
+  Predicate2<Object, Object> TRUE = (v0, v1) -> true;
 
   /**
    * Predicate that always evaluates to {@code false}.
    *
    * @see org.apache.calcite.linq4j.function.Functions#falsePredicate1()
    */
-  Predicate2<Object, Object> FALSE = new Predicate2<Object, Object>() {
-    public boolean apply(Object v0, Object v1) {
-      return false;
-    }
-  };
+  Predicate2<Object, Object> FALSE = (v0, v1) -> false;
 
   boolean apply(T0 v0, T1 v1);
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ClassDeclarationFinder.java
----------------------------------------------------------------------
diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ClassDeclarationFinder.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ClassDeclarationFinder.java
index d0c27e8..227e90d 100644
--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ClassDeclarationFinder.java
+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/ClassDeclarationFinder.java
@@ -42,11 +42,7 @@ public class ClassDeclarationFinder extends Shuttle {
 
   private static final Function1<ClassDeclarationFinder,
       ClassDeclarationFinder> DEFAULT_CHILD_FACTORY =
-      new Function1<ClassDeclarationFinder, ClassDeclarationFinder>() {
-      public ClassDeclarationFinder apply(ClassDeclarationFinder a0) {
-        return new DeterministicCodeOptimizer(a0);
-      }
-    };
+      DeterministicCodeOptimizer::new;
 
   /**
    * Creates visitor that uses default optimizer.
@@ -94,20 +90,18 @@ public class ClassDeclarationFinder extends Shuttle {
     try {
       final Constructor<? extends ClassDeclarationFinder> constructor =
           optimizingClass.getConstructor(ClassDeclarationFinder.class);
-      return new Function1<ClassDeclarationFinder, ClassDeclarationFinder>() {
-        public ClassDeclarationFinder apply(ClassDeclarationFinder a0) {
-          try {
-            return constructor.newInstance(a0);
-          } catch (InstantiationException e) {
-            throw new IllegalStateException(
-                "Unable to create optimizer via " + constructor, e);
-          } catch (IllegalAccessException e) {
-            throw new IllegalStateException(
-                "Unable to create optimizer via " + constructor, e);
-          } catch (InvocationTargetException e) {
-            throw new IllegalStateException(
-                "Unable to create optimizer via " + constructor, e);
-          }
+      return a0 -> {
+        try {
+          return constructor.newInstance(a0);
+        } catch (InstantiationException e) {
+          throw new IllegalStateException(
+              "Unable to create optimizer via " + constructor, e);
+        } catch (IllegalAccessException e) {
+          throw new IllegalStateException(
+              "Unable to create optimizer via " + constructor, e);
+        } catch (InvocationTargetException e) {
+          throw new IllegalStateException(
+              "Unable to create optimizer via " + constructor, e);
         }
       };
     } catch (NoSuchMethodException e) {


[18/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdAllPredicates.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdAllPredicates.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdAllPredicates.java
index 4430db4..6101846 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdAllPredicates.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdAllPredicates.java
@@ -41,7 +41,6 @@ import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
@@ -195,14 +194,9 @@ public class RelMdAllPredicates
               RelTableRef.of(rightRef.getTable(), shift + rightRef.getEntityNumber()));
         }
         final List<RexNode> updatedPreds = Lists.newArrayList(
-            Iterables.transform(
-                inputPreds.pulledUpPredicates,
-                new Function<RexNode, RexNode>() {
-                  @Override public RexNode apply(RexNode e) {
-                    return RexUtil.swapTableReferences(rexBuilder, e, currentTablesMapping);
-                  }
-                }
-          ));
+            Iterables.transform(inputPreds.pulledUpPredicates,
+                e -> RexUtil.swapTableReferences(rexBuilder, e,
+                    currentTablesMapping)));
         newPreds = newPreds.union(rexBuilder,
             RelOptPredicateList.of(rexBuilder, updatedPreds));
       }
@@ -283,14 +277,9 @@ public class RelMdAllPredicates
         }
         // Update preds
         final List<RexNode> updatedPreds = Lists.newArrayList(
-            Iterables.transform(
-                inputPreds.pulledUpPredicates,
-                new Function<RexNode, RexNode>() {
-                  @Override public RexNode apply(RexNode e) {
-                    return RexUtil.swapTableReferences(rexBuilder, e, currentTablesMapping);
-                  }
-                }
-          ));
+            Iterables.transform(inputPreds.pulledUpPredicates,
+                e -> RexUtil.swapTableReferences(rexBuilder, e,
+                    currentTablesMapping)));
         newPreds = newPreds.union(rexBuilder,
             RelOptPredicateList.of(rexBuilder, updatedPreds));
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdCollation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdCollation.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdCollation.java
index 8fed9bb..aa42f42 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdCollation.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdCollation.java
@@ -48,10 +48,8 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.LinkedListMultimap;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Ordering;
 
@@ -60,6 +58,7 @@ import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
@@ -169,7 +168,7 @@ public class RelMdCollation
   public ImmutableList<RelCollation> collations(RelSubset rel,
       RelMetadataQuery mq) {
     return ImmutableList.copyOf(
-        Preconditions.checkNotNull(
+        Objects.requireNonNull(
             rel.getTraitSet().getTraits(RelCollationTraitDef.INSTANCE)));
   }
 
@@ -302,10 +301,10 @@ public class RelMdCollation
   public static List<RelCollation> values(RelMetadataQuery mq,
       RelDataType rowType, ImmutableList<ImmutableList<RexLiteral>> tuples) {
     Util.discard(mq); // for future use
-    final List<RelCollation> list = Lists.newArrayList();
+    final List<RelCollation> list = new ArrayList<>();
     final int n = rowType.getFieldCount();
     final List<Pair<RelFieldCollation, Ordering<List<RexLiteral>>>> pairs =
-        Lists.newArrayList();
+        new ArrayList<>();
   outer:
     for (int i = 0; i < n; i++) {
       pairs.clear();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdColumnUniqueness.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdColumnUniqueness.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdColumnUniqueness.java
index ead85fa..e9625fa 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdColumnUniqueness.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdColumnUniqueness.java
@@ -40,13 +40,11 @@ import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 
 import java.util.ArrayList;
@@ -64,14 +62,6 @@ public class RelMdColumnUniqueness
       ReflectiveRelMetadataProvider.reflectiveSource(
           BuiltInMethod.COLUMN_UNIQUENESS.method, new RelMdColumnUniqueness());
 
-  /** Aggregate and Calc are "safe" children of a RelSubset to delve into. */
-  private static final Predicate<RelNode> SAFE_REL =
-      new PredicateImpl<RelNode>() {
-        public boolean test(RelNode r) {
-          return r instanceof Aggregate || r instanceof Project;
-        }
-      };
-
   //~ Constructors -----------------------------------------------------------
 
   private RelMdColumnUniqueness() {}

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdExpressionLineage.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdExpressionLineage.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdExpressionLineage.java
index e7c82fd..1afadc3 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdExpressionLineage.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdExpressionLineage.java
@@ -41,12 +41,11 @@ import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.HashMultimap;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -57,6 +56,7 @@ import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 /**
  * Default implementation of
@@ -127,9 +127,8 @@ public class RelMdExpressionLineage
       final RexNode inputRef = RexTableInputRef.of(
           RelTableRef.of(rel.getTable(), 0),
           RexInputRef.of(idx, rel.getRowType().getFieldList()));
-      final Set<RexNode> originalExprs = Sets.newHashSet(inputRef);
       final RexInputRef ref = RexInputRef.of(idx, rel.getRowType().getFieldList());
-      mapping.put(ref, originalExprs);
+      mapping.put(ref, ImmutableSet.of(inputRef));
     }
 
     // Return result
@@ -237,15 +236,10 @@ public class RelMdExpressionLineage
           currentTablesMapping.put(rightRef,
               RelTableRef.of(rightRef.getTable(), shift + rightRef.getEntityNumber()));
         }
-        final Set<RexNode> updatedExprs = Sets.newHashSet(
-            Iterables.transform(
-                originalExprs,
-                new Function<RexNode, RexNode>() {
-                  @Override public RexNode apply(RexNode e) {
-                    return RexUtil.swapTableReferences(rexBuilder, e, currentTablesMapping);
-                  }
-                }
-          ));
+        final Set<RexNode> updatedExprs = ImmutableSet.copyOf(
+            Iterables.transform(originalExprs, e ->
+                RexUtil.swapTableReferences(rexBuilder, e,
+                    currentTablesMapping)));
         mapping.put(RexInputRef.of(idx, rel.getRowType().getFieldList()), updatedExprs);
       }
     }
@@ -292,15 +286,12 @@ public class RelMdExpressionLineage
           currentTablesMapping.put(tableRef,
               RelTableRef.of(tableRef.getTable(), shift + tableRef.getEntityNumber()));
         }
-        final Set<RexNode> updatedExprs = Sets.newHashSet(
-            Iterables.transform(
-                originalExprs,
-                new Function<RexNode, RexNode>() {
-                  @Override public RexNode apply(RexNode e) {
-                    return RexUtil.swapTableReferences(rexBuilder, e, currentTablesMapping);
-                  }
-                }
-          ));
+        final Set<RexNode> updatedExprs =
+            originalExprs.stream()
+                .map(e ->
+                    RexUtil.swapTableReferences(rexBuilder, e,
+                        currentTablesMapping))
+                .collect(Collectors.toSet());
         final Set<RexNode> set = mapping.get(ref);
         if (set != null) {
           set.addAll(updatedExprs);
@@ -393,7 +384,7 @@ public class RelMdExpressionLineage
 
     if (predFieldsUsed.isEmpty()) {
       // The unique expression is the input expression
-      return Sets.newHashSet(expr);
+      return ImmutableSet.of(expr);
     }
 
     return createAllPossibleExpressions(rexBuilder, expr, predFieldsUsed, mapping,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdPredicates.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdPredicates.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdPredicates.java
index 02f6bda..6e30189 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdPredicates.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdPredicates.java
@@ -18,7 +18,6 @@ package org.apache.calcite.rel.metadata;
 
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.Ord;
-import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptPredicateList;
 import org.apache.calcite.plan.RelOptUtil;
@@ -58,11 +57,9 @@ import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.MappingType;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
 import java.util.ArrayList;
 import java.util.BitSet;
@@ -73,8 +70,10 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.Objects;
 import java.util.Set;
 import java.util.SortedMap;
+import java.util.TreeMap;
 
 /**
  * Utility to infer Predicates that are applicable above a RelNode.
@@ -511,7 +510,7 @@ public class RelMdPredicates
       allFieldsBitSet = ImmutableBitSet.range(0,
           nSysFields + nFieldsLeft + nFieldsRight);
 
-      exprFields = Maps.newHashMap();
+      exprFields = new HashMap<>();
       allExprDigests = new HashSet<>();
 
       if (lPreds == null) {
@@ -544,7 +543,7 @@ public class RelMdPredicates
         }
       }
 
-      equivalence = Maps.newTreeMap();
+      equivalence = new TreeMap<>();
       equalityPredicates = new HashSet<>();
       for (int i = 0; i < nSysFields + nFieldsLeft + nFieldsRight; i++) {
         equivalence.put(i, BitSets.of(i));
@@ -560,12 +559,7 @@ public class RelMdPredicates
 
       final EquivalenceFinder eF = new EquivalenceFinder();
       new ArrayList<>(
-          Lists.transform(exprs,
-              new Function<RexNode, Void>() {
-                public Void apply(RexNode input) {
-                  return input.accept(eF);
-                }
-              }));
+          Lists.transform(exprs, input -> input.accept(eF)));
 
       equivalence = BitSets.closure(equivalence);
     }
@@ -695,14 +689,12 @@ public class RelMdPredicates
     }
 
     Iterable<Mapping> mappings(final RexNode predicate) {
-      return new Iterable<Mapping>() {
-        public Iterator<Mapping> iterator() {
-          ImmutableBitSet fields = exprFields.get(predicate.toString());
-          if (fields.cardinality() == 0) {
-            return Collections.emptyIterator();
-          }
-          return new ExprsItr(fields);
+      return () -> {
+        ImmutableBitSet fields = exprFields.get(predicate.toString());
+        if (fields.cardinality() == 0) {
+          return Collections.emptyIterator();
         }
+        return new ExprsItr(fields);
       };
     }
 
@@ -722,11 +714,7 @@ public class RelMdPredicates
     }
 
     RexNode compose(RexBuilder rexBuilder, Iterable<RexNode> exprs) {
-      exprs = Linq4j.asEnumerable(exprs).where(new Predicate1<RexNode>() {
-        public boolean apply(RexNode expr) {
-          return expr != null;
-        }
-      });
+      exprs = Linq4j.asEnumerable(exprs).where(Objects::nonNull);
       return RexUtil.composeConjunction(rexBuilder, exprs, false);
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdSize.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdSize.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdSize.java
index 63c27b1..998b7aa 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdSize.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdSize.java
@@ -43,8 +43,8 @@ import org.apache.calcite.util.NlsString;
 import org.apache.calcite.util.Pair;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -219,7 +219,7 @@ public class RelMdSize implements MetadataHandler<BuiltInMetadata.Size> {
 
   public List<Double> averageColumnSizes(Union rel, RelMetadataQuery mq) {
     final int fieldCount = rel.getRowType().getFieldCount();
-    List<List<Double>> inputColumnSizeList = Lists.newArrayList();
+    List<List<Double>> inputColumnSizeList = new ArrayList<>();
     for (RelNode input : rel.getInputs()) {
       final List<Double> inputSizes = mq.getAverageColumnSizes(input);
       if (inputSizes != null) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMdTableReferences.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdTableReferences.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdTableReferences.java
index d84e911..38b1ca2 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMdTableReferences.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMdTableReferences.java
@@ -32,8 +32,8 @@ import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Util;
 
 import com.google.common.collect.HashMultimap;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
 
 import java.util.Collection;
 import java.util.HashMap;
@@ -88,7 +88,7 @@ public class RelMdTableReferences
    * TableScan table reference.
    */
   public Set<RelTableRef> getTableReferences(TableScan rel, RelMetadataQuery mq) {
-    return Sets.newHashSet(RelTableRef.of(rel.getTable(), 0));
+    return ImmutableSet.of(RelTableRef.of(rel.getTable(), 0));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/RelMetadataQuery.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/RelMetadataQuery.java b/core/src/main/java/org/apache/calcite/rel/metadata/RelMetadataQuery.java
index 06c4fb0..d8f3dd2 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/RelMetadataQuery.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/RelMetadataQuery.java
@@ -27,18 +27,16 @@ import org.apache.calcite.rex.RexTableInputRef.RelTableRef;
 import org.apache.calcite.sql.SqlExplainLevel;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Multimap;
 
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -109,15 +107,11 @@ public class RelMetadataQuery {
   private BuiltInMetadata.UniqueKeys.Handler uniqueKeysHandler;
 
   public static final ThreadLocal<JaninoRelMetadataProvider> THREAD_PROVIDERS =
-      new ThreadLocal<JaninoRelMetadataProvider>() {
-        protected JaninoRelMetadataProvider initialValue() {
-          return JaninoRelMetadataProvider.DEFAULT;
-        }
-      };
+      ThreadLocal.withInitial(() -> JaninoRelMetadataProvider.DEFAULT);
 
   protected RelMetadataQuery(JaninoRelMetadataProvider metadataProvider,
       RelMetadataQuery prototype) {
-    this.metadataProvider = Preconditions.checkNotNull(metadataProvider);
+    this.metadataProvider = Objects.requireNonNull(metadataProvider);
     this.collationHandler = prototype.collationHandler;
     this.columnOriginHandler = prototype.columnOriginHandler;
     this.expressionLineageHandler = prototype.expressionLineageHandler;
@@ -146,13 +140,9 @@ public class RelMetadataQuery {
   protected static <H> H initialHandler(Class<H> handlerClass) {
     return handlerClass.cast(
         Proxy.newProxyInstance(RelMetadataQuery.class.getClassLoader(),
-            new Class[] {handlerClass},
-            new InvocationHandler() {
-              public Object invoke(Object proxy, Method method, Object[] args)
-                  throws Throwable {
-                final RelNode r = (RelNode) args[0];
-                throw new JaninoRelMetadataProvider.NoHandler(r.getClass());
-              }
+            new Class[] {handlerClass}, (proxy, method, args) -> {
+              final RelNode r = (RelNode) args[0];
+              throw new JaninoRelMetadataProvider.NoHandler(r.getClass());
             }));
   }
 
@@ -656,7 +646,7 @@ public class RelMetadataQuery {
   public List<Double> getAverageColumnSizesNotNull(RelNode rel) {
     final List<Double> averageColumnSizes = getAverageColumnSizes(rel);
     return averageColumnSizes == null
-        ? Collections.<Double>nCopies(rel.getRowType().getFieldCount(), null)
+        ? Collections.nCopies(rel.getRowType().getFieldCount(), null)
         : averageColumnSizes;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/metadata/UnboundMetadata.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/metadata/UnboundMetadata.java b/core/src/main/java/org/apache/calcite/rel/metadata/UnboundMetadata.java
index ef8dc4a..85a6c76 100644
--- a/core/src/main/java/org/apache/calcite/rel/metadata/UnboundMetadata.java
+++ b/core/src/main/java/org/apache/calcite/rel/metadata/UnboundMetadata.java
@@ -24,6 +24,7 @@ import org.apache.calcite.rel.RelNode;
  *
  * @param <M> Metadata type
  */
+@FunctionalInterface
 public interface UnboundMetadata<M extends Metadata> {
   M bind(RelNode rel, RelMetadataQuery mq);
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/mutable/MutableMultiRel.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/mutable/MutableMultiRel.java b/core/src/main/java/org/apache/calcite/rel/mutable/MutableMultiRel.java
index 531f3e5..05ba762 100644
--- a/core/src/main/java/org/apache/calcite/rel/mutable/MutableMultiRel.java
+++ b/core/src/main/java/org/apache/calcite/rel/mutable/MutableMultiRel.java
@@ -20,7 +20,6 @@ import org.apache.calcite.linq4j.Ord;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.rel.type.RelDataType;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
@@ -59,12 +58,7 @@ abstract class MutableMultiRel extends MutableRel {
   }
 
   protected List<MutableRel> cloneChildren() {
-    return Lists.transform(inputs,
-        new Function<MutableRel, MutableRel>() {
-          public MutableRel apply(MutableRel mutableRel) {
-            return mutableRel.clone();
-          }
-        });
+    return Lists.transform(inputs, MutableRel::clone);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/mutable/MutableRel.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/mutable/MutableRel.java b/core/src/main/java/org/apache/calcite/rel/mutable/MutableRel.java
index 385ea44..fb0d72b 100644
--- a/core/src/main/java/org/apache/calcite/rel/mutable/MutableRel.java
+++ b/core/src/main/java/org/apache/calcite/rel/mutable/MutableRel.java
@@ -22,10 +22,10 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.type.RelDataType;
 
 import com.google.common.base.Equivalence;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
 import java.util.List;
+import java.util.Objects;
 
 /** Mutable equivalent of {@link RelNode}.
  *
@@ -69,9 +69,9 @@ public abstract class MutableRel {
 
   protected MutableRel(RelOptCluster cluster,
       RelDataType rowType, MutableRelType type) {
-    this.cluster = Preconditions.checkNotNull(cluster);
-    this.rowType = Preconditions.checkNotNull(rowType);
-    this.type = Preconditions.checkNotNull(type);
+    this.cluster = Objects.requireNonNull(cluster);
+    this.rowType = Objects.requireNonNull(rowType);
+    this.type = Objects.requireNonNull(type);
   }
 
   public MutableRel getParent() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/mutable/MutableRels.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/mutable/MutableRels.java b/core/src/main/java/org/apache/calcite/rel/mutable/MutableRels.java
index 8470dc6..31510ca 100644
--- a/core/src/main/java/org/apache/calcite/rel/mutable/MutableRels.java
+++ b/core/src/main/java/org/apache/calcite/rel/mutable/MutableRels.java
@@ -56,7 +56,6 @@ import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.util.AbstractList;
@@ -275,13 +274,10 @@ public abstract class MutableRels {
     }
   }
 
-  private static List<RelNode> fromMutables(List<MutableRel> nodes, final RelBuilder relBuilder) {
+  private static List<RelNode> fromMutables(List<MutableRel> nodes,
+      final RelBuilder relBuilder) {
     return Lists.transform(nodes,
-        new Function<MutableRel, RelNode>() {
-          public RelNode apply(MutableRel mutableRel) {
-            return fromMutable(mutableRel, relBuilder);
-          }
-        });
+        mutableRel -> fromMutable(mutableRel, relBuilder));
   }
 
   public static MutableRel toMutable(RelNode rel) {
@@ -408,12 +404,7 @@ public abstract class MutableRels {
   }
 
   private static List<MutableRel> toMutables(List<RelNode> nodes) {
-    return Lists.transform(nodes,
-        new Function<RelNode, MutableRel>() {
-          public MutableRel apply(RelNode relNode) {
-            return toMutable(relNode);
-          }
-        });
+    return Lists.transform(nodes, MutableRels::toMutable);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java b/core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java
index 2afda14..4ee45fd 100644
--- a/core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java
+++ b/core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java
@@ -65,7 +65,6 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.ReflectUtil;
 import org.apache.calcite.util.ReflectiveVisitor;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
@@ -381,7 +380,7 @@ public class RelToSqlConverter extends SqlImplementor
           new SqlInsert(POS, SqlNodeList.EMPTY, sqlTargetTable, sqlSource,
               identifierList(modify.getInput().getRowType().getFieldNames()));
 
-      return result(sqlInsert, ImmutableList.<Clause>of(), modify, null);
+      return result(sqlInsert, ImmutableList.of(), modify, null);
     }
     case UPDATE: {
       final Result input = visitChild(0, modify.getInput());
@@ -415,24 +414,14 @@ public class RelToSqlConverter extends SqlImplementor
   private SqlNodeList exprList(final Context context,
       List<? extends RexNode> exprs) {
     return new SqlNodeList(
-        Lists.transform(exprs,
-            new Function<RexNode, SqlNode>() {
-              public SqlNode apply(RexNode e) {
-                return context.toSql(null, e);
-              }
-            }), POS);
+        Lists.transform(exprs, e -> context.toSql(null, e)), POS);
   }
 
   /** Converts a list of names expressions to a list of single-part
    * {@link SqlIdentifier}s. */
   private SqlNodeList identifierList(List<String> names) {
     return new SqlNodeList(
-        Lists.transform(names,
-            new Function<String, SqlNode>() {
-              public SqlNode apply(String name) {
-                return new SqlIdentifier(name, POS);
-              }
-            }), POS);
+        Lists.transform(names, name -> new SqlIdentifier(name, POS)), POS);
   }
 
   /** @see #dispatch */
@@ -500,7 +489,7 @@ public class RelToSqlConverter extends SqlImplementor
     final SqlNodeList subsetList = new SqlNodeList(POS);
     for (Map.Entry<String, SortedSet<String>> entry : e.getSubsets().entrySet()) {
       SqlNode left = new SqlIdentifier(entry.getKey(), POS);
-      List<SqlNode> rhl = Lists.newArrayList();
+      List<SqlNode> rhl = new ArrayList<>();
       for (String right : entry.getValue()) {
         rhl.add(new SqlIdentifier(right, POS));
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java b/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java
index 594cd3c..6508525 100644
--- a/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java
+++ b/core/src/main/java/org/apache/calcite/rel/rel2sql/SqlImplementor.java
@@ -72,7 +72,6 @@ import org.apache.calcite.util.TimeString;
 import org.apache.calcite.util.TimestampString;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
@@ -90,6 +89,7 @@ import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -106,7 +106,7 @@ public abstract class SqlImplementor {
   protected final Map<CorrelationId, Context> correlTableMap = new HashMap<>();
 
   protected SqlImplementor(SqlDialect dialect) {
-    this.dialect = Preconditions.checkNotNull(dialect);
+    this.dialect = Objects.requireNonNull(dialect);
   }
 
   public abstract Result visitChild(int i, RelNode e);
@@ -730,7 +730,7 @@ public abstract class SqlImplementor {
       }
       return op.createCall(
           aggCall.isDistinct() ? SqlSelectKeyword.DISTINCT.symbol(POS) : null,
-          POS, operands.toArray(new SqlNode[operands.size()]));
+          POS, operands.toArray(new SqlNode[0]));
     }
 
     /** Converts a collation to an ORDER BY item. */
@@ -1067,7 +1067,7 @@ public abstract class SqlImplementor {
         return this;
       } else {
         return new Result(node, clauses, neededAlias, neededType,
-            ImmutableMap.<String, RelDataType>of(neededAlias, neededType));
+            ImmutableMap.of(neededAlias, neededType));
       }
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AbstractMaterializedViewRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AbstractMaterializedViewRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AbstractMaterializedViewRule.java
index f9dd2f4..2753c44 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AbstractMaterializedViewRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AbstractMaterializedViewRule.java
@@ -214,7 +214,7 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
     final List<RelOptMaterialization> materializations =
         (planner instanceof VolcanoPlanner)
             ? ((VolcanoPlanner) planner).getMaterializations()
-            : ImmutableList.<RelOptMaterialization>of();
+            : ImmutableList.of();
 
     if (!materializations.isEmpty()) {
       // 1. Explore query plan to recognize whether preconditions to
@@ -1365,7 +1365,7 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
       // if not present
       if (topViewProject == null) {
         topViewProject = (Project) relBuilder.push(viewNode)
-            .project(relBuilder.fields(), ImmutableList.<String>of(), true).build();
+            .project(relBuilder.fields(), ImmutableList.of(), true).build();
       }
 
       // Generate result rewriting
@@ -1836,8 +1836,8 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
       return ImmutableList.of();
     }
     List<BiMap<RelTableRef, RelTableRef>> result =
-        ImmutableList.<BiMap<RelTableRef, RelTableRef>>of(
-            HashBiMap.<RelTableRef, RelTableRef>create());
+        ImmutableList.of(
+            HashBiMap.create());
     for (Entry<RelTableRef, Collection<RelTableRef>> e : multiMapTables.asMap().entrySet()) {
       if (e.getValue().size() == 1) {
         // Only one reference, we can just add it to every map
@@ -1854,7 +1854,7 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
         for (BiMap<RelTableRef, RelTableRef> m : result) {
           if (!m.containsValue(target)) {
             final BiMap<RelTableRef, RelTableRef> newM =
-                HashBiMap.<RelTableRef, RelTableRef>create(m);
+                HashBiMap.create(m);
             newM.put(e.getKey(), target);
             newResult.add(newM);
           }
@@ -1937,7 +1937,7 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
         residualPreds.add(e);
       }
     }
-    return ImmutableTriple.<RexNode, RexNode, RexNode>of(
+    return ImmutableTriple.of(
         RexUtil.composeConjunction(rexBuilder, equiColumnsPreds, false),
         RexUtil.composeConjunction(rexBuilder, rangePreds, false),
         RexUtil.composeConjunction(rexBuilder, residualPreds, false));
@@ -1968,7 +1968,7 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
       Multimap<RexTableInputRef, RexTableInputRef> compensationEquiColumns) {
     // Create UK-FK graph with view tables
     final DirectedGraph<RelTableRef, Edge> graph =
-        DefaultDirectedGraph.create(Edge.FACTORY);
+        DefaultDirectedGraph.create(Edge::new);
     final Multimap<List<String>, RelTableRef> tableVNameToTableRefs =
         ArrayListMultimap.create();
     final Set<RelTableRef> extraTableRefs = new HashSet<>();
@@ -2117,8 +2117,8 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
       return null;
     }
 
-    return ImmutableTriple.<RexNode, RexNode, RexNode>of(
-        compensationColumnsEquiPred, compensationRangePred, compensationResidualPred);
+    return ImmutableTriple.of(compensationColumnsEquiPred,
+        compensationRangePred, compensationResidualPred);
   }
 
   /**
@@ -2625,12 +2625,6 @@ public abstract class AbstractMaterializedViewRule extends RelOptRule {
 
   /** Edge for graph */
   private static class Edge extends DefaultEdge {
-    public static final DirectedGraph.EdgeFactory<RelTableRef, Edge> FACTORY =
-        new DirectedGraph.EdgeFactory<RelTableRef, Edge>() {
-          public Edge createEdge(RelTableRef source, RelTableRef target) {
-            return new Edge(source, target);
-          }
-        };
 
     final Multimap<RexTableInputRef, RexTableInputRef> equiColumns =
         ArrayListMultimap.create();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java
index 918a4db..d150989 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExpandDistinctAggregatesRule.java
@@ -308,7 +308,7 @@ public final class AggregateExpandDistinctAggregatesRule extends RelOptRule {
 
     // Add aggregate A (see the reference example above), the top aggregate
     // to handle the rest of the aggregation that the bottom aggregate hasn't handled
-    final List<AggregateCall> topAggregateCalls = Lists.newArrayList();
+    final List<AggregateCall> topAggregateCalls = new ArrayList<>();
     // Use the remapped arguments for the (non)distinct aggregate calls
     int nonDistinctAggCallProcessedSoFar = 0;
     for (AggregateCall aggCall : originalAggCalls) {
@@ -707,7 +707,7 @@ public final class AggregateExpandDistinctAggregatesRule extends RelOptRule {
     // where {f0, f1, ...} are the GROUP BY fields.
     final List<RelDataTypeField> distinctFields =
         relBuilder.peek().getRowType().getFieldList();
-    final List<RexNode> conditions = Lists.newArrayList();
+    final List<RexNode> conditions = new ArrayList<>();
     for (i = 0; i < groupAndIndicatorCount; ++i) {
       // null values form its own group
       // use "is not distinct from" so that the join condition
@@ -845,7 +845,7 @@ public final class AggregateExpandDistinctAggregatesRule extends RelOptRule {
     relBuilder.push(
         aggregate.copy(aggregate.getTraitSet(), relBuilder.build(), false,
             ImmutableBitSet.range(projects.size()),
-            null, ImmutableList.<AggregateCall>of()));
+            null, ImmutableList.of()));
     return relBuilder;
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java
index 0e4f76d..23e1425 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateExtractProjectRule.java
@@ -24,7 +24,6 @@ import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.AggregateCall;
 import org.apache.calcite.rel.core.Project;
 import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
@@ -32,16 +31,12 @@ import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.MappingType;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.annotation.Nullable;
-
 /**
  * Rule to extract a {@link org.apache.calcite.rel.core.Project}
  * from an {@link org.apache.calcite.rel.core.Aggregate}
@@ -55,16 +50,6 @@ import javax.annotation.Nullable;
  */
 public class AggregateExtractProjectRule extends RelOptRule {
 
-  /** Predicate that prevents matching against an {@code Aggregate} whose input
-   * is already a {@code Project}. This will prevent this rule firing
-   * repeatedly. */
-  private static final Predicate<RelNode> PREDICATE =
-      new PredicateImpl<RelNode>() {
-        public boolean test(@Nullable RelNode relNode) {
-          return !(relNode instanceof Project);
-        }
-      };
-
   /**
    * Creates an AggregateExtractProjectRule.
    *
@@ -74,7 +59,11 @@ public class AggregateExtractProjectRule extends RelOptRule {
       Class<? extends Aggregate> aggregateClass,
       Class<? extends RelNode> inputClass,
       RelBuilderFactory relBuilderFactory) {
-    this(operand(aggregateClass, operand(inputClass, null, PREDICATE, any())),
+    // Predicate prevents matching against an Aggregate whose input
+    // is already a Project. Prevents this rule firing repeatedly.
+    this(
+        operand(aggregateClass,
+            operandJ(inputClass, null, r -> !(r instanceof Project), any())),
         relBuilderFactory);
   }
 
@@ -119,11 +108,7 @@ public class AggregateExtractProjectRule extends RelOptRule {
     final ImmutableList<ImmutableBitSet> newGroupSets =
         ImmutableList.copyOf(
             Iterables.transform(aggregate.getGroupSets(),
-                new Function<ImmutableBitSet, ImmutableBitSet>() {
-                  public ImmutableBitSet apply(ImmutableBitSet input) {
-                    return Mappings.apply(mapping, input);
-                  }
-                }));
+                bitSet -> Mappings.apply(mapping, bitSet)));
     final List<RelBuilder.AggCall> newAggCallList = new ArrayList<>();
     for (AggregateCall aggCall : aggregate.getAggCallList()) {
       final ImmutableList<RexNode> args =

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java
index 6e9e508..5c0e531 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java
@@ -35,10 +35,9 @@ import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -97,11 +96,7 @@ public class AggregateFilterTransposeRule extends RelOptRule {
         aggregate.copy(aggregate.getTraitSet(), input,
                 false, newGroupSet, null, aggregate.getAggCallList());
     final Mappings.TargetMapping mapping = Mappings.target(
-        new Function<Integer, Integer>() {
-          public Integer apply(Integer a0) {
-            return newGroupSet.indexOf(a0);
-          }
-        },
+        newGroupSet::indexOf,
         input.getRowType().getFieldCount(),
         newGroupSet.cardinality());
     final RexNode newCondition =
@@ -134,7 +129,7 @@ public class AggregateFilterTransposeRule extends RelOptRule {
         }
         newGroupingSets = newGroupingSetsBuilder.build();
       }
-      final List<AggregateCall> topAggCallList = Lists.newArrayList();
+      final List<AggregateCall> topAggCallList = new ArrayList<>();
       int i = newGroupSet.cardinality();
       for (AggregateCall aggregateCall : aggregate.getAggCallList()) {
         final SqlAggFunction rollup =

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java
index 28c58f3..e841952 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateJoinTransposeRule.java
@@ -45,16 +45,14 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.SortedMap;
 import java.util.TreeMap;
 
@@ -80,8 +78,10 @@ public class AggregateJoinTransposeRule extends RelOptRule {
       Class<? extends Join> joinClass, RelBuilderFactory relBuilderFactory,
       boolean allowFunctions) {
     super(
-        operand(aggregateClass, null, Aggregate.IS_SIMPLE,
-            operand(joinClass, any())), relBuilderFactory, null);
+        operandJ(aggregateClass, null,
+            aggregate -> aggregate.getGroupType() == Aggregate.Group.SIMPLE,
+            operand(joinClass, any())),
+        relBuilderFactory, null);
     this.allowFunctions = allowFunctions;
   }
 
@@ -167,9 +167,9 @@ public class AggregateJoinTransposeRule extends RelOptRule {
         aggregateColumns.union(joinColumns);
 
     // Split join condition
-    final List<Integer> leftKeys = Lists.newArrayList();
-    final List<Integer> rightKeys = Lists.newArrayList();
-    final List<Boolean> filterNulls = Lists.newArrayList();
+    final List<Integer> leftKeys = new ArrayList<>();
+    final List<Integer> rightKeys = new ArrayList<>();
+    final List<Boolean> filterNulls = new ArrayList<>();
     RexNode nonEquiConj =
         RelOptUtil.splitJoinCondition(join.getLeft(), join.getRight(),
             join.getCondition(), leftKeys, rightKeys, filterNulls);
@@ -237,7 +237,7 @@ public class AggregateJoinTransposeRule extends RelOptRule {
         for (Ord<AggregateCall> aggCall : Ord.zip(aggregate.getAggCallList())) {
           final SqlAggFunction aggregation = aggCall.e.getAggregation();
           final SqlSplittableAggFunction splitter =
-              Preconditions.checkNotNull(
+              Objects.requireNonNull(
                   aggregation.unwrap(SqlSplittableAggFunction.class));
           if (!aggCall.e.getArgList().isEmpty()
               && fieldSet.contains(ImmutableBitSet.of(aggCall.e.getArgList()))) {
@@ -268,7 +268,7 @@ public class AggregateJoinTransposeRule extends RelOptRule {
         for (Ord<AggregateCall> aggCall : Ord.zip(aggregate.getAggCallList())) {
           final SqlAggFunction aggregation = aggCall.e.getAggregation();
           final SqlSplittableAggFunction splitter =
-              Preconditions.checkNotNull(
+              Objects.requireNonNull(
                   aggregation.unwrap(SqlSplittableAggFunction.class));
           final AggregateCall call1;
           if (fieldSet.contains(ImmutableBitSet.of(aggCall.e.getArgList()))) {
@@ -303,11 +303,7 @@ public class AggregateJoinTransposeRule extends RelOptRule {
 
     // Update condition
     final Mapping mapping = (Mapping) Mappings.target(
-        new Function<Integer, Integer>() {
-          public Integer apply(Integer a0) {
-            return map.get(a0);
-          }
-        },
+        map::get,
         join.getRowType().getFieldCount(),
         belowOffset);
     final RexNode newCondition =
@@ -329,7 +325,7 @@ public class AggregateJoinTransposeRule extends RelOptRule {
     for (Ord<AggregateCall> aggCall : Ord.zip(aggregate.getAggCallList())) {
       final SqlAggFunction aggregation = aggCall.e.getAggregation();
       final SqlSplittableAggFunction splitter =
-          Preconditions.checkNotNull(
+          Objects.requireNonNull(
               aggregation.unwrap(SqlSplittableAggFunction.class));
       final Integer leftSubTotal = sides.get(0).split.get(aggCall.i);
       final Integer rightSubTotal = sides.get(1).split.get(aggCall.i);
@@ -425,15 +421,13 @@ public class AggregateJoinTransposeRule extends RelOptRule {
    * that is a view of a list. */
   private static <E> SqlSplittableAggFunction.Registry<E> registry(
       final List<E> list) {
-    return new SqlSplittableAggFunction.Registry<E>() {
-      public int register(E e) {
-        int i = list.indexOf(e);
-        if (i < 0) {
-          i = list.size();
-          list.add(e);
-        }
-        return i;
+    return e -> {
+      int i = list.indexOf(e);
+      if (i < 0) {
+        i = list.size();
+        list.add(e);
       }
+      return i;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectMergeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectMergeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectMergeRule.java
index e7ddd58..c5ec515 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectMergeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectMergeRule.java
@@ -31,8 +31,8 @@ import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -73,7 +73,7 @@ public class AggregateProjectMergeRule extends RelOptRule {
 
   public static RelNode apply(RelOptRuleCall call, Aggregate aggregate,
       Project project) {
-    final List<Integer> newKeys = Lists.newArrayList();
+    final List<Integer> newKeys = new ArrayList<>();
     final Map<Integer, Integer> map = new HashMap<>();
     for (int key : aggregate.getGroupSet()) {
       final RexNode rex = project.getProjects().get(key);
@@ -131,7 +131,7 @@ public class AggregateProjectMergeRule extends RelOptRule {
     final RelBuilder relBuilder = call.builder();
     relBuilder.push(newAggregate);
     if (!newKeys.equals(newGroupSet.asList())) {
-      final List<Integer> posList = Lists.newArrayList();
+      final List<Integer> posList = new ArrayList<>();
       for (int newKey : newKeys) {
         posList.add(newGroupSet.indexOf(newKey));
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectPullUpConstantsRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectPullUpConstantsRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectPullUpConstantsRule.java
index eda2b20..8686db2 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectPullUpConstantsRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateProjectPullUpConstantsRule.java
@@ -87,7 +87,7 @@ public class AggregateProjectPullUpConstantsRule extends RelOptRule {
       Class<? extends RelNode> inputClass,
       RelBuilderFactory relBuilderFactory, String description) {
     super(
-        operand(aggregateClass, null, Aggregate.IS_SIMPLE,
+        operandJ(aggregateClass, null, Aggregate::isSimple,
             operand(inputClass, any())),
         relBuilderFactory, description);
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsRule.java
index e65b6a1..8bdd6c1 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsRule.java
@@ -42,12 +42,11 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
 import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -154,10 +153,10 @@ public class AggregateReduceFunctionsRule extends RelOptRule {
     final int groupCount = oldAggRel.getGroupCount();
     final int indicatorCount = oldAggRel.getIndicatorCount();
 
-    final List<AggregateCall> newCalls = Lists.newArrayList();
-    final Map<AggregateCall, RexNode> aggCallMapping = Maps.newHashMap();
+    final List<AggregateCall> newCalls = new ArrayList<>();
+    final Map<AggregateCall, RexNode> aggCallMapping = new HashMap<>();
 
-    final List<RexNode> projList = Lists.newArrayList();
+    final List<RexNode> projList = new ArrayList<>();
 
     // pass through group key (+ indicators if present)
     for (int i = 0; i < groupCount + indicatorCount; ++i) {
@@ -187,7 +186,7 @@ public class AggregateReduceFunctionsRule extends RelOptRule {
       relBuilder.project(inputExprs,
           CompositeList.of(
               relBuilder.peek().getRowType().getFieldNames(),
-              Collections.<String>nCopies(extraArgCount, null)));
+              Collections.nCopies(extraArgCount, null)));
     }
     newAggregateRel(relBuilder, oldAggRel, newCalls);
     newCalcRel(relBuilder, oldAggRel.getRowType(), projList);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java
index f000d39..f1b6d6e 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateStarTableRule.java
@@ -48,8 +48,8 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.mapping.AbstractSourceMapping;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -62,14 +62,14 @@ import java.util.List;
 public class AggregateStarTableRule extends RelOptRule {
   public static final AggregateStarTableRule INSTANCE =
       new AggregateStarTableRule(
-          operand(Aggregate.class, null, Aggregate.IS_SIMPLE,
+          operandJ(Aggregate.class, null, Aggregate::isSimple,
               some(operand(StarTable.StarTableScan.class, none()))),
           RelFactories.LOGICAL_BUILDER,
           "AggregateStarTableRule");
 
   public static final AggregateStarTableRule INSTANCE2 =
       new AggregateStarTableRule(
-          operand(Aggregate.class, null, Aggregate.IS_SIMPLE,
+          operandJ(Aggregate.class, null, Aggregate::isSimple,
               operand(Project.class,
                   operand(StarTable.StarTableScan.class, none()))),
           RelFactories.LOGICAL_BUILDER,
@@ -164,7 +164,7 @@ public class AggregateStarTableRule extends RelOptRule {
             + aggregate.getGroupSet());
       }
       assert tileKey.dimensions.contains(aggregate.getGroupSet());
-      final List<AggregateCall> aggCalls = Lists.newArrayList();
+      final List<AggregateCall> aggCalls = new ArrayList<>();
       ImmutableBitSet.Builder groupSet = ImmutableBitSet.builder();
       for (int key : aggregate.getGroupSet()) {
         groupSet.set(tileKey.dimensions.indexOf(key));
@@ -242,7 +242,7 @@ public class AggregateStarTableRule extends RelOptRule {
     // Second, try to satisfy the aggregation based on group set columns.
   tryGroup:
     {
-      List<Integer> newArgs = Lists.newArrayList();
+      List<Integer> newArgs = new ArrayList<>();
       for (Integer arg : aggregateCall.getArgList()) {
         int z = tileKey.dimensions.indexOf(arg);
         if (z < 0) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionAggregateRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionAggregateRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionAggregateRule.java
index a15d74a..f65bb7f 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionAggregateRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionAggregateRule.java
@@ -77,7 +77,7 @@ public class AggregateUnionAggregateRule extends RelOptRule {
       RelBuilderFactory relBuilderFactory,
       String desc) {
     super(
-        operand(aggregateClass, null, Aggregate.IS_SIMPLE,
+        operandJ(aggregateClass, null, Aggregate::isSimple,
             operand(unionClass,
                 operand(firstUnionInputClass, any()),
                 operand(secondUnionInputClass, any()))),

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java
index abc5fbe..2372205 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateUnionTransposeRule.java
@@ -39,8 +39,8 @@ import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
@@ -147,7 +147,7 @@ public class AggregateUnionTransposeRule extends RelOptRule {
 
   private List<AggregateCall> transformAggCalls(RelNode input, int groupCount,
       List<AggregateCall> origCalls) {
-    final List<AggregateCall> newCalls = Lists.newArrayList();
+    final List<AggregateCall> newCalls = new ArrayList<>();
     for (Ord<AggregateCall> ord : Ord.zip(origCalls)) {
       final AggregateCall origCall = ord.e;
       if (origCall.isDistinct()

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/AggregateValuesRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/AggregateValuesRule.java b/core/src/main/java/org/apache/calcite/rel/rules/AggregateValuesRule.java
index db31937..d61cb95 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/AggregateValuesRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/AggregateValuesRule.java
@@ -28,7 +28,6 @@ import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 
 import java.math.BigDecimal;
@@ -64,8 +63,10 @@ public class AggregateValuesRule extends RelOptRule {
    */
   public AggregateValuesRule(RelBuilderFactory relBuilderFactory) {
     super(
-        operand(Aggregate.class, null, Predicates.not(Aggregate.IS_NOT_GRAND_TOTAL),
-            operand(Values.class, null, Values.IS_EMPTY, none())),
+        operandJ(Aggregate.class, null,
+            aggregate -> aggregate.getGroupCount() == 0,
+            operandJ(Values.class, null,
+                values -> values.getTuples().isEmpty(), none())),
         relBuilderFactory, null);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/CalcRelSplitter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/CalcRelSplitter.java b/core/src/main/java/org/apache/calcite/rel/rules/CalcRelSplitter.java
index f3b03a9..51826bf 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/CalcRelSplitter.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/CalcRelSplitter.java
@@ -126,7 +126,7 @@ public abstract class CalcRelSplitter {
     // expressions to the left.
     assert program.isValid(Litmus.THROW, null);
     final List<RexNode> exprList = program.getExprList();
-    final RexNode[] exprs = exprList.toArray(new RexNode[exprList.size()]);
+    final RexNode[] exprs = exprList.toArray(new RexNode[0]);
     assert !RexUtil.containComplexExprs(exprList);
 
     // Figure out what level each expression belongs to.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/DateRangeRules.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/DateRangeRules.java b/core/src/main/java/org/apache/calcite/rel/rules/DateRangeRules.java
index fac9f02..ae51560 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/DateRangeRules.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/DateRangeRules.java
@@ -30,7 +30,6 @@ import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexShuttle;
 import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.rex.RexVisitorImpl;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.runtime.SqlFunctions;
 import org.apache.calcite.sql.SqlBinaryOperator;
 import org.apache.calcite.sql.SqlKind;
@@ -44,8 +43,6 @@ import org.apache.calcite.util.TimestampWithTimeZoneString;
 import org.apache.calcite.util.Util;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.BoundType;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -64,8 +61,10 @@ import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.TimeZone;
+import java.util.function.Predicate;
 
 /**
  * Collection of planner rules that convert
@@ -92,17 +91,15 @@ public abstract class DateRangeRules {
   private DateRangeRules() {}
 
   private static final Predicate<Filter> FILTER_PREDICATE =
-      new PredicateImpl<Filter>() {
-        @Override public boolean test(Filter filter) {
-          try (ExtractFinder finder = ExtractFinder.THREAD_INSTANCES.get()) {
-            assert finder.timeUnits.isEmpty() && finder.opKinds.isEmpty()
-                : "previous user did not clean up";
-            filter.getCondition().accept(finder);
-            // bail out if there is no EXTRACT of YEAR, or call to FLOOR or CEIL
-            return finder.timeUnits.contains(TimeUnitRange.YEAR)
-                || finder.opKinds.contains(SqlKind.FLOOR)
-                || finder.opKinds.contains(SqlKind.CEIL);
-          }
+      filter -> {
+        try (ExtractFinder finder = ExtractFinder.THREAD_INSTANCES.get()) {
+          assert finder.timeUnits.isEmpty() && finder.opKinds.isEmpty()
+              : "previous user did not clean up";
+          filter.getCondition().accept(finder);
+          // bail out if there is no EXTRACT of YEAR, or call to FLOOR or CEIL
+          return finder.timeUnits.contains(TimeUnitRange.YEAR)
+              || finder.opKinds.contains(SqlKind.FLOOR)
+              || finder.opKinds.contains(SqlKind.CEIL);
         }
       };
 
@@ -174,7 +171,7 @@ public abstract class DateRangeRules {
   @SuppressWarnings("WeakerAccess")
   public static class FilterDateRangeRule extends RelOptRule {
     public FilterDateRangeRule(RelBuilderFactory relBuilderFactory) {
-      super(operand(Filter.class, null, FILTER_PREDICATE, any()),
+      super(operandJ(Filter.class, null, FILTER_PREDICATE, any()),
           relBuilderFactory, "FilterDateRangeRule");
     }
 
@@ -205,11 +202,7 @@ public abstract class DateRangeRules {
     private final Set<SqlKind> opKinds = EnumSet.noneOf(SqlKind.class);
 
     private static final ThreadLocal<ExtractFinder> THREAD_INSTANCES =
-        new ThreadLocal<ExtractFinder>() {
-          @Override protected ExtractFinder initialValue() {
-            return new ExtractFinder();
-          }
-        };
+        ThreadLocal.withInitial(ExtractFinder::new);
 
     private ExtractFinder() {
       super(true);
@@ -253,12 +246,12 @@ public abstract class DateRangeRules {
     ExtractShuttle(RexBuilder rexBuilder, TimeUnitRange timeUnit,
         Map<String, RangeSet<Calendar>> operandRanges,
         ImmutableSortedSet<TimeUnitRange> timeUnitRanges, String timeZone) {
-      this.rexBuilder = Preconditions.checkNotNull(rexBuilder);
-      this.timeUnit = Preconditions.checkNotNull(timeUnit);
+      this.rexBuilder = Objects.requireNonNull(rexBuilder);
+      this.timeUnit = Objects.requireNonNull(timeUnit);
       Bug.upgrade("Change type to Map<RexNode, RangeSet<Calendar>> when"
           + " [CALCITE-1367] is fixed");
-      this.operandRanges = Preconditions.checkNotNull(operandRanges);
-      this.timeUnitRanges = Preconditions.checkNotNull(timeUnitRanges);
+      this.operandRanges = Objects.requireNonNull(operandRanges);
+      this.timeUnitRanges = Objects.requireNonNull(timeUnitRanges);
       this.timeZone = timeZone;
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/FilterAggregateTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/FilterAggregateTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/FilterAggregateTransposeRule.java
index f65d874..9501e74 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/FilterAggregateTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/FilterAggregateTransposeRule.java
@@ -34,8 +34,8 @@ import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -103,8 +103,8 @@ public class FilterAggregateTransposeRule extends RelOptRule {
       adjustments[j] = i - j;
       j++;
     }
-    final List<RexNode> pushedConditions = Lists.newArrayList();
-    final List<RexNode> remainingConditions = Lists.newArrayList();
+    final List<RexNode> pushedConditions = new ArrayList<>();
+    final List<RexNode> remainingConditions = new ArrayList<>();
 
     for (RexNode condition : conditions) {
       ImmutableBitSet rCols = RelOptUtil.InputFinder.bits(condition);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/FilterJoinRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/FilterJoinRule.java b/core/src/main/java/org/apache/calcite/rel/rules/FilterJoinRule.java
index 0bb3830..9d06e50 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/FilterJoinRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/FilterJoinRule.java
@@ -33,14 +33,15 @@ import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Objects;
+
+import static org.apache.calcite.plan.RelOptUtil.conjunctions;
 
 /**
  * Planner rule that pushes filters above and
@@ -49,12 +50,7 @@ import java.util.List;
 public abstract class FilterJoinRule extends RelOptRule {
   /** Predicate that always returns true. With this predicate, every filter
    * will be pushed into the ON clause. */
-  public static final Predicate TRUE_PREDICATE =
-      new Predicate() {
-        public boolean apply(Join join, JoinRelType joinType, RexNode exp) {
-          return true;
-        }
-      };
+  public static final Predicate TRUE_PREDICATE = (join, joinType, exp) -> true;
 
   /** Rule that pushes predicates from a Filter into the Join below them. */
   public static final FilterJoinRule FILTER_ON_JOIN =
@@ -90,7 +86,7 @@ public abstract class FilterJoinRule extends RelOptRule {
       boolean smart, RelBuilderFactory relBuilderFactory, Predicate predicate) {
     super(operand, relBuilderFactory, "FilterJoinRule:" + id);
     this.smart = smart;
-    this.predicate = Preconditions.checkNotNull(predicate);
+    this.predicate = Objects.requireNonNull(predicate);
   }
 
   /**
@@ -136,8 +132,8 @@ public abstract class FilterJoinRule extends RelOptRule {
 
     final List<RexNode> aboveFilters =
         filter != null
-            ? RelOptUtil.conjunctions(filter.getCondition())
-            : Lists.<RexNode>newArrayList();
+            ? conjunctions(filter.getCondition())
+            : new ArrayList<>();
     final ImmutableList<RexNode> origAboveFilters =
         ImmutableList.copyOf(aboveFilters);
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/FilterTableScanRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/FilterTableScanRule.java b/core/src/main/java/org/apache/calcite/rel/rules/FilterTableScanRule.java
index 1a52eec..7e597b0 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/FilterTableScanRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/FilterTableScanRule.java
@@ -27,7 +27,6 @@ import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.core.TableScan;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexUtil;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.FilterableTable;
 import org.apache.calcite.schema.ProjectableFilterableTable;
 import org.apache.calcite.tools.RelBuilderFactory;
@@ -35,7 +34,6 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 
 /**
@@ -52,22 +50,17 @@ import com.google.common.collect.ImmutableList;
  * @see org.apache.calcite.rel.rules.ProjectTableScanRule
  */
 public abstract class FilterTableScanRule extends RelOptRule {
-  public static final Predicate<TableScan> PREDICATE =
-      new PredicateImpl<TableScan>() {
-        public boolean test(TableScan scan) {
-          // We can only push filters into a FilterableTable or
-          // ProjectableFilterableTable.
-          final RelOptTable table = scan.getTable();
-          return table.unwrap(FilterableTable.class) != null
-              || table.unwrap(ProjectableFilterableTable.class) != null;
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<TableScan> PREDICATE =
+      FilterTableScanRule::test;
 
   /** Rule that matches Filter on TableScan. */
   public static final FilterTableScanRule INSTANCE =
       new FilterTableScanRule(
           operand(Filter.class,
-              operand(TableScan.class, null, PREDICATE, none())),
+              operandJ(TableScan.class, null, FilterTableScanRule::test,
+                  none())),
           RelFactories.LOGICAL_BUILDER,
           "FilterTableScanRule") {
         public void onMatch(RelOptRuleCall call) {
@@ -82,7 +75,8 @@ public abstract class FilterTableScanRule extends RelOptRule {
       new FilterTableScanRule(
           operand(Filter.class,
               operand(EnumerableInterpreter.class,
-                  operand(TableScan.class, null, PREDICATE, none()))),
+                  operandJ(TableScan.class, null, FilterTableScanRule::test,
+                      none()))),
           RelFactories.LOGICAL_BUILDER,
           "FilterTableScanRule:interpreter") {
         public void onMatch(RelOptRuleCall call) {
@@ -107,6 +101,14 @@ public abstract class FilterTableScanRule extends RelOptRule {
 
   //~ Methods ----------------------------------------------------------------
 
+  public static boolean test(TableScan scan) {
+    // We can only push filters into a FilterableTable or
+    // ProjectableFilterableTable.
+    final RelOptTable table = scan.getTable();
+    return table.unwrap(FilterableTable.class) != null
+        || table.unwrap(ProjectableFilterableTable.class) != null;
+  }
+
   protected void apply(RelOptRuleCall call, Filter filter, TableScan scan) {
     final ImmutableIntList projects;
     final ImmutableList.Builder<RexNode> filters = ImmutableList.builder();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/JoinAssociateRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/JoinAssociateRule.java b/core/src/main/java/org/apache/calcite/rel/rules/JoinAssociateRule.java
index ad6b3c6..b3e9f99 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/JoinAssociateRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/JoinAssociateRule.java
@@ -32,8 +32,7 @@ import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.collect.Lists;
-
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -119,8 +118,8 @@ public class JoinAssociateRule extends RelOptRule {
 
     // Split the condition of topJoin and bottomJoin into a conjunctions. A
     // condition can be pushed down if it does not use columns from A.
-    final List<RexNode> top = Lists.newArrayList();
-    final List<RexNode> bottom = Lists.newArrayList();
+    final List<RexNode> top = new ArrayList<>();
+    final List<RexNode> bottom = new ArrayList<>();
     JoinPushThroughJoinRule.split(topJoin.getCondition(), aBitSet, top, bottom);
     JoinPushThroughJoinRule.split(bottomJoin.getCondition(), aBitSet, top,
         bottom);
@@ -134,7 +133,7 @@ public class JoinAssociateRule extends RelOptRule {
             aCount + bCount + cCount,
             0, aCount, bCount,
             bCount, aCount + bCount, cCount);
-    final List<RexNode> newBottomList = Lists.newArrayList();
+    final List<RexNode> newBottomList = new ArrayList<>();
     new RexPermuteInputsShuttle(bottomMapping, relB, relC)
         .visitList(bottom, newBottomList);
     RexNode newBottomCondition =

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/JoinProjectTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/JoinProjectTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/JoinProjectTransposeRule.java
index 39b4ef6..6e53ec2 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/JoinProjectTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/JoinProjectTransposeRule.java
@@ -187,7 +187,7 @@ public class JoinProjectTransposeRule extends RelOptRule {
             JoinRelType.INNER,
             joinRel.getCluster().getTypeFactory(),
             null,
-            Collections.<RelDataTypeField>emptyList());
+            Collections.emptyList());
 
     // Create projection expressions, combining the projection expressions
     // from the projects that feed into the join.  For the RHS projection

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/JoinToMultiJoinRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/JoinToMultiJoinRule.java b/core/src/main/java/org/apache/calcite/rel/rules/JoinToMultiJoinRule.java
index 90a98bf..52e5ed0 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/JoinToMultiJoinRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/JoinToMultiJoinRule.java
@@ -36,9 +36,9 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Pair;
 
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -134,8 +134,8 @@ public class JoinToMultiJoinRule extends RelOptRule {
 
     // combine the children MultiJoin inputs into an array of inputs
     // for the new MultiJoin
-    final List<ImmutableBitSet> projFieldsList = Lists.newArrayList();
-    final List<int[]> joinFieldRefCountsList = Lists.newArrayList();
+    final List<ImmutableBitSet> projFieldsList = new ArrayList<>();
+    final List<int[]> joinFieldRefCountsList = new ArrayList<>();
     final List<RelNode> newInputs =
         combineInputs(
             origJoin,
@@ -147,7 +147,7 @@ public class JoinToMultiJoinRule extends RelOptRule {
     // combine the outer join information from the left and right
     // inputs, and include the outer join information from the current
     // join, if it's a left/right outer join
-    final List<Pair<JoinRelType, RexNode>> joinSpecs = Lists.newArrayList();
+    final List<Pair<JoinRelType, RexNode>> joinSpecs = new ArrayList<>();
     combineOuterJoins(
         origJoin,
         newInputs,
@@ -206,7 +206,7 @@ public class JoinToMultiJoinRule extends RelOptRule {
       RelNode right,
       List<ImmutableBitSet> projFieldsList,
       List<int[]> joinFieldRefCountsList) {
-    final List<RelNode> newInputs = Lists.newArrayList();
+    final List<RelNode> newInputs = new ArrayList<>();
 
     // leave the null generating sides of an outer join intact; don't
     // pull up those children inputs into the array we're constructing
@@ -390,7 +390,7 @@ public class JoinToMultiJoinRule extends RelOptRule {
     // AND the join condition if this isn't a left or right outer join;
     // in those cases, the outer join condition is already tracked
     // separately
-    final List<RexNode> filters = Lists.newArrayList();
+    final List<RexNode> filters = new ArrayList<>();
     if ((joinType != JoinRelType.LEFT) && (joinType != JoinRelType.RIGHT)) {
       filters.add(joinRel.getCondition());
     }
@@ -481,7 +481,7 @@ public class JoinToMultiJoinRule extends RelOptRule {
     joinCondition.accept(new InputReferenceCounter(joinCondRefCounts));
 
     // first, make a copy of the ref counters
-    final Map<Integer, int[]> refCountsMap = Maps.newHashMap();
+    final Map<Integer, int[]> refCountsMap = new HashMap<>();
     int nInputs = multiJoinInputs.size();
     int currInput = 0;
     for (int[] origRefCounts : origJoinFieldRefCounts) {
@@ -532,7 +532,7 @@ public class JoinToMultiJoinRule extends RelOptRule {
       Join joinRel,
       RelNode left,
       RelNode right) {
-    final List<RexNode> filters = Lists.newArrayList();
+    final List<RexNode> filters = new ArrayList<>();
     if (right instanceof MultiJoin) {
       final MultiJoin multiRight = (MultiJoin) right;
       filters.add(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/LoptJoinTree.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/LoptJoinTree.java b/core/src/main/java/org/apache/calcite/rel/rules/LoptJoinTree.java
index 126659b..5765d69 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/LoptJoinTree.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/LoptJoinTree.java
@@ -19,10 +19,9 @@ package org.apache.calcite.rel.rules;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Join;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Utility class used to store a {@link org.apache.calcite.rel.core.Join} tree
@@ -134,7 +133,7 @@ public class LoptJoinTree {
   }
 
   public List<Integer> getTreeOrder() {
-    List<Integer> treeOrder = Lists.newArrayList();
+    List<Integer> treeOrder = new ArrayList<>();
     getTreeOrder(treeOrder);
     return treeOrder;
   }
@@ -157,7 +156,7 @@ public class LoptJoinTree {
     private final LoptJoinTree parent;
 
     protected BinaryTree(LoptJoinTree parent) {
-      this.parent = Preconditions.checkNotNull(parent);
+      this.parent = Objects.requireNonNull(parent);
     }
 
     public LoptJoinTree getParent() {
@@ -195,8 +194,8 @@ public class LoptJoinTree {
 
     public Node(BinaryTree left, BinaryTree right, LoptJoinTree parent) {
       super(parent);
-      this.left = Preconditions.checkNotNull(left);
-      this.right = Preconditions.checkNotNull(right);
+      this.left = Objects.requireNonNull(left);
+      this.right = Objects.requireNonNull(right);
     }
 
     public BinaryTree getLeft() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/LoptMultiJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/LoptMultiJoin.java b/core/src/main/java/org/apache/calcite/rel/rules/LoptMultiJoin.java
index 7d865bf..ba86639 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/LoptMultiJoin.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/LoptMultiJoin.java
@@ -34,7 +34,6 @@ import org.apache.calcite.util.ImmutableIntList;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
 import java.util.ArrayList;
 import java.util.BitSet;
@@ -462,8 +461,8 @@ public class LoptMultiJoin {
    * references
    */
   private void setJoinFilterRefs() {
-    fieldsRefByJoinFilter = Maps.newHashMap();
-    factorsRefByJoinFilter = Maps.newHashMap();
+    fieldsRefByJoinFilter = new HashMap<>();
+    factorsRefByJoinFilter = new HashMap<>();
     ListIterator<RexNode> filterIter = allJoinFilters.listIterator();
     while (filterIter.hasNext()) {
       RexNode joinFilter = filterIter.next();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/LoptOptimizeJoinRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/LoptOptimizeJoinRule.java b/core/src/main/java/org/apache/calcite/rel/rules/LoptOptimizeJoinRule.java
index e17ac1e..5a25d63 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/LoptOptimizeJoinRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/LoptOptimizeJoinRule.java
@@ -47,8 +47,6 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.mapping.IntPair;
 
-import com.google.common.collect.Lists;
-
 import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.HashMap;
@@ -298,7 +296,7 @@ public class LoptOptimizeJoinRule extends RelOptRule {
     sortedFactors.addAll(simpleFactors.keySet());
     final Map<Integer, Integer> selfJoinPairs = new HashMap<>();
     Integer [] factors =
-        sortedFactors.toArray(new Integer[sortedFactors.size()]);
+        sortedFactors.toArray(new Integer[0]);
     for (int i = 0; i < factors.length; i++) {
       if (repeatedTables.contains(simpleFactors.get(factors[i]))) {
         continue;
@@ -493,7 +491,7 @@ public class LoptOptimizeJoinRule extends RelOptRule {
       LoptMultiJoin multiJoin,
       LoptJoinTree joinTree,
       List<String> fieldNames) {
-    List<RexNode> newProjExprs = Lists.newArrayList();
+    List<RexNode> newProjExprs = new ArrayList<>();
     RexBuilder rexBuilder =
         multiJoin.getMultiJoinRel().getCluster().getRexBuilder();
 
@@ -1633,7 +1631,7 @@ public class LoptOptimizeJoinRule extends RelOptRule {
     List<RelDataTypeField> newFields =
         multiJoin.getJoinFactor(factorToAdd).getRowType().getFieldList();
     final int nNewFields = newFields.size();
-    List<Pair<RexNode, String>> projects = Lists.newArrayList();
+    List<Pair<RexNode, String>> projects = new ArrayList<>();
     RexBuilder rexBuilder = currJoinRel.getCluster().getRexBuilder();
     RelDataTypeFactory typeFactory = rexBuilder.getTypeFactory();
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/MaterializedViewFilterScanRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/MaterializedViewFilterScanRule.java b/core/src/main/java/org/apache/calcite/rel/rules/MaterializedViewFilterScanRule.java
index b382f52..88e752b 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/MaterializedViewFilterScanRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/MaterializedViewFilterScanRule.java
@@ -74,7 +74,7 @@ public class MaterializedViewFilterScanRule extends RelOptRule {
     List<RelOptMaterialization> materializations =
         (planner instanceof VolcanoPlanner)
             ? ((VolcanoPlanner) planner).getMaterializations()
-            : ImmutableList.<RelOptMaterialization>of();
+            : ImmutableList.of();
     if (!materializations.isEmpty()) {
       RelNode root = filter.copy(filter.getTraitSet(),
           Collections.singletonList((RelNode) scan));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/MultiJoinOptimizeBushyRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/MultiJoinOptimizeBushyRule.java b/core/src/main/java/org/apache/calcite/rel/rules/MultiJoinOptimizeBushyRule.java
index a482904..bdaeb05 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/MultiJoinOptimizeBushyRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/MultiJoinOptimizeBushyRule.java
@@ -36,14 +36,17 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.io.PrintWriter;
+import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Objects;
+
+import static org.apache.calcite.rel.rules.LoptMultiJoin.Edge;
+import static org.apache.calcite.util.mapping.Mappings.TargetMapping;
 
 /**
  * Planner rule that finds an approximately optimal ordering for join operators
@@ -92,7 +95,7 @@ public class MultiJoinOptimizeBushyRule extends RelOptRule {
 
     final LoptMultiJoin multiJoin = new LoptMultiJoin(multiJoinRel);
 
-    final List<Vertex> vertexes = Lists.newArrayList();
+    final List<Vertex> vertexes = new ArrayList<>();
     int x = 0;
     for (int i = 0; i < multiJoin.getNumJoinFactors(); i++) {
       final RelNode rel = multiJoin.getJoinFactor(i);
@@ -102,7 +105,7 @@ public class MultiJoinOptimizeBushyRule extends RelOptRule {
     }
     assert x == multiJoin.getNumTotalFields();
 
-    final List<LoptMultiJoin.Edge> unusedEdges = Lists.newArrayList();
+    final List<Edge> unusedEdges = new ArrayList<>();
     for (RexNode node : multiJoin.getJoinFilters()) {
       unusedEdges.add(multiJoin.createEdge(node));
     }
@@ -124,7 +127,7 @@ public class MultiJoinOptimizeBushyRule extends RelOptRule {
           }
         };
 
-    final List<LoptMultiJoin.Edge> usedEdges = Lists.newArrayList();
+    final List<Edge> usedEdges = new ArrayList<>();
     for (;;) {
       final int edgeOrdinal = chooseBestEdge(unusedEdges, edgeComparator);
       if (pw != null) {
@@ -174,7 +177,7 @@ public class MultiJoinOptimizeBushyRule extends RelOptRule {
               .set(v)
               .build();
 
-      final List<RexNode> conditions = Lists.newArrayList();
+      final List<RexNode> conditions = new ArrayList<>();
       final Iterator<LoptMultiJoin.Edge> edgeIterator = unusedEdges.iterator();
       while (edgeIterator.hasNext()) {
         LoptMultiJoin.Edge edge = edgeIterator.next();
@@ -223,7 +226,7 @@ public class MultiJoinOptimizeBushyRule extends RelOptRule {
     }
 
     // We have a winner!
-    List<Pair<RelNode, Mappings.TargetMapping>> relNodes = Lists.newArrayList();
+    List<Pair<RelNode, TargetMapping>> relNodes = new ArrayList<>();
     for (Vertex vertex : vertexes) {
       if (vertex instanceof LeafVertex) {
         LeafVertex leafVertex = (LeafVertex) vertex;
@@ -372,7 +375,7 @@ public class MultiJoinOptimizeBushyRule extends RelOptRule {
       super(id, factors, cost);
       this.leftFactor = leftFactor;
       this.rightFactor = rightFactor;
-      this.conditions = Preconditions.checkNotNull(conditions);
+      this.conditions = Objects.requireNonNull(conditions);
     }
 
     @Override public String toString() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectCorrelateTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectCorrelateTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectCorrelateTransposeRule.java
index 67d9402..adeac9e 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectCorrelateTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectCorrelateTransposeRule.java
@@ -46,8 +46,7 @@ import java.util.Map;
 public class ProjectCorrelateTransposeRule  extends RelOptRule {
 
   public static final ProjectCorrelateTransposeRule INSTANCE =
-      new ProjectCorrelateTransposeRule(
-          PushProjector.ExprCondition.TRUE,
+      new ProjectCorrelateTransposeRule(expr -> true,
           RelFactories.LOGICAL_BUILDER);
 
   //~ Instance fields --------------------------------------------------------


[08/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/Matchers.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/Matchers.java b/core/src/test/java/org/apache/calcite/test/Matchers.java
index 5ea3a4e..0b5e6bd 100644
--- a/core/src/test/java/org/apache/calcite/test/Matchers.java
+++ b/core/src/test/java/org/apache/calcite/test/Matchers.java
@@ -20,10 +20,7 @@ import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
 import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 
 import org.hamcrest.BaseMatcher;
@@ -37,9 +34,12 @@ import org.hamcrest.core.Is;
 
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
 
 /**
  * Matchers for testing SQL queries.
@@ -74,7 +74,7 @@ public class Matchers {
       }
 
       protected boolean matchesSafely(ResultSet resultSet) {
-        final List<String> actualList = Lists.newArrayList();
+        final List<String> actualList = new ArrayList<>();
         try {
           CalciteAssert.toStringList(resultSet, actualList);
           resultSet.close();
@@ -119,7 +119,9 @@ public class Matchers {
   }
 
   private static <E> Iterable<String> toStringList(Iterable<E> items) {
-    return Iterables.transform(items, Functions.toStringFunction());
+    return StreamSupport.stream(items.spliterator(), false)
+        .map(Object::toString)
+        .collect(Util.toImmutableList());
   }
 
   /**
@@ -156,12 +158,7 @@ public class Matchers {
    */
   @Factory
   public static Matcher<String> isLinux(final String value) {
-    return compose(Is.is(value),
-        new Function<String, String>() {
-          public String apply(String input) {
-            return input == null ? null : Util.toLinux(input);
-          }
-        });
+    return compose(Is.is(value), input -> input == null ? null : Util.toLinux(input));
   }
 
   /**
@@ -171,13 +168,10 @@ public class Matchers {
    */
   @Factory
   public static Matcher<RelNode> hasTree(final String value) {
-    return compose(Is.is(value),
-        new Function<RelNode, String>() {
-          public String apply(RelNode input) {
-            // Convert RelNode to a string with Linux line-endings
-            return Util.toLinux(RelOptUtil.toString(input));
-          }
-        });
+    return compose(Is.is(value), input -> {
+      // Convert RelNode to a string with Linux line-endings
+      return Util.toLinux(RelOptUtil.toString(input));
+    });
   }
 
   /**
@@ -198,12 +192,7 @@ public class Matchers {
    */
   @Factory
   public static Matcher<String> containsStringLinux(String value) {
-    return compose(CoreMatchers.containsString(value),
-        new Function<String, String>() {
-          public String apply(String input) {
-            return Util.toLinux(input);
-          }
-        });
+    return compose(CoreMatchers.containsString(value), Util::toLinux);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/MaterializationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/MaterializationTest.java b/core/src/test/java/org/apache/calcite/test/MaterializationTest.java
index e1b314c..b32ec74 100644
--- a/core/src/test/java/org/apache/calcite/test/MaterializationTest.java
+++ b/core/src/test/java/org/apache/calcite/test/MaterializationTest.java
@@ -54,7 +54,6 @@ import org.apache.calcite.util.Smalls;
 import org.apache.calcite.util.TryThreadLocal;
 import org.apache.calcite.util.mapping.IntPair;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Ordering;
 
@@ -69,6 +68,7 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
@@ -84,11 +84,11 @@ import static org.junit.Assert.assertTrue;
  * and checks that the materialization is used.
  */
 public class MaterializationTest {
-  private static final Function<ResultSet, Void> CONTAINS_M0 =
+  private static final Consumer<ResultSet> CONTAINS_M0 =
       CalciteAssert.checkResultContains(
           "EnumerableTableScan(table=[[hr, m0]])");
 
-  private static final Function<ResultSet, Void> CONTAINS_LOCATIONS =
+  private static final Consumer<ResultSet> CONTAINS_LOCATIONS =
       CalciteAssert.checkResultContains(
           "EnumerableTableScan(table=[[hr, locations]])");
 
@@ -184,7 +184,7 @@ public class MaterializationTest {
    * definition. */
   private void checkMaterialize(String materialize, String query) {
     checkMaterialize(materialize, query, HR_FKUK_MODEL, CONTAINS_M0,
-        RuleSets.ofList(ImmutableList.<RelOptRule>of()));
+        RuleSets.ofList(ImmutableList.of()));
   }
 
   /** Checks that a given query can use a materialized view with a given
@@ -196,14 +196,14 @@ public class MaterializationTest {
   /** Checks that a given query can use a materialized view with a given
    * definition. */
   private void checkMaterialize(String materialize, String query, String model,
-      Function<ResultSet, Void> explainChecker) {
+      Consumer<ResultSet> explainChecker) {
     checkMaterialize(materialize, query, model, explainChecker,
-        RuleSets.ofList(ImmutableList.<RelOptRule>of()));
+        RuleSets.ofList(ImmutableList.of()));
   }
 
 
   private void checkMaterialize(String materialize, String query, String model,
-      Function<ResultSet, Void> explainChecker, final RuleSet rules) {
+      Consumer<ResultSet> explainChecker, final RuleSet rules) {
     checkThatMaterialize(materialize, query, "m0", false, model, explainChecker,
         rules).sameResultWithMaterializationsDisabled();
   }
@@ -212,7 +212,7 @@ public class MaterializationTest {
    * definition. */
   private CalciteAssert.AssertQuery checkThatMaterialize(String materialize,
       String query, String name, boolean existing, String model,
-      Function<ResultSet, Void> explainChecker, final RuleSet rules) {
+      Consumer<ResultSet> explainChecker, final RuleSet rules) {
     try (final TryThreadLocal.Memo ignored = Prepare.THREAD_TRIM.push(true)) {
       MaterializationService.setThreadLocal();
       CalciteAssert.AssertQuery that = CalciteAssert.that()
@@ -222,12 +222,9 @@ public class MaterializationTest {
 
       // Add any additional rules required for the test
       if (rules.iterator().hasNext()) {
-        that.withHook(Hook.PLANNER, new Function<RelOptPlanner, Void>() {
-          public Void apply(RelOptPlanner planner) {
-            for (RelOptRule rule : rules) {
-              planner.addRule(rule);
-            }
-            return null;
+        that.withHook(Hook.PLANNER, (Consumer<RelOptPlanner>) planner -> {
+          for (RelOptRule rule : rules) {
+            planner.addRule(rule);
           }
         });
       }
@@ -1955,7 +1952,7 @@ public class MaterializationTest {
         HR_FKUK_MODEL,
         CalciteAssert.checkResultContains(
             "EnumerableValues(tuples=[[{ 'noname' }]])"),
-        RuleSets.ofList(ImmutableList.<RelOptRule>of()))
+        RuleSets.ofList(ImmutableList.of()))
         .returnsValue("noname");
   }
 
@@ -1984,13 +1981,8 @@ public class MaterializationTest {
           .withMaterializations(HR_FKUK_MODEL,
               "m0", m)
           .query(q)
-          .withHook(Hook.SUB,
-              new Function<RelNode, Void>() {
-                public Void apply(RelNode input) {
-                  substitutedNames.add(new TableNameVisitor().run(input));
-                  return null;
-                }
-              })
+          .withHook(Hook.SUB, (Consumer<RelNode>) r ->
+              substitutedNames.add(new TableNameVisitor().run(r)))
           .enableMaterializations(true)
           .explainContains("hr, m0");
     } catch (Exception e) {
@@ -2008,17 +2000,14 @@ public class MaterializationTest {
       MaterializationService.setThreadLocal();
       CalciteAssert.that()
           .withMaterializations(
-              HR_FKUK_MODEL,
-              new Function<JsonBuilder, List<Object>>() {
-                public List<Object> apply(JsonBuilder builder) {
-                  final Map<String, Object> map = builder.map();
-                  map.put("table", "locations");
-                  String sql = "select `deptno` as `empid`, '' as `name`\n"
-                      + "from `emps`";
-                  final String sql2 = sql.replaceAll("`", "\"");
-                  map.put("sql", sql2);
-                  return ImmutableList.<Object>of(map);
-                }
+              HR_FKUK_MODEL, builder -> {
+                final Map<String, Object> map = builder.map();
+                map.put("table", "locations");
+                String sql = "select `deptno` as `empid`, '' as `name`\n"
+                    + "from `emps`";
+                final String sql2 = sql.replaceAll("`", "\"");
+                map.put("sql", sql2);
+                return ImmutableList.of(map);
               })
           .query(q)
           .enableMaterializations(true)
@@ -2228,16 +2217,11 @@ public class MaterializationTest {
               "m0", "select * from \"emps\" where \"empid\" < 300",
               "m1", "select * from \"emps\" where \"empid\" < 600")
           .query(q)
-          .withHook(Hook.SUB,
-              new Function<RelNode, Void>() {
-                public Void apply(RelNode input) {
-                  substitutedNames.add(new TableNameVisitor().run(input));
-                  return null;
-                }
-              })
+          .withHook(Hook.SUB, (Consumer<RelNode>) r ->
+              substitutedNames.add(new TableNameVisitor().run(r)))
           .enableMaterializations(true)
           .sameResultWithMaterializationsDisabled();
-      Collections.sort(substitutedNames, CASE_INSENSITIVE_LIST_LIST_COMPARATOR);
+      substitutedNames.sort(CASE_INSENSITIVE_LIST_LIST_COMPARATOR);
       assertThat(substitutedNames, is(list3(expectedNames)));
     }
   }
@@ -2273,16 +2257,11 @@ public class MaterializationTest {
               "m1", "select * from \"emps\" where \"empid\" < 600",
               "m2", "select * from \"m1\"")
           .query(q)
-          .withHook(Hook.SUB,
-              new Function<RelNode, Void>() {
-                public Void apply(RelNode input) {
-                  substitutedNames.add(new TableNameVisitor().run(input));
-                  return null;
-                }
-              })
+          .withHook(Hook.SUB, (Consumer<RelNode>) r ->
+              substitutedNames.add(new TableNameVisitor().run(r)))
           .enableMaterializations(true)
           .sameResultWithMaterializationsDisabled();
-      Collections.sort(substitutedNames, CASE_INSENSITIVE_LIST_LIST_COMPARATOR);
+      substitutedNames.sort(CASE_INSENSITIVE_LIST_LIST_COMPARATOR);
       assertThat(substitutedNames, is(list3(expectedNames)));
     }
   }
@@ -2342,7 +2321,7 @@ public class MaterializationTest {
     public final Department[] depts = {
         new Department(10, "Sales", Arrays.asList(emps[0], emps[2], emps[3]),
             new Location(-122, 38)),
-        new Department(30, "Marketing", Collections.<Employee>emptyList(),
+        new Department(30, "Marketing", ImmutableList.of(),
             new Location(0, 52)),
         new Department(20, "HR", Collections.singletonList(emps[1]), null),
     };

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/MockCatalogReader.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/MockCatalogReader.java b/core/src/test/java/org/apache/calcite/test/MockCatalogReader.java
index df1bffe..663a98e 100644
--- a/core/src/test/java/org/apache/calcite/test/MockCatalogReader.java
+++ b/core/src/test/java/org/apache/calcite/test/MockCatalogReader.java
@@ -99,9 +99,6 @@ import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
 
 import java.lang.reflect.Type;
 import java.math.BigDecimal;
@@ -110,12 +107,10 @@ import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -149,7 +144,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
       boolean caseSensitive) {
     super(CalciteSchema.createRootSchema(false, true, DEFAULT_CATALOG),
         SqlNameMatchers.withCaseSensitive(caseSensitive),
-        ImmutableList.of(PREFIX, ImmutableList.<String>of()),
+        ImmutableList.of(PREFIX, ImmutableList.of()),
         typeFactory, null);
   }
 
@@ -677,7 +672,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
 
   private static List<RelCollation> deduceMonotonicity(
       Prepare.PreparingTable table) {
-    final List<RelCollation> collationList = Lists.newArrayList();
+    final List<RelCollation> collationList = new ArrayList<>();
 
     // Deduce which fields the table is sorted on.
     int i = -1;
@@ -708,7 +703,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
 
   /** Mock schema. */
   public static class MockSchema {
-    private final List<String> tableNames = Lists.newArrayList();
+    private final List<String> tableNames = new ArrayList<>();
     private String name;
 
     public MockSchema(String name) {
@@ -744,7 +739,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
     protected RelDataType rowType;
     protected List<RelCollation> collationList;
     protected final List<String> names;
-    protected final Set<String> monotonicColumnSet = Sets.newHashSet();
+    protected final Set<String> monotonicColumnSet = new HashSet<>();
     protected StructKind kind = StructKind.FULLY_QUALIFIED;
     protected final ColumnResolver resolver;
     protected final InitializerExpressionFactory initializerFactory;
@@ -1149,7 +1144,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
         final ImmutableList.Builder<Pair<String, Schema>> builder =
             ImmutableList.builder();
         for (String name : fromTable.names) {
-          builder.add(Pair.<String, Schema>of(name, null));
+          builder.add(Pair.of(name, null));
         }
         return Schemas.path(builder.build());
       }
@@ -1404,8 +1399,8 @@ public class MockCatalogReader extends CalciteCatalogReader {
   /** ColumnResolver implementation that resolves CompoundNameColumn by simulating
    *  Phoenix behaviors. */
   private static final class CompoundNameColumnResolver implements ColumnResolver {
-    private final Map<String, Integer> nameMap = Maps.newHashMap();
-    private final Map<String, Map<String, Integer>> groupMap = Maps.newHashMap();
+    private final Map<String, Integer> nameMap = new HashMap<>();
+    private final Map<String, Map<String, Integer>> groupMap = new HashMap<>();
     private final String defaultColumnGroup;
 
     CompoundNameColumnResolver(
@@ -1415,7 +1410,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
         nameMap.put(column.e.getName(), column.i);
         Map<String, Integer> subMap = groupMap.get(column.e.first);
         if (subMap == null) {
-          subMap = Maps.newHashMap();
+          subMap = new HashMap<>();
           groupMap.put(column.e.first, subMap);
         }
         subMap.put(column.e.second, column.i);
@@ -1478,14 +1473,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
         if (subMap != null) {
           List<Map.Entry<String, Integer>> entries =
               new ArrayList<>(subMap.entrySet());
-          Collections.sort(
-              entries,
-              new Comparator<Map.Entry<String, Integer>>() {
-                @Override public int compare(
-                    Entry<String, Integer> o1, Entry<String, Integer> o2) {
-                  return o1.getValue() - o2.getValue();
-                }
-              });
+          entries.sort((o1, o2) -> o1.getValue() - o2.getValue());
           ret.add(
               new Pair<RelDataTypeField, List<String>>(
                   new RelDataTypeFieldImpl(
@@ -1575,8 +1563,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
     }
 
     @Override public boolean rolledUpColumnValidInsideAgg(String column,
-                                                          SqlCall call, SqlNode parent,
-                                                          CalciteConnectionConfig config) {
+        SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
       // For testing
       return call.getKind() != SqlKind.MAX
               && (parent.getKind() == SqlKind.SELECT || parent.getKind() == SqlKind.FILTER);
@@ -1723,11 +1710,7 @@ public class MockCatalogReader extends CalciteCatalogReader {
    * value. */
   public static class CountingFactory extends NullInitializerExpressionFactory {
     static final ThreadLocal<AtomicInteger> THREAD_CALL_COUNT =
-        new ThreadLocal<AtomicInteger>() {
-          protected AtomicInteger initialValue() {
-            return new AtomicInteger();
-          }
-        };
+        ThreadLocal.withInitial(AtomicInteger::new);
 
     private final List<String> defaultColumns;
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/MockRelOptPlanner.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/MockRelOptPlanner.java b/core/src/test/java/org/apache/calcite/test/MockRelOptPlanner.java
index d35c019..77c8427 100644
--- a/core/src/test/java/org/apache/calcite/test/MockRelOptPlanner.java
+++ b/core/src/test/java/org/apache/calcite/test/MockRelOptPlanner.java
@@ -76,7 +76,7 @@ public class MockRelOptPlanner extends AbstractRelOptPlanner {
 
   public List<RelOptRule> getRules() {
     return rule == null
-        ? ImmutableList.<RelOptRule>of() : ImmutableList.of(rule);
+        ? ImmutableList.of() : ImmutableList.of(rule);
   }
 
   public boolean addRule(RelOptRule rule) {
@@ -126,7 +126,7 @@ public class MockRelOptPlanner extends AbstractRelOptPlanner {
           new MockRuleCall(
               this,
               rule.getOperand(),
-              bindings.toArray(new RelNode[bindings.size()]));
+              bindings.toArray(new RelNode[0]));
       if (rule.matches(call)) {
         rule.onMatch(call);
       }
@@ -229,7 +229,7 @@ public class MockRelOptPlanner extends AbstractRelOptPlanner {
           planner,
           operand,
           rels,
-          Collections.<RelNode, List<RelNode>>emptyMap());
+          Collections.emptyMap());
     }
 
     // implement RelOptRuleCall

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/MultiJdbcSchemaJoinTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/MultiJdbcSchemaJoinTest.java b/core/src/test/java/org/apache/calcite/test/MultiJdbcSchemaJoinTest.java
index a97b1f9..e9c2795 100644
--- a/core/src/test/java/org/apache/calcite/test/MultiJdbcSchemaJoinTest.java
+++ b/core/src/test/java/org/apache/calcite/test/MultiJdbcSchemaJoinTest.java
@@ -32,6 +32,7 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.util.HashSet;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
 import javax.sql.DataSource;
@@ -159,7 +160,7 @@ public class MultiJdbcSchemaJoinTest {
 
       // Run the actual query
       rs = stmt.executeQuery(query);
-      Set<Integer> ids = Sets.newHashSet();
+      Set<Integer> ids = new HashSet<>();
       while (rs.next()) {
         ids.add(rs.getInt(1));
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/MutableRelTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/MutableRelTest.java b/core/src/test/java/org/apache/calcite/test/MutableRelTest.java
index f99d8c1..a2158f0 100644
--- a/core/src/test/java/org/apache/calcite/test/MutableRelTest.java
+++ b/core/src/test/java/org/apache/calcite/test/MutableRelTest.java
@@ -77,7 +77,7 @@ public class MutableRelTest {
         "Calc",
         "select * from emp where ename = 'DUMMY'",
         false,
-        ImmutableList.<RelOptRule>of(FilterToCalcRule.INSTANCE));
+        ImmutableList.of(FilterToCalcRule.INSTANCE));
   }
 
   @Test public void testConvertWindow() {
@@ -85,7 +85,7 @@ public class MutableRelTest {
         "Window",
         "select sal, avg(sal) over (partition by deptno) from emp",
         false,
-        ImmutableList.<RelOptRule>of(ProjectToWindowRule.PROJECT));
+        ImmutableList.of(ProjectToWindowRule.PROJECT));
   }
 
   @Test public void testConvertCollect() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/QuidemTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/QuidemTest.java b/core/src/test/java/org/apache/calcite/test/QuidemTest.java
index 20e47b3..e70c7e9 100644
--- a/core/src/test/java/org/apache/calcite/test/QuidemTest.java
+++ b/core/src/test/java/org/apache/calcite/test/QuidemTest.java
@@ -32,7 +32,6 @@ import org.apache.calcite.util.Bug;
 import org.apache.calcite.util.Closer;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 import com.google.common.io.PatternFilenameFilter;
 
@@ -53,6 +52,7 @@ import java.sql.DriverManager;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
+import java.util.function.Function;
 
 import static org.junit.Assert.fail;
 
@@ -70,6 +70,26 @@ public abstract class QuidemTest {
     this.method = findMethod(path);
   }
 
+  private static Object getEnv(String varName) {
+    switch (varName) {
+    case "jdk18":
+      return System.getProperty("java.version").startsWith("1.8");
+    case "fixed":
+      // Quidem requires a Guava function
+      return (com.google.common.base.Function<String, Object>) v -> {
+        switch (v) {
+        case "calcite1045":
+          return Bug.CALCITE_1045_FIXED;
+        case "calcite1048":
+          return Bug.CALCITE_1048_FIXED;
+        }
+        return null;
+      };
+    default:
+      return null;
+    }
+  }
+
   private Method findMethod(String path) {
     // E.g. path "sql/agg.iq" gives method "testSqlAgg"
     String methodName =
@@ -103,11 +123,7 @@ public abstract class QuidemTest {
           : "f: " + f.getAbsolutePath() + "; base: " + base;
       paths.add(f.getAbsolutePath().substring(base.length()));
     }
-    return Lists.transform(paths, new Function<String, Object[]>() {
-      public Object[] apply(String path) {
-        return new Object[] {path};
-      }
-    });
+    return Lists.transform(paths, path -> new Object[] {path});
   }
 
   protected void checkRun(String path) throws Exception {
@@ -136,19 +152,17 @@ public abstract class QuidemTest {
     try (final Reader reader = Util.reader(inFile);
          final Writer writer = Util.printWriter(outFile);
          final Closer closer = new Closer()) {
-      new Quidem(reader, writer, env(), createConnectionFactory())
-          .withPropertyHandler(new Quidem.PropertyHandler() {
-            public void onSet(String propertyName, Object value) {
-              if (propertyName.equals("bindable")) {
-                final boolean b = value instanceof Boolean
-                    && (Boolean) value;
-                closer.add(Hook.ENABLE_BINDABLE.addThread(Hook.property(b)));
-              }
-              if (propertyName.equals("expand")) {
-                final boolean b = value instanceof Boolean
-                    && (Boolean) value;
-                closer.add(Prepare.THREAD_EXPAND.push(b));
-              }
+      new Quidem(reader, writer, QuidemTest::getEnv, createConnectionFactory())
+          .withPropertyHandler((propertyName, value) -> {
+            if (propertyName.equals("bindable")) {
+              final boolean b = value instanceof Boolean
+                  && (Boolean) value;
+              closer.add(Hook.ENABLE_BINDABLE.addThread(Hook.propertyJ(b)));
+            }
+            if (propertyName.equals("expand")) {
+              final boolean b = value instanceof Boolean
+                  && (Boolean) value;
+              closer.add(Prepare.THREAD_EXPAND.push(b));
             }
           })
           .execute();
@@ -179,31 +193,6 @@ public abstract class QuidemTest {
         : s;
   }
 
-  private Function<String, Object> env() {
-    return new Function<String, Object>() {
-      public Object apply(String varName) {
-        switch (varName) {
-        case "jdk18":
-          return System.getProperty("java.version").startsWith("1.8");
-        case "fixed":
-          return new Function<String, Object>() {
-            public Object apply(String v) {
-              switch (v) {
-              case "calcite1045":
-                return Bug.CALCITE_1045_FIXED;
-              case "calcite1048":
-                return Bug.CALCITE_1048_FIXED;
-              }
-              return null;
-            }
-          };
-        default:
-          return null;
-        }
-      }
-    };
-  }
-
   @Test public void test() throws Exception {
     if (method != null) {
       method.invoke(this);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/ReflectiveSchemaTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/ReflectiveSchemaTest.java b/core/src/test/java/org/apache/calcite/test/ReflectiveSchemaTest.java
index b5a256b..824276b 100644
--- a/core/src/test/java/org/apache/calcite/test/ReflectiveSchemaTest.java
+++ b/core/src/test/java/org/apache/calcite/test/ReflectiveSchemaTest.java
@@ -25,7 +25,6 @@ import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.QueryProvider;
 import org.apache.calcite.linq4j.function.Function1;
-import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.ParameterExpression;
 import org.apache.calcite.linq4j.tree.Primitive;
@@ -37,7 +36,6 @@ import org.apache.calcite.schema.impl.ViewTable;
 import org.apache.calcite.util.Smalls;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 
 import org.junit.Assert;
@@ -104,14 +102,14 @@ public class ReflectiveSchemaTest {
                 "asQueryable"),
             Employee.class)
             .where(
-                Expressions.<Predicate1<Employee>>lambda(
+                Expressions.lambda(
                     Expressions.lessThan(
                         Expressions.field(
                             e, "empid"),
                         Expressions.constant(160)),
                     e))
             .where(
-                Expressions.<Predicate1<Employee>>lambda(
+                Expressions.lambda(
                     Expressions.greaterThan(
                         Expressions.field(
                             e, "empid"),
@@ -339,105 +337,99 @@ public class ReflectiveSchemaTest {
           "select " + fn + "(\"" + field.getName() + "\") as c\n"
               + "from \"s\".\"everyTypes\"")
           .returns(
-              new Function<ResultSet, Void>() {
-                public Void apply(ResultSet input) {
-                  int n = 0;
-                  try {
-                    while (input.next()) {
-                      final Object o = get(input);
-                      Util.discard(o);
-                      ++n;
-                    }
-                  } catch (SQLException e) {
-                    throw new RuntimeException(e);
-                  }
-                  assertThat(n, equalTo(1));
-                  return null;
-                }
-
-                private Object get(ResultSet input) throws SQLException {
-                  final int type = input.getMetaData().getColumnType(1);
-                  switch (type) {
-                  case java.sql.Types.BOOLEAN:
-                    return input.getBoolean(1);
-                  case java.sql.Types.TINYINT:
-                    return input.getByte(1);
-                  case java.sql.Types.SMALLINT:
-                    return input.getShort(1);
-                  case java.sql.Types.INTEGER:
-                    return input.getInt(1);
-                  case java.sql.Types.BIGINT:
-                    return input.getLong(1);
-                  case java.sql.Types.REAL:
-                    return input.getFloat(1);
-                  case java.sql.Types.DOUBLE:
-                    return input.getDouble(1);
-                  case java.sql.Types.CHAR:
-                  case java.sql.Types.VARCHAR:
-                    return input.getString(1);
-                  case java.sql.Types.DATE:
-                    return input.getDate(1);
-                  case java.sql.Types.TIME:
-                    return input.getTime(1);
-                  case java.sql.Types.TIMESTAMP:
-                    return input.getTimestamp(1);
-                  default:
-                    throw new AssertionError(type);
+              input -> {
+                int n = 0;
+                try {
+                  while (input.next()) {
+                    final Object o = get(input);
+                    Util.discard(o);
+                    ++n;
                   }
+                } catch (SQLException e) {
+                  throw new RuntimeException(e);
                 }
+                assertThat(n, equalTo(1));
               });
     }
   }
 
+  private Object get(ResultSet input) throws SQLException {
+    final int type = input.getMetaData().getColumnType(1);
+    switch (type) {
+    case java.sql.Types.BOOLEAN:
+      return input.getBoolean(1);
+    case java.sql.Types.TINYINT:
+      return input.getByte(1);
+    case java.sql.Types.SMALLINT:
+      return input.getShort(1);
+    case java.sql.Types.INTEGER:
+      return input.getInt(1);
+    case java.sql.Types.BIGINT:
+      return input.getLong(1);
+    case java.sql.Types.REAL:
+      return input.getFloat(1);
+    case java.sql.Types.DOUBLE:
+      return input.getDouble(1);
+    case java.sql.Types.CHAR:
+    case java.sql.Types.VARCHAR:
+      return input.getString(1);
+    case java.sql.Types.DATE:
+      return input.getDate(1);
+    case java.sql.Types.TIME:
+      return input.getTime(1);
+    case java.sql.Types.TIMESTAMP:
+      return input.getTimestamp(1);
+    default:
+      throw new AssertionError(type);
+    }
+  }
+
   @Test public void testClassNames() throws Exception {
     CalciteAssert.that()
         .withSchema("s", CATCHALL).query("select * from \"s\".\"everyTypes\"")
         .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet input) {
-                try {
-                  final ResultSetMetaData metaData = input.getMetaData();
-                  check(metaData, "primitiveBoolean", Boolean.class);
-                  check(metaData, "primitiveByte", Byte.class);
-                  check(metaData, "primitiveChar", String.class);
-                  check(metaData, "primitiveShort", Short.class);
-                  check(metaData, "primitiveInt", Integer.class);
-                  check(metaData, "primitiveLong", Long.class);
-                  check(metaData, "primitiveFloat", Float.class);
-                  check(metaData, "primitiveDouble", Double.class);
-                  check(metaData, "wrapperBoolean", Boolean.class);
-                  check(metaData, "wrapperByte", Byte.class);
-                  check(metaData, "wrapperCharacter", String.class);
-                  check(metaData, "wrapperShort", Short.class);
-                  check(metaData, "wrapperInteger", Integer.class);
-                  check(metaData, "wrapperLong", Long.class);
-                  check(metaData, "wrapperFloat", Float.class);
-                  check(metaData, "wrapperDouble", Double.class);
-                  check(metaData, "sqlDate", java.sql.Date.class);
-                  check(metaData, "sqlTime", Time.class);
-                  check(metaData, "sqlTimestamp", Timestamp.class);
-                  check(metaData, "utilDate", Timestamp.class);
-                  check(metaData, "string", String.class);
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-
-              private void check(ResultSetMetaData metaData, String columnName,
-                  Class expectedType) throws SQLException {
-                for (int i = 1; i <= metaData.getColumnCount(); i++) {
-                  if (metaData.getColumnName(i).equals(columnName)) {
-                    assertThat(metaData.getColumnClassName(i),
-                        equalTo(expectedType.getName()));
-                    return;
-                  }
-                }
-                Assert.fail("column not found: " + columnName);
+            resultSet -> {
+              try {
+                final ResultSetMetaData metaData = resultSet.getMetaData();
+                check(metaData, "primitiveBoolean", Boolean.class);
+                check(metaData, "primitiveByte", Byte.class);
+                check(metaData, "primitiveChar", String.class);
+                check(metaData, "primitiveShort", Short.class);
+                check(metaData, "primitiveInt", Integer.class);
+                check(metaData, "primitiveLong", Long.class);
+                check(metaData, "primitiveFloat", Float.class);
+                check(metaData, "primitiveDouble", Double.class);
+                check(metaData, "wrapperBoolean", Boolean.class);
+                check(metaData, "wrapperByte", Byte.class);
+                check(metaData, "wrapperCharacter", String.class);
+                check(metaData, "wrapperShort", Short.class);
+                check(metaData, "wrapperInteger", Integer.class);
+                check(metaData, "wrapperLong", Long.class);
+                check(metaData, "wrapperFloat", Float.class);
+                check(metaData, "wrapperDouble", Double.class);
+                check(metaData, "sqlDate", java.sql.Date.class);
+                check(metaData, "sqlTime", Time.class);
+                check(metaData, "sqlTimestamp", Timestamp.class);
+                check(metaData, "utilDate", Timestamp.class);
+                check(metaData, "string", String.class);
+              } catch (SQLException e) {
+                throw new RuntimeException(e);
               }
             });
   }
 
+  private void check(ResultSetMetaData metaData, String columnName,
+      Class expectedType) throws SQLException {
+    for (int i = 1; i <= metaData.getColumnCount(); i++) {
+      if (metaData.getColumnName(i).equals(columnName)) {
+        assertThat(metaData.getColumnClassName(i),
+            equalTo(expectedType.getName()));
+        return;
+      }
+    }
+    Assert.fail("column not found: " + columnName);
+  }
+
   @Test public void testJavaBoolean() throws Exception {
     final CalciteAssert.AssertThat with =
         CalciteAssert.that().withSchema("s", CATCHALL);
@@ -553,7 +545,7 @@ public class ReflectiveSchemaTest {
             + " " + fn + " " + name2 + " as c\n"
             + "from \"s\".\"everyTypes\"\n"
             + "where " + name + " <> 0")
-            .returns(CalciteAssert.<ResultSet, Void>constantNull());
+            .returns(resultSet -> { });
       }
     }
   }
@@ -571,23 +563,19 @@ public class ReflectiveSchemaTest {
   @Test public void testAvgInt() throws Exception {
     CalciteAssert.that().withSchema("s", CATCHALL).with(Lex.JAVA)
         .query("select primitiveLong, avg(primitiveInt)\n"
-                + "from s.everyTypes\n"
-                + "group by primitiveLong order by primitiveLong")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet input) {
-                StringBuilder buf = new StringBuilder();
-                try {
-                  while (input.next()) {
-                    buf.append(input.getInt(2)).append("\n");
-                  }
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                assertThat(buf.toString(), equalTo("0\n2147483647\n"));
-                return null;
-              }
-            });
+            + "from s.everyTypes\n"
+            + "group by primitiveLong order by primitiveLong")
+        .returns(input -> {
+          StringBuilder buf = new StringBuilder();
+          try {
+            while (input.next()) {
+              buf.append(input.getInt(2)).append("\n");
+            }
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+          assertThat(buf.toString(), equalTo("0\n2147483647\n"));
+        });
   }
 
   private static boolean isNumeric(Class type) {
@@ -836,12 +824,7 @@ public class ReflectiveSchemaTest {
 
     static Enumerable<Field> numericFields() {
       return fields()
-          .where(
-              new Predicate1<Field>() {
-                public boolean apply(Field v1) {
-                  return isNumeric(v1.getType());
-                }
-              });
+          .where(v1 -> isNumeric(v1.getType()));
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java b/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
index 1f166f2..cb87d19 100644
--- a/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
+++ b/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
@@ -1724,7 +1724,7 @@ public class RelBuilderTest {
     final RelBuilder builder = RelBuilder.create(config().build());
     final RelNode root =
         builder.scan("EMP")
-            .sortLimit(0, -1, ImmutableList.<RexNode>of())
+            .sortLimit(0, -1, ImmutableList.of())
             .build();
     final String expected = "LogicalTableScan(table=[[scott, EMP]])\n";
     assertThat(root, hasTree(expected));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/RelMetadataTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/RelMetadataTest.java b/core/src/test/java/org/apache/calcite/test/RelMetadataTest.java
index 9da50f2..7b090d5 100644
--- a/core/src/test/java/org/apache/calcite/test/RelMetadataTest.java
+++ b/core/src/test/java/org/apache/calcite/test/RelMetadataTest.java
@@ -21,7 +21,6 @@ import org.apache.calcite.linq4j.tree.Types;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptPlanner;
 import org.apache.calcite.plan.RelOptPredicateList;
-import org.apache.calcite.plan.RelOptSchema;
 import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.rel.InvalidRelException;
 import org.apache.calcite.rel.RelCollation;
@@ -35,7 +34,6 @@ import org.apache.calcite.rel.RelRoot;
 import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.AggregateCall;
 import org.apache.calcite.rel.core.Correlate;
-import org.apache.calcite.rel.core.CorrelationId;
 import org.apache.calcite.rel.core.Filter;
 import org.apache.calcite.rel.core.Join;
 import org.apache.calcite.rel.core.JoinRelType;
@@ -78,7 +76,6 @@ import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexTableInputRef;
 import org.apache.calcite.rex.RexTableInputRef.RelTableRef;
-import org.apache.calcite.schema.SchemaPlus;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlSpecialOperator;
@@ -93,11 +90,9 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.SaffronProperties;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
 import com.google.common.collect.Sets;
 
@@ -899,7 +894,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final RelMetadataQuery mq = RelMetadataQuery.instance();
     Set<ImmutableBitSet> result = mq.getUniqueKeys(rel);
     assertThat(result,
-        CoreMatchers.<Set<ImmutableBitSet>>equalTo(
+        CoreMatchers.equalTo(
             ImmutableSet.of(ImmutableBitSet.of())));
     assertUniqueConsistent(rel);
   }
@@ -909,7 +904,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final RelMetadataQuery mq = RelMetadataQuery.instance();
     final Set<ImmutableBitSet> result = mq.getUniqueKeys(rel);
     assertThat(result,
-        CoreMatchers.<Set<ImmutableBitSet>>equalTo(
+        CoreMatchers.equalTo(
             ImmutableSet.of(ImmutableBitSet.of())));
     assertUniqueConsistent(rel);
   }
@@ -920,7 +915,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final RelMetadataQuery mq = RelMetadataQuery.instance();
     final Set<ImmutableBitSet> result = mq.getUniqueKeys(rel);
     assertThat(result,
-        CoreMatchers.<Set<ImmutableBitSet>>equalTo(
+        CoreMatchers.equalTo(
             ImmutableSet.of(ImmutableBitSet.of(0))));
     assertUniqueConsistent(rel);
   }
@@ -932,28 +927,25 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final RelMetadataQuery mq = RelMetadataQuery.instance();
     final Set<ImmutableBitSet> result = mq.getUniqueKeys(rel);
     assertThat(result,
-        CoreMatchers.<Set<ImmutableBitSet>>equalTo(
+        CoreMatchers.equalTo(
             ImmutableSet.of(ImmutableBitSet.of(0))));
     assertUniqueConsistent(rel);
   }
 
   @Test public void testBrokenCustomProvider() {
-    final List<String> buf = Lists.newArrayList();
+    final List<String> buf = new ArrayList<>();
     ColTypeImpl.THREAD_LIST.set(buf);
 
     final String sql = "select deptno, count(*) from emp where deptno > 10 "
         + "group by deptno having count(*) = 0";
     final RelRoot root = tester
-        .withClusterFactory(
-            new Function<RelOptCluster, RelOptCluster>() {
-              public RelOptCluster apply(RelOptCluster cluster) {
-                cluster.setMetadataProvider(
-                    ChainedRelMetadataProvider.of(
-                        ImmutableList.of(BrokenColTypeImpl.SOURCE,
-                            cluster.getMetadataProvider())));
-                return cluster;
-              }
-            })
+        .withClusterFactory(cluster -> {
+          cluster.setMetadataProvider(
+              ChainedRelMetadataProvider.of(
+                  ImmutableList.of(BrokenColTypeImpl.SOURCE,
+                      cluster.getMetadataProvider())));
+          return cluster;
+        })
         .convertSqlToRel(sql);
 
     final RelNode rel = root.rel;
@@ -981,25 +973,22 @@ public class RelMetadataTest extends SqlToRelTestBase {
   }
 
   @Test public void testCustomProvider() {
-    final List<String> buf = Lists.newArrayList();
+    final List<String> buf = new ArrayList<>();
     ColTypeImpl.THREAD_LIST.set(buf);
 
     final String sql = "select deptno, count(*) from emp where deptno > 10 "
         + "group by deptno having count(*) = 0";
     final RelRoot root = tester
-        .withClusterFactory(
-            new Function<RelOptCluster, RelOptCluster>() {
-              public RelOptCluster apply(RelOptCluster cluster) {
-                // Create a custom provider that includes ColType.
-                // Include the same provider twice just to be devious.
-                final ImmutableList<RelMetadataProvider> list =
-                    ImmutableList.of(ColTypeImpl.SOURCE, ColTypeImpl.SOURCE,
-                        cluster.getMetadataProvider());
-                cluster.setMetadataProvider(
-                    ChainedRelMetadataProvider.of(list));
-                return cluster;
-              }
-            })
+        .withClusterFactory(cluster -> {
+          // Create a custom provider that includes ColType.
+          // Include the same provider twice just to be devious.
+          final ImmutableList<RelMetadataProvider> list =
+              ImmutableList.of(ColTypeImpl.SOURCE, ColTypeImpl.SOURCE,
+                  cluster.getMetadataProvider());
+          cluster.setMetadataProvider(
+              ChainedRelMetadataProvider.of(list));
+          return cluster;
+        })
         .convertSqlToRel(sql);
     final RelNode rel = root.rel;
 
@@ -1056,15 +1045,10 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final Join join = (Join) rel.getInput();
     final RelOptTable empTable = join.getInput(0).getTable();
     final RelOptTable deptTable = join.getInput(1).getTable();
-    Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Void>() {
-          public Void apply(RelOptCluster cluster,
-              RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            checkCollation(cluster, empTable, deptTable);
-            return null;
-          }
-        });
+    Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+      checkCollation(cluster, empTable, deptTable);
+      return null;
+    });
   }
 
   private void checkCollation(RelOptCluster cluster, RelOptTable empTable,
@@ -1130,7 +1114,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
 
     // Values (empty)
     collations = RelMdCollation.values(mq, empTable.getRowType(),
-        ImmutableList.<ImmutableList<RexLiteral>>of());
+        ImmutableList.of());
     assertThat(collations.toString(),
         equalTo("[[0, 1, 2, 3, 4, 5, 6, 7, 8], "
             + "[1, 2, 3, 4, 5, 6, 7, 8], "
@@ -1175,54 +1159,50 @@ public class RelMetadataTest extends SqlToRelTestBase {
    * {@link org.apache.calcite.rel.metadata.RelMdColumnUniqueness#areColumnsUnique}
    * applied to {@link Values}. */
   @Test public void testColumnUniquenessForValues() {
-    Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Void>() {
-          public Void apply(RelOptCluster cluster, RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            final RexBuilder rexBuilder = cluster.getRexBuilder();
-            final RelMetadataQuery mq = RelMetadataQuery.instance();
-            final RelDataType rowType = cluster.getTypeFactory().builder()
-                .add("a", SqlTypeName.INTEGER)
-                .add("b", SqlTypeName.VARCHAR)
-                .build();
-            final ImmutableList.Builder<ImmutableList<RexLiteral>> tuples =
-                ImmutableList.builder();
-            addRow(tuples, rexBuilder, 1, "X");
-            addRow(tuples, rexBuilder, 2, "Y");
-            addRow(tuples, rexBuilder, 3, "X");
-            addRow(tuples, rexBuilder, 4, "X");
-
-            final LogicalValues values =
-                LogicalValues.create(cluster, rowType, tuples.build());
-
-            final ImmutableBitSet colNone = ImmutableBitSet.of();
-            final ImmutableBitSet col0 = ImmutableBitSet.of(0);
-            final ImmutableBitSet col1 = ImmutableBitSet.of(1);
-            final ImmutableBitSet colAll = ImmutableBitSet.of(0, 1);
-
-            assertThat(mq.areColumnsUnique(values, col0), is(true));
-            assertThat(mq.areColumnsUnique(values, col1), is(false));
-            assertThat(mq.areColumnsUnique(values, colAll), is(true));
-            assertThat(mq.areColumnsUnique(values, colNone), is(false));
-
-            // Repeat the above tests directly against the handler.
-            final RelMdColumnUniqueness handler =
-                (RelMdColumnUniqueness) RelMdColumnUniqueness.SOURCE
-                    .handlers(BuiltInMetadata.ColumnUniqueness.DEF)
-                    .get(BuiltInMethod.COLUMN_UNIQUENESS.method)
-                    .iterator().next();
-            assertThat(handler.areColumnsUnique(values, mq, col0, false),
-                is(true));
-            assertThat(handler.areColumnsUnique(values, mq, col1, false),
-                is(false));
-            assertThat(handler.areColumnsUnique(values, mq, colAll, false),
-                is(true));
-            assertThat(handler.areColumnsUnique(values, mq, colNone, false),
-                is(false));
-
-            return null;
-          }
-        });
+    Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+      final RexBuilder rexBuilder = cluster.getRexBuilder();
+      final RelMetadataQuery mq = RelMetadataQuery.instance();
+      final RelDataType rowType = cluster.getTypeFactory().builder()
+          .add("a", SqlTypeName.INTEGER)
+          .add("b", SqlTypeName.VARCHAR)
+          .build();
+      final ImmutableList.Builder<ImmutableList<RexLiteral>> tuples =
+          ImmutableList.builder();
+      addRow(tuples, rexBuilder, 1, "X");
+      addRow(tuples, rexBuilder, 2, "Y");
+      addRow(tuples, rexBuilder, 3, "X");
+      addRow(tuples, rexBuilder, 4, "X");
+
+      final LogicalValues values =
+          LogicalValues.create(cluster, rowType, tuples.build());
+
+      final ImmutableBitSet colNone = ImmutableBitSet.of();
+      final ImmutableBitSet col0 = ImmutableBitSet.of(0);
+      final ImmutableBitSet col1 = ImmutableBitSet.of(1);
+      final ImmutableBitSet colAll = ImmutableBitSet.of(0, 1);
+
+      assertThat(mq.areColumnsUnique(values, col0), is(true));
+      assertThat(mq.areColumnsUnique(values, col1), is(false));
+      assertThat(mq.areColumnsUnique(values, colAll), is(true));
+      assertThat(mq.areColumnsUnique(values, colNone), is(false));
+
+      // Repeat the above tests directly against the handler.
+      final RelMdColumnUniqueness handler =
+          (RelMdColumnUniqueness) RelMdColumnUniqueness.SOURCE
+              .handlers(BuiltInMetadata.ColumnUniqueness.DEF)
+              .get(BuiltInMethod.COLUMN_UNIQUENESS.method)
+              .iterator().next();
+      assertThat(handler.areColumnsUnique(values, mq, col0, false),
+          is(true));
+      assertThat(handler.areColumnsUnique(values, mq, col1, false),
+          is(false));
+      assertThat(handler.areColumnsUnique(values, mq, colAll, false),
+          is(true));
+      assertThat(handler.areColumnsUnique(values, mq, colNone, false),
+          is(false));
+
+      return null;
+    });
   }
 
   private void addRow(ImmutableList.Builder<ImmutableList<RexLiteral>> builder,
@@ -1253,15 +1233,10 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final Join join = (Join) rel.getInput();
     final RelOptTable empTable = join.getInput(0).getTable();
     final RelOptTable deptTable = join.getInput(1).getTable();
-    Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Void>() {
-          public Void apply(RelOptCluster cluster,
-              RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            checkAverageRowSize(cluster, empTable, deptTable);
-            return null;
-          }
-        });
+    Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+      checkAverageRowSize(cluster, empTable, deptTable);
+      return null;
+    });
   }
 
   private void checkAverageRowSize(RelOptCluster cluster, RelOptTable empTable,
@@ -1312,7 +1287,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
 
     // Union
     final LogicalUnion union =
-        LogicalUnion.create(ImmutableList.<RelNode>of(empScan, emptyValues),
+        LogicalUnion.create(ImmutableList.of(empScan, emptyValues),
             true);
     rowSize = mq.getAverageRowSize(union);
     columnSizes = mq.getAverageColumnSizes(union);
@@ -1356,7 +1331,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
     // Join
     final LogicalJoin join =
         LogicalJoin.create(empScan, deptProject, rexBuilder.makeLiteral(true),
-            ImmutableSet.<CorrelationId>of(), JoinRelType.INNER);
+            ImmutableSet.of(), JoinRelType.INNER);
     rowSize = mq.getAverageRowSize(join);
     columnSizes = mq.getAverageColumnSizes(join);
     assertThat(columnSizes.size(), equalTo(13));
@@ -1369,7 +1344,7 @@ public class RelMetadataTest extends SqlToRelTestBase {
     // Aggregate
     final LogicalAggregate aggregate =
         LogicalAggregate.create(join, ImmutableBitSet.of(2, 0),
-            ImmutableList.<ImmutableBitSet>of(),
+            ImmutableList.of(),
             ImmutableList.of(
                 AggregateCall.create(SqlStdOperatorTable.COUNT,
                     false, false, ImmutableIntList.of(),
@@ -1397,15 +1372,10 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final Join join = (Join) rel.getInput();
     final RelOptTable empTable = join.getInput(0).getTable();
     final RelOptTable deptTable = join.getInput(1).getTable();
-    Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Void>() {
-          public Void apply(RelOptCluster cluster,
-              RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            checkPredicates(cluster, empTable, deptTable);
-            return null;
-          }
-        });
+    Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+      checkPredicates(cluster, empTable, deptTable);
+      return null;
+    });
   }
 
   private void checkPredicates(RelOptCluster cluster, RelOptTable empTable,
@@ -1898,15 +1868,10 @@ public class RelMetadataTest extends SqlToRelTestBase {
     final Join join = (Join) rel.getInput();
     final RelOptTable empTable = join.getInput(0).getTable();
     final RelOptTable deptTable = join.getInput(1).getTable();
-    Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Void>() {
-          public Void apply(RelOptCluster cluster,
-              RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            checkAllPredicates(cluster, empTable, deptTable);
-            return null;
-          }
-        });
+    Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+      checkAllPredicates(cluster, empTable, deptTable);
+      return null;
+    });
   }
 
   private void checkAllPredicates(RelOptCluster cluster, RelOptTable empTable,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java b/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java
index 282449f..07dd0b0 100644
--- a/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java
+++ b/core/src/test/java/org/apache/calcite/test/RelOptRulesTest.java
@@ -35,7 +35,6 @@ import org.apache.calcite.rel.RelRoot;
 import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.CorrelationId;
 import org.apache.calcite.rel.core.Intersect;
-import org.apache.calcite.rel.core.Join;
 import org.apache.calcite.rel.core.JoinRelType;
 import org.apache.calcite.rel.core.Minus;
 import org.apache.calcite.rel.core.Project;
@@ -110,7 +109,6 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.runtime.Hook;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SemiJoinType;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
@@ -120,23 +118,23 @@ import org.apache.calcite.sql2rel.SqlToRelConverter;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import static org.apache.calcite.plan.RelOptRule.none;
-import static org.apache.calcite.plan.RelOptRule.operand;
-
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import org.junit.Ignore;
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Properties;
+import java.util.function.Predicate;
 
-import javax.annotation.Nullable;
+import static org.apache.calcite.plan.RelOptRule.none;
+import static org.apache.calcite.plan.RelOptRule.operand;
+import static org.apache.calcite.plan.RelOptRule.operandJ;
 
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
 
 /**
  * Unit test for rules in {@code org.apache.calcite.rel} and subpackages.
@@ -181,19 +179,9 @@ import static org.junit.Assert.assertTrue;
 public class RelOptRulesTest extends RelOptTestBase {
   //~ Methods ----------------------------------------------------------------
 
-  private final PushProjector.ExprCondition skipItem = new PushProjector.ExprCondition() {
-
-    @Override public boolean apply(RexNode rexNode) {
-      return false;
-    }
-    @Override public boolean test(RexNode expr) {
-      if (expr instanceof RexCall) {
-        RexCall call = (RexCall) expr;
-        return "item".equalsIgnoreCase(call.getOperator().getName());
-      }
-      return false;
-    }
-  };
+  private final PushProjector.ExprCondition skipItem = expr ->
+      expr instanceof RexCall
+          && "item".equalsIgnoreCase(((RexCall) expr).getOperator().getName());
 
   protected DiffRepository getDiffRepos() {
     return DiffRepository.lookup(RelOptRulesTest.class);
@@ -466,11 +454,7 @@ public class RelOptRulesTest extends RelOptTestBase {
             .addRuleInstance(ProjectMergeRule.INSTANCE)
             .build();
     final FilterJoinRule.Predicate predicate =
-        new FilterJoinRule.Predicate() {
-          public boolean apply(Join join, JoinRelType joinType, RexNode exp) {
-            return joinType != JoinRelType.INNER;
-          }
-        };
+        (join, joinType, exp) -> joinType != JoinRelType.INNER;
     final FilterJoinRule join =
         new FilterJoinRule.JoinConditionPushRule(RelBuilder.proto(), predicate);
     final FilterJoinRule filterOnJoin =
@@ -1195,7 +1179,7 @@ public class RelOptRulesTest extends RelOptTestBase {
 
   @Test public void testProjectCorrelateTranspose() {
     ProjectCorrelateTransposeRule customPCTrans =
-        new ProjectCorrelateTransposeRule(PushProjector.ExprCondition.TRUE,
+        new ProjectCorrelateTransposeRule(expr -> true,
             RelFactories.LOGICAL_BUILDER);
 
     checkPlanning(customPCTrans,
@@ -1993,30 +1977,26 @@ public class RelOptRulesTest extends RelOptTestBase {
 
   private void checkPlanning(String query) throws Exception {
     final Tester tester1 = tester.withCatalogReaderFactory(
-        new Function<RelDataTypeFactory, Prepare.CatalogReader>() {
-          public Prepare.CatalogReader apply(RelDataTypeFactory typeFactory) {
-            return new MockCatalogReader(typeFactory, true) {
-              @Override public MockCatalogReader init() {
-                // CREATE SCHEMA abc;
-                // CREATE TABLE a(a INT);
-                // ...
-                // CREATE TABLE j(j INT);
-                MockSchema schema = new MockSchema("SALES");
-                registerSchema(schema);
-                final RelDataType intType =
-                    typeFactory.createSqlType(SqlTypeName.INTEGER);
-                for (int i = 0; i < 10; i++) {
-                  String t = String.valueOf((char) ('A' + i));
-                  MockTable table = MockTable.create(this, schema, t, false, 100);
-                  table.addColumn(t, intType);
-                  registerTable(table);
-                }
-                return this;
-              }
-              // CHECKSTYLE: IGNORE 1
-            }.init();
+        typeFactory -> new MockCatalogReader(typeFactory, true) {
+          @Override public MockCatalogReader init() {
+            // CREATE SCHEMA abc;
+            // CREATE TABLE a(a INT);
+            // ...
+            // CREATE TABLE j(j INT);
+            MockSchema schema = new MockSchema("SALES");
+            registerSchema(schema);
+            final RelDataType intType =
+                typeFactory.createSqlType(SqlTypeName.INTEGER);
+            for (int i = 0; i < 10; i++) {
+              String t = String.valueOf((char) ('A' + i));
+              MockTable table = MockTable.create(this, schema, t, false, 100);
+              table.addColumn(t, intType);
+              registerTable(table);
+            }
+            return this;
           }
-        });
+          // CHECKSTYLE: IGNORE 1
+        }.init());
     HepProgram program = new HepProgramBuilder()
         .addMatchOrder(HepMatchOrder.BOTTOM_UP)
         .addRuleInstance(ProjectRemoveRule.INSTANCE)
@@ -2804,11 +2784,11 @@ public class RelOptRulesTest extends RelOptTestBase {
     final AggregateExtractProjectRule rule =
         new AggregateExtractProjectRule(
             operand(Aggregate.class,
-                operand(Project.class, null,
-                    new PredicateImpl<Project>() {
+                operandJ(Project.class, null,
+                    new Predicate<Project>() {
                       int matchCount = 0;
 
-                      public boolean test(@Nullable Project project) {
+                      public boolean test(Project project) {
                         return matchCount++ == 0;
                       }
                     },
@@ -2863,9 +2843,9 @@ public class RelOptRulesTest extends RelOptTestBase {
     final RelRoot root = tester.convertSqlToRel(sql);
     final RelNode relInitial = root.rel;
 
-    assertTrue(relInitial != null);
+    assertThat(relInitial, notNullValue());
 
-    List<RelMetadataProvider> list = Lists.newArrayList();
+    List<RelMetadataProvider> list = new ArrayList<>();
     list.add(DefaultRelMetadataProvider.INSTANCE);
     planner.registerMetadataProviders(list);
     RelMetadataProvider plannerChain = ChainedRelMetadataProvider.of(list);
@@ -3499,7 +3479,7 @@ public class RelOptRulesTest extends RelOptTestBase {
       @Override public RelOptPlanner createPlanner() {
         return new MockRelOptPlanner(Contexts.empty()) {
           @Override public List<RelTraitDef> getRelTraitDefs() {
-            return ImmutableList.<RelTraitDef>of(RelCollationTraitDef.INSTANCE);
+            return ImmutableList.of(RelCollationTraitDef.INSTANCE);
           }
           @Override public RelTraitSet emptyTraitSet() {
             return RelTraitSet.createEmpty().plus(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/RelOptTestBase.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/RelOptTestBase.java b/core/src/test/java/org/apache/calcite/test/RelOptTestBase.java
index 3882c84..9b8ddb1 100644
--- a/core/src/test/java/org/apache/calcite/test/RelOptTestBase.java
+++ b/core/src/test/java/org/apache/calcite/test/RelOptTestBase.java
@@ -36,13 +36,14 @@ import org.apache.calcite.sql2rel.RelDecorrelator;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.Closer;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Consumer;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.notNullValue;
@@ -178,7 +179,7 @@ abstract class RelOptTestBase extends SqlToRelTestBase {
 
     assertTrue(relInitial != null);
 
-    List<RelMetadataProvider> list = Lists.newArrayList();
+    List<RelMetadataProvider> list = new ArrayList<>();
     list.add(DefaultRelMetadataProvider.INSTANCE);
     planner.registerMetadataProviders(list);
     RelMetadataProvider plannerChain =
@@ -227,8 +228,7 @@ abstract class RelOptTestBase extends SqlToRelTestBase {
   /** Sets the SQL statement for a test. */
   Sql sql(String sql) {
     return new Sql(sql, null, null,
-        ImmutableMap.<Hook, Function>of(),
-        ImmutableList.<Function<Tester, Tester>>of());
+        ImmutableMap.of(), ImmutableList.of());
   }
 
   /** Allows fluent testing. */
@@ -236,11 +236,11 @@ abstract class RelOptTestBase extends SqlToRelTestBase {
     private final String sql;
     private HepProgram preProgram;
     private final HepPlanner hepPlanner;
-    private final ImmutableMap<Hook, Function> hooks;
+    private final ImmutableMap<Hook, Consumer> hooks;
     private ImmutableList<Function<Tester, Tester>> transforms;
 
     Sql(String sql, HepProgram preProgram, HepPlanner hepPlanner,
-        ImmutableMap<Hook, Function> hooks,
+        ImmutableMap<Hook, Consumer> hooks,
         ImmutableList<Function<Tester, Tester>> transforms) {
       this.sql = sql;
       this.preProgram = preProgram;
@@ -274,60 +274,43 @@ abstract class RelOptTestBase extends SqlToRelTestBase {
     }
 
     /** Adds a hook and a handler for that hook. Calcite will create a thread
-     * hook (by calling {@link Hook#addThread(com.google.common.base.Function)})
+     * hook (by calling {@link Hook#addThread(Consumer)})
      * just before running the query, and remove the hook afterwards. */
-    public <T> Sql withHook(Hook hook, Function<T, Void> handler) {
+    public <T> Sql withHook(Hook hook, Consumer<T> handler) {
       return new Sql(sql, preProgram, hepPlanner,
           FlatLists.append(hooks, hook, handler), transforms);
     }
 
+    /** @deprecated Use {@link #withHook(Hook, Consumer)}. */
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed before 2.0
+    public <T> Sql withHook(Hook hook,
+        com.google.common.base.Function<T, Void> handler) {
+      return withHook(hook, (Consumer<T>) handler::apply);
+    }
+
     public <V> Sql withProperty(Hook hook, V value) {
-      return withHook(hook, Hook.property(value));
+      return withHook(hook, Hook.propertyJ(value));
     }
 
     public Sql expand(final boolean b) {
-      return withTransform(
-          new Function<Tester, Tester>() {
-            public Tester apply(Tester tester) {
-              return tester.withExpand(b);
-            }
-          });
+      return withTransform(tester -> tester.withExpand(b));
     }
 
     public Sql withLateDecorrelation(final boolean b) {
-      return withTransform(
-          new Function<Tester, Tester>() {
-            public Tester apply(Tester tester) {
-              return tester.withLateDecorrelation(b);
-            }
-          });
+      return withTransform(tester -> tester.withLateDecorrelation(b));
     }
 
     public Sql withDecorrelation(final boolean b) {
-      return withTransform(
-          new Function<Tester, Tester>() {
-            public Tester apply(Tester tester) {
-              return tester.withDecorrelation(b);
-            }
-          });
+      return withTransform(tester -> tester.withDecorrelation(b));
     }
 
     public Sql withTrim(final boolean b) {
-      return withTransform(
-          new Function<Tester, Tester>() {
-            public Tester apply(Tester tester) {
-              return tester.withTrim(b);
-            }
-          });
+      return withTransform(tester -> tester.withTrim(b));
     }
 
     public Sql withContext(final Context context) {
-      return withTransform(
-          new Function<Tester, Tester>() {
-            public Tester apply(Tester tester) {
-              return tester.withContext(context);
-            }
-          });
+      return withTransform(tester -> tester.withContext(context));
     }
 
     public void check() {
@@ -338,9 +321,10 @@ abstract class RelOptTestBase extends SqlToRelTestBase {
       check(true);
     }
 
+    @SuppressWarnings("unchecked")
     private void check(boolean unchanged) {
       try (final Closer closer = new Closer()) {
-        for (Map.Entry<Hook, Function> entry : hooks.entrySet()) {
+        for (Map.Entry<Hook, Consumer> entry : hooks.entrySet()) {
           closer.add(entry.getKey().addThread(entry.getValue()));
         }
         Tester t = tester;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/RexProgramTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/RexProgramTest.java b/core/src/test/java/org/apache/calcite/test/RexProgramTest.java
index 007b1c4..733579d 100644
--- a/core/src/test/java/org/apache/calcite/test/RexProgramTest.java
+++ b/core/src/test/java/org/apache/calcite/test/RexProgramTest.java
@@ -62,7 +62,6 @@ import org.apache.calcite.util.Util;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.LinkedHashMultimap;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
 
 import org.junit.Before;
@@ -129,7 +128,7 @@ public class RexProgramTest {
 
     DummyTestDataContext() {
       this.map =
-          ImmutableMap.<String, Object>of(
+          ImmutableMap.of(
               Variable.TIME_ZONE.camelName, TimeZone.getTimeZone("America/Los_Angeles"),
               Variable.CURRENT_TIMESTAMP.camelName, 1311120000000L);
     }
@@ -1007,7 +1006,7 @@ public class RexProgramTest {
     }
     final RelDataType rowType3 = builder.build();
     final RexDynamicParam range3 = rexBuilder.makeDynamicParam(rowType3, 0);
-    final List<RexNode> list = Lists.newArrayList();
+    final List<RexNode> list = new ArrayList<>();
     for (int i = 0; i < n; i++) {
       list.add(
           and(rexBuilder.makeFieldAccess(range3, i * 2),

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/ScannableTableTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/ScannableTableTest.java b/core/src/test/java/org/apache/calcite/test/ScannableTableTest.java
index ae18bc6..582389b 100644
--- a/core/src/test/java/org/apache/calcite/test/ScannableTableTest.java
+++ b/core/src/test/java/org/apache/calcite/test/ScannableTableTest.java
@@ -358,7 +358,7 @@ public class ScannableTableTest {
       final Schema schema =
           new AbstractSchema() {
             @Override protected Map<String, Table> getTableMap() {
-              return ImmutableMap.<String, Table>of("TENS",
+              return ImmutableMap.of("TENS",
                   new SimpleTable() {
                     private Enumerable<Object[]> superScan(DataContext root) {
                       return super.scan(root);
@@ -414,16 +414,13 @@ public class ScannableTableTest {
 
   protected ConnectionPostProcessor newSchema(final String schemaName,
       final String tableName, final Table table) {
-    return new ConnectionPostProcessor() {
-
-      @Override public Connection apply(Connection connection) throws SQLException {
-        CalciteConnection con = connection.unwrap(CalciteConnection.class);
-        SchemaPlus rootSchema = con.getRootSchema();
-        SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
-        schema.add(tableName, table);
-        connection.setSchema(schemaName);
-        return connection;
-      }
+    return connection -> {
+      CalciteConnection con = connection.unwrap(CalciteConnection.class);
+      SchemaPlus rootSchema = con.getRootSchema();
+      SchemaPlus schema = rootSchema.add(schemaName, new AbstractSchema());
+      schema.add(tableName, table);
+      connection.setSchema(schemaName);
+      return connection;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlLineTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlLineTest.java b/core/src/test/java/org/apache/calcite/test/SqlLineTest.java
index 9530e06..17b6d86 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlLineTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlLineTest.java
@@ -76,7 +76,7 @@ public class SqlLineTest {
     } else {
       args.add("--run=" + scriptFile.getAbsolutePath());
     }
-    return run(args.toArray(new String[args.size()]));
+    return run(args.toArray(new String[0]));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlTestGen.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlTestGen.java b/core/src/test/java/org/apache/calcite/test/SqlTestGen.java
index 95ab005..54ddd61 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlTestGen.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlTestGen.java
@@ -80,7 +80,7 @@ public class SqlTestGen {
         list.add(method);
       }
     }
-    return list.toArray(new Method[list.size()]);
+    return list.toArray(new Method[0]);
   }
 
   //~ Inner Classes ----------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlToRelConverterExtendedTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterExtendedTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterExtendedTest.java
index 2deab9d..d19e4cc 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterExtendedTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterExtendedTest.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.test;
 
-import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptSchema;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.RelShuttleImpl;
@@ -24,11 +23,8 @@ import org.apache.calcite.rel.core.TableScan;
 import org.apache.calcite.rel.externalize.RelJsonReader;
 import org.apache.calcite.rel.externalize.RelJsonWriter;
 import org.apache.calcite.runtime.Hook;
-import org.apache.calcite.schema.SchemaPlus;
 import org.apache.calcite.tools.Frameworks;
 
-import com.google.common.base.Function;
-
 import org.junit.After;
 import org.junit.Before;
 
@@ -41,13 +37,8 @@ public class SqlToRelConverterExtendedTest extends SqlToRelConverterTest {
   Hook.Closeable closeable;
 
   @Before public void before() {
-    this.closeable = Hook.CONVERTED.addThread(
-        new Function<RelNode, Void>() {
-          public Void apply(RelNode a0) {
-            foo(a0);
-            return null;
-          }
-        });
+    this.closeable =
+        Hook.CONVERTED.addThread(SqlToRelConverterExtendedTest::foo);
   }
 
   @After public void after() {
@@ -73,21 +64,17 @@ public class SqlToRelConverterExtendedTest extends SqlToRelConverterTest {
     });
 
     // Convert JSON back to rel tree.
-    Frameworks.withPlanner(
-        new Frameworks.PlannerAction<Object>() {
-          public Object apply(RelOptCluster cluster,
-              RelOptSchema relOptSchema, SchemaPlus rootSchema) {
-            final RelJsonReader reader = new RelJsonReader(
-                cluster,
-                schemas[0], rootSchema);
-            try {
-              RelNode x = reader.read(json);
-            } catch (IOException e) {
-              throw new RuntimeException(e);
-            }
-            return null;
-          }
-        });
+    Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+      final RelJsonReader reader = new RelJsonReader(
+          cluster,
+          schemas[0], rootSchema);
+      try {
+        RelNode x = reader.read(json);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      return null;
+    });
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
index 4a1f2e6..0f9dad2 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
@@ -21,13 +21,11 @@ import org.apache.calcite.config.CalciteConnectionProperty;
 import org.apache.calcite.config.NullCollation;
 import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.RelOptUtil;
-import org.apache.calcite.prepare.Prepare;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.RelRoot;
 import org.apache.calcite.rel.RelVisitor;
 import org.apache.calcite.rel.core.CorrelationId;
 import org.apache.calcite.rel.externalize.RelXmlWriter;
-import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.sql.SqlExplainLevel;
 import org.apache.calcite.sql.validate.SqlConformance;
 import org.apache.calcite.sql.validate.SqlConformanceEnum;
@@ -37,7 +35,6 @@ import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.TestUtil;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableSet;
 
 import org.junit.Ignore;
@@ -2618,25 +2615,18 @@ public class SqlToRelConverterTest extends SqlToRelTestBase {
   }
 
   private Tester getExtendedTester() {
-    return tester.withCatalogReaderFactory(
-      new Function<RelDataTypeFactory, Prepare.CatalogReader>() {
-        public Prepare.CatalogReader apply(RelDataTypeFactory typeFactory) {
-          return new MockCatalogReader(typeFactory, true)
-              .init().init2();
-        }
-      });
+    return tester.withCatalogReaderFactory(typeFactory ->
+        new MockCatalogReader(typeFactory, true).init().init2());
   }
 
   @Test public void testLarge() {
-    SqlValidatorTest.checkLarge(400,
-        new Function<String, Void>() {
-          public Void apply(String input) {
-            final RelRoot root = tester.convertSqlToRel(input);
-            final String s = RelOptUtil.toString(root.project());
-            assertThat(s, notNullValue());
-            return null;
-          }
-        });
+    // Size factor used to be 400, but lambdas use a lot of stack
+    final int x = 300;
+    SqlValidatorTest.checkLarge(x, input -> {
+      final RelRoot root = tester.convertSqlToRel(input);
+      final String s = RelOptUtil.toString(root.project());
+      assertThat(s, notNullValue());
+    });
   }
 
   @Test public void testUnionInFrom() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlToRelTestBase.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelTestBase.java b/core/src/test/java/org/apache/calcite/test/SqlToRelTestBase.java
index 7bc3b88..d2192ae 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlToRelTestBase.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlToRelTestBase.java
@@ -62,13 +62,13 @@ import org.apache.calcite.sql2rel.StandardConvertletTable;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
@@ -111,43 +111,42 @@ public abstract class SqlToRelTestBase {
 
   protected Tester getTesterWithDynamicTable() {
     return tester.withCatalogReaderFactory(
-        new Function<RelDataTypeFactory, Prepare.CatalogReader>() {
-          public Prepare.CatalogReader apply(RelDataTypeFactory typeFactory) {
-            return new MockCatalogReader(typeFactory, true) {
-              @Override public MockCatalogReader init() {
-                // CREATE SCHEMA "SALES;
-                // CREATE DYNAMIC TABLE "NATION"
-                // CREATE DYNAMIC TABLE "CUSTOMER"
-
-                MockSchema schema = new MockSchema("SALES");
-                registerSchema(schema);
-
-                MockTable nationTable = new MockDynamicTable(this, schema.getCatalogName(),
-                    schema.getName(), "NATION", false, 100);
-                registerTable(nationTable);
-
-                MockTable customerTable = new MockDynamicTable(this, schema.getCatalogName(),
-                    schema.getName(), "CUSTOMER", false, 100);
-                registerTable(customerTable);
-
-                // CREATE TABLE "REGION" - static table with known schema.
-                final RelDataType intType =
-                    typeFactory.createSqlType(SqlTypeName.INTEGER);
-                final RelDataType varcharType =
-                    typeFactory.createSqlType(SqlTypeName.VARCHAR);
-
-                MockTable regionTable = MockTable.create(this, schema, "REGION", false, 100);
-                regionTable.addColumn("R_REGIONKEY", intType);
-                regionTable.addColumn("R_NAME", varcharType);
-                regionTable.addColumn("R_COMMENT", varcharType);
-                registerTable(regionTable);
-
-                return this;
-              }
-              // CHECKSTYLE: IGNORE 1
-            }.init();
-          }
-        });
+        typeFactory -> new MockCatalogReader(typeFactory, true) {
+            @Override public MockCatalogReader init() {
+              // CREATE SCHEMA "SALES;
+              // CREATE DYNAMIC TABLE "NATION"
+              // CREATE DYNAMIC TABLE "CUSTOMER"
+
+              MockSchema schema = new MockSchema("SALES");
+              registerSchema(schema);
+
+              MockTable nationTable =
+                  new MockDynamicTable(this, schema.getCatalogName(),
+                      schema.getName(), "NATION", false, 100);
+              registerTable(nationTable);
+
+              MockTable customerTable =
+                  new MockDynamicTable(this, schema.getCatalogName(),
+                      schema.getName(), "CUSTOMER", false, 100);
+              registerTable(customerTable);
+
+              // CREATE TABLE "REGION" - static table with known schema.
+              final RelDataType intType =
+                  typeFactory.createSqlType(SqlTypeName.INTEGER);
+              final RelDataType varcharType =
+                  typeFactory.createSqlType(SqlTypeName.VARCHAR);
+
+              MockTable regionTable =
+                  MockTable.create(this, schema, "REGION", false, 100);
+              regionTable.addColumn("R_REGIONKEY", intType);
+              regionTable.addColumn("R_NAME", varcharType);
+              regionTable.addColumn("R_COMMENT", varcharType);
+              registerTable(regionTable);
+
+              return this;
+            }
+            // CHECKSTYLE: IGNORE 1
+          }.init());
   }
 
   /**
@@ -605,7 +604,7 @@ public abstract class SqlToRelTestBase {
     }
 
     public RelRoot convertSqlToRel(String sql) {
-      Preconditions.checkNotNull(sql);
+      Objects.requireNonNull(sql);
       final SqlNode sqlQuery;
       final SqlToRelConverter.Config localConfig;
       try {


[29/30] calcite git commit: [CALCITE-2383] NTH_VALUE window function (Sergey Nuyanzin)

Posted by jh...@apache.org.
[CALCITE-2383] NTH_VALUE window function (Sergey Nuyanzin)

Break SqlNthValueAggregateFunction out as a top-level class, and add
tests to SqlValidatorTest. (Julian Hyde)

Close apache/calcite#742


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/df774b9e
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/df774b9e
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/df774b9e

Branch: refs/heads/master
Commit: df774b9efa97c0b11ed63036e829750aaa88b99d
Parents: bc269aa
Author: snuyanzin <sn...@gmail.com>
Authored: Tue Jun 26 15:09:06 2018 +0300
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:46:20 2018 -0700

----------------------------------------------------------------------
 core/src/main/codegen/templates/Parser.jj       |  1 +
 .../calcite/adapter/enumerable/RexImpTable.java | 58 ++++++++++++++++++++
 .../java/org/apache/calcite/sql/SqlKind.java    |  3 +
 .../calcite/sql/fun/SqlNthValueAggFunction.java | 38 +++++++++++++
 .../calcite/sql/fun/SqlStdOperatorTable.java    |  7 +++
 .../apache/calcite/sql/test/SqlAdvisorTest.java |  1 +
 .../apache/calcite/test/SqlValidatorTest.java   | 21 ++++---
 core/src/test/resources/sql/winagg.iq           | 25 +++++++++
 site/_docs/reference.md                         |  3 +-
 9 files changed, 148 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/main/codegen/templates/Parser.jj
----------------------------------------------------------------------
diff --git a/core/src/main/codegen/templates/Parser.jj b/core/src/main/codegen/templates/Parser.jj
index 7fda2bc..a89352f 100644
--- a/core/src/main/codegen/templates/Parser.jj
+++ b/core/src/main/codegen/templates/Parser.jj
@@ -5163,6 +5163,7 @@ SqlIdentifier ReservedFunctionName() :
     |   <MINUTE>
     |   <MOD>
     |   <MONTH>
+    |   <NTH_VALUE>
     |   <NTILE>
     |   <NULLIF>
     |   <OCTET_LENGTH>

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
index 1bc9de4..f806a11 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
@@ -178,6 +178,7 @@ import static org.apache.calcite.sql.fun.SqlStdOperatorTable.NOT_EQUALS;
 import static org.apache.calcite.sql.fun.SqlStdOperatorTable.NOT_LIKE;
 import static org.apache.calcite.sql.fun.SqlStdOperatorTable.NOT_SIMILAR_TO;
 import static org.apache.calcite.sql.fun.SqlStdOperatorTable.NOT_SUBMULTISET_OF;
+import static org.apache.calcite.sql.fun.SqlStdOperatorTable.NTH_VALUE;
 import static org.apache.calcite.sql.fun.SqlStdOperatorTable.NTILE;
 import static org.apache.calcite.sql.fun.SqlStdOperatorTable.OR;
 import static org.apache.calcite.sql.fun.SqlStdOperatorTable.OVERLAY;
@@ -455,6 +456,7 @@ public class RexImpTable {
     winAggMap.put(ROW_NUMBER, constructorSupplier(RowNumberImplementor.class));
     winAggMap.put(FIRST_VALUE,
         constructorSupplier(FirstValueImplementor.class));
+    winAggMap.put(NTH_VALUE, constructorSupplier(NthValueImplementor.class));
     winAggMap.put(LAST_VALUE, constructorSupplier(LastValueImplementor.class));
     winAggMap.put(LEAD, constructorSupplier(LeadImplementor.class));
     winAggMap.put(LAG, constructorSupplier(LagImplementor.class));
@@ -1517,6 +1519,62 @@ public class RexImpTable {
     }
   }
 
+  /** Implementor for the {@code NTH_VALUE}
+   * windowed aggregate function. */
+  static class NthValueImplementor implements WinAggImplementor {
+    public List<Type> getStateType(AggContext info) {
+      return Collections.emptyList();
+    }
+
+    public void implementReset(AggContext info, AggResetContext reset) {
+      // no op
+    }
+
+    public void implementAdd(AggContext info, AggAddContext add) {
+      // no op
+    }
+
+    public boolean needCacheWhenFrameIntact() {
+      return true;
+    }
+
+    public Expression implementResult(AggContext info,
+        AggResultContext result) {
+      WinAggResultContext winResult = (WinAggResultContext) result;
+
+      List<RexNode> rexArgs = winResult.rexArguments();
+
+      ParameterExpression res = Expressions.parameter(0, info.returnType(),
+          result.currentBlock().newName("nth"));
+
+      RexToLixTranslator currentRowTranslator =
+          winResult.rowTranslator(
+              winResult.computeIndex(Expressions.constant(0), SeekType.START));
+
+      Expression dstIndex = winResult.computeIndex(
+          Expressions.subtract(
+              currentRowTranslator.translate(rexArgs.get(1), int.class),
+              Expressions.constant(1)), SeekType.START);
+
+      Expression rowInRange = winResult.rowInPartition(dstIndex);
+
+      BlockBuilder thenBlock = result.nestBlock();
+      Expression nthValue = winResult.rowTranslator(dstIndex)
+          .translate(rexArgs.get(0), res.type);
+      thenBlock.add(Expressions.statement(Expressions.assign(res, nthValue)));
+      result.exitBlock();
+      BlockStatement thenBranch = thenBlock.toBlock();
+
+      Expression defaultValue = getDefaultValue(res.type);
+
+      result.currentBlock().add(Expressions.declare(0, res, null));
+      result.currentBlock().add(
+          Expressions.ifThenElse(rowInRange, thenBranch,
+              Expressions.statement(Expressions.assign(res, defaultValue))));
+      return res;
+    }
+  }
+
   /** Implementor for the {@code LEAD} and {@code LAG} windowed
    * aggregate functions. */
   static class LeadLagImplementor implements WinAggImplementor {

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/main/java/org/apache/calcite/sql/SqlKind.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlKind.java b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
index a2cb6d0..08cfbec 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlKind.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
@@ -879,6 +879,9 @@ public enum SqlKind {
   /** The {@code NTILE} aggregate function. */
   NTILE,
 
+  /** The {@code NTH_VALUE} aggregate function. */
+  NTH_VALUE,
+
   /** The {@code COLLECT} aggregate function. */
   COLLECT,
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/main/java/org/apache/calcite/sql/fun/SqlNthValueAggFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlNthValueAggFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlNthValueAggFunction.java
new file mode 100644
index 0000000..b1a2a86
--- /dev/null
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlNthValueAggFunction.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.sql.fun;
+
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.ReturnTypes;
+
+/**
+ * <code>NTH_VALUE</code> windowed aggregate function
+ * returns the value of an expression evaluated at the {@code n}th row of the
+ * window frame.
+ */
+public class SqlNthValueAggFunction extends SqlAggFunction {
+  public SqlNthValueAggFunction(SqlKind kind) {
+    super(kind.name(), null, kind, ReturnTypes.ARG0_NULLABLE_IF_EMPTY,
+        null, OperandTypes.ANY_NUMERIC, SqlFunctionCategory.NUMERIC, false,
+        true);
+  }
+}
+
+// End SqlNthValueAggFunction.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
index c9f8363..6ac1eb4 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
@@ -867,6 +867,12 @@ public class SqlStdOperatorTable extends ReflectiveSqlOperatorTable {
       new SqlFirstLastValueAggFunction(SqlKind.FIRST_VALUE);
 
   /**
+   * <code>NTH_VALUE</code> aggregate function.
+   */
+  public static final SqlAggFunction NTH_VALUE =
+      new SqlNthValueAggFunction(SqlKind.NTH_VALUE);
+
+  /**
    * <code>LEAD</code> aggregate function.
    */
   public static final SqlAggFunction LEAD =
@@ -2296,6 +2302,7 @@ public class SqlStdOperatorTable extends ReflectiveSqlOperatorTable {
       throw new AssertionError(comparisonKind);
     }
   }
+
 }
 
 // End SqlStdOperatorTable.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/test/java/org/apache/calcite/sql/test/SqlAdvisorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/sql/test/SqlAdvisorTest.java b/core/src/test/java/org/apache/calcite/sql/test/SqlAdvisorTest.java
index e877b2a..c8476be 100644
--- a/core/src/test/java/org/apache/calcite/sql/test/SqlAdvisorTest.java
+++ b/core/src/test/java/org/apache/calcite/sql/test/SqlAdvisorTest.java
@@ -176,6 +176,7 @@ public class SqlAdvisorTest extends SqlValidatorTestCase {
           "KEYWORD(NEW)",
           "KEYWORD(NEXT)",
           "KEYWORD(NOT)",
+          "KEYWORD(NTH_VALUE)",
           "KEYWORD(NTILE)",
           "KEYWORD(NULL)",
           "KEYWORD(NULLIF)",

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
index e96f1d2..b659009 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
@@ -3936,26 +3936,27 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
    * <a href="https://issues.apache.org/jira/browse/CALCITE-1340">[CALCITE-1340]
    * Window aggregates give invalid errors</a>. */
   @Test public void testWindowFunctionsWithoutOver() {
-    winSql(
-        "select sum(empno) \n"
-        + "from emp \n"
-        + "group by deptno \n"
+    winSql("select sum(empno)\n"
+        + "from emp\n"
+        + "group by deptno\n"
         + "order by ^row_number()^")
         .fails("OVER clause is necessary for window functions");
 
-    winSql(
-        "select ^rank()^ \n"
+    winSql("select ^rank()^\n"
         + "from emp")
         .fails("OVER clause is necessary for window functions");
 
     // With [CALCITE-1340], the validator would see RANK without OVER,
     // mistakenly think this is an aggregating query, and wrongly complain
     // about the PARTITION BY: "Expression 'DEPTNO' is not being grouped"
-    winSql(
-        "select cume_dist() over w , ^rank()^\n"
+    winSql("select cume_dist() over w , ^rank()^\n"
         + "from emp \n"
         + "window w as (partition by deptno order by deptno)")
         .fails("OVER clause is necessary for window functions");
+
+    winSql("select ^nth_value(sal, 2)^\n"
+        + "from emp")
+        .fails("OVER clause is necessary for window functions");
   }
 
   @Test public void testOverInPartitionBy() {
@@ -4096,6 +4097,7 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
     winExp("rank() over (order by empno)").ok();
     winExp("percent_rank() over (order by empno)").ok();
     winExp("cume_dist() over (order by empno)").ok();
+    winExp("nth_value(sal, 2) over (order by empno)").ok();
 
     // rule 6a
     // ORDER BY required with RANK & DENSE_RANK
@@ -7680,6 +7682,9 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
 
     check("select FIRST_VALUE(sal) over (order by empno) from emp");
     check("select FIRST_VALUE(ename) over (order by empno) from emp");
+
+    check("select NTH_VALUE(sal, 2) over (order by empno) from emp");
+    check("select NTH_VALUE(ename, 2) over (order by empno) from emp");
   }
 
   @Test public void testMinMaxFunctions() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/core/src/test/resources/sql/winagg.iq
----------------------------------------------------------------------
diff --git a/core/src/test/resources/sql/winagg.iq b/core/src/test/resources/sql/winagg.iq
index 809db77..eac5822 100644
--- a/core/src/test/resources/sql/winagg.iq
+++ b/core/src/test/resources/sql/winagg.iq
@@ -430,4 +430,29 @@ limit 5;
 
 !ok
 
+# NTH_VALUE
+select emp."ENAME", emp."DEPTNO",
+ nth_value(emp."DEPTNO", 1) over() as "first_value",
+ nth_value(emp."DEPTNO", 2) over() as "second_value",
+ nth_value(emp."DEPTNO", 5) over() as "fifth_value",
+ nth_value(emp."DEPTNO", 8) over() as "eighth_value",
+ nth_value(emp."DEPTNO", 10) over() as "tenth_value"
+from emp order by emp."ENAME";
++-------+--------+-------------+--------------+-------------+--------------+-------------+
+| ENAME | DEPTNO | first_value | second_value | fifth_value | eighth_value | tenth_value |
++-------+--------+-------------+--------------+-------------+--------------+-------------+
+| Adam  |     50 |          10 |           10 |          30 |           60 |             |
+| Alice |     30 |          10 |           10 |          30 |           60 |             |
+| Bob   |     10 |          10 |           10 |          30 |           60 |             |
+| Eric  |     20 |          10 |           10 |          30 |           60 |             |
+| Eve   |     50 |          10 |           10 |          30 |           60 |             |
+| Grace |     60 |          10 |           10 |          30 |           60 |             |
+| Jane  |     10 |          10 |           10 |          30 |           60 |             |
+| Susan |     30 |          10 |           10 |          30 |           60 |             |
+| Wilma |        |          10 |           10 |          30 |           60 |             |
++-------+--------+-------------+--------------+-------------+--------------+-------------+
+(9 rows)
+
+!ok
+
 # End winagg.iq

http://git-wip-us.apache.org/repos/asf/calcite/blob/df774b9e/site/_docs/reference.md
----------------------------------------------------------------------
diff --git a/site/_docs/reference.md b/site/_docs/reference.md
index be3831f..3d1433f 100644
--- a/site/_docs/reference.md
+++ b/site/_docs/reference.md
@@ -1538,6 +1538,7 @@ Not implemented:
 | LAST_VALUE(value) OVER window             | Returns *value* evaluated at the row that is the last row of the window frame
 | LEAD(value, offset, default) OVER window  | Returns *value* evaluated at the row that is *offset* rows after the current row within the partition; if there is no such row, instead returns *default*. Both *offset* and *default* are evaluated with respect to the current row. If omitted, *offset* defaults to 1 and *default* to NULL
 | LAG(value, offset, default) OVER window   | Returns *value* evaluated at the row that is *offset* rows before the current row within the partition; if there is no such row, instead returns *default*. Both *offset* and *default* are evaluated with respect to the current row. If omitted, *offset* defaults to 1 and *default* to NULL
+| NTH_VALUE(value, nth) OVER window         | Returns *value* evaluated at the row that is the *n*th row of the window frame
 | NTILE(value) OVER window                  | Returns an integer ranging from 1 to *value*, dividing the partition as equally as possible
 
 Not implemented:
@@ -1548,7 +1549,7 @@ Not implemented:
 * LAST_VALUE(value) IGNORE NULLS OVER window
 * PERCENT_RANK(value) OVER window
 * CUME_DIST(value) OVER window
-* NTH_VALUE(value, nth) OVER window
+* NTH_VALUE(value, nth) [ FROM { FIRST | LAST } ] IGNORE NULLS OVER window
 
 ### Grouping functions
 


[26/30] calcite git commit: [CALCITE-1866] JDBC adapter generates incorrect code when pushing FLOOR to MySQL (Kang Wang, Sergey Nuyanzin)

Posted by jh...@apache.org.
[CALCITE-1866] JDBC adapter generates incorrect code when pushing FLOOR to MySQL (Kang Wang, Sergey Nuyanzin)

Fix format string. DateTime FLOOR to HOUR cause MySQL use '%H' rather than '%k'. (Kang Wang)

Add test-cases for MySQL (FLOOR to HOUR, FLOOR to MINUTE, FLOOR to SECOND) (Sergey Nuyanzin)

Close apache/calcite#745


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/bc269aab
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/bc269aab
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/bc269aab

Branch: refs/heads/master
Commit: bc269aab9e87715a250a4e28851d125b195815c7
Parents: cf3eca2
Author: snuyanzin <sn...@gmail.com>
Authored: Fri Jun 29 16:22:23 2018 +0300
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:41:09 2018 -0700

----------------------------------------------------------------------
 .../calcite/sql/dialect/MysqlSqlDialect.java    |  6 ++--
 .../rel/rel2sql/RelToSqlConverterTest.java      | 31 ++++++++++++++++++--
 2 files changed, 32 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/bc269aab/core/src/main/java/org/apache/calcite/sql/dialect/MysqlSqlDialect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/dialect/MysqlSqlDialect.java b/core/src/main/java/org/apache/calcite/sql/dialect/MysqlSqlDialect.java
index bc05165..e4f6b7f 100644
--- a/core/src/main/java/org/apache/calcite/sql/dialect/MysqlSqlDialect.java
+++ b/core/src/main/java/org/apache/calcite/sql/dialect/MysqlSqlDialect.java
@@ -193,13 +193,13 @@ public class MysqlSqlDialect extends SqlDialect {
       format = "%Y-%m-%d";
       break;
     case HOUR:
-      format = "%Y-%m-%d %k:00:00";
+      format = "%Y-%m-%d %H:00:00";
       break;
     case MINUTE:
-      format = "%Y-%m-%d %k:%i:00";
+      format = "%Y-%m-%d %H:%i:00";
       break;
     case SECOND:
-      format = "%Y-%m-%d %k:%i:%s";
+      format = "%Y-%m-%d %H:%i:%s";
       break;
     default:
       throw new AssertionError("MYSQL does not support FLOOR for time unit: "

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc269aab/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
index c5af61a..ec216a1 100644
--- a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
+++ b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
@@ -1286,6 +1286,33 @@ public class RelToSqlConverterTest {
         .ok(expected);
   }
 
+  @Test public void testFloorMysqlHour() {
+    String query = "SELECT floor(\"hire_date\" TO HOUR) FROM \"employee\"";
+    String expected = "SELECT DATE_FORMAT(`hire_date`, '%Y-%m-%d %H:00:00')\n"
+        + "FROM `foodmart`.`employee`";
+    sql(query)
+        .withMysql()
+        .ok(expected);
+  }
+
+  @Test public void testFloorMysqlMinute() {
+    String query = "SELECT floor(\"hire_date\" TO MINUTE) FROM \"employee\"";
+    String expected = "SELECT DATE_FORMAT(`hire_date`, '%Y-%m-%d %H:%i:00')\n"
+        + "FROM `foodmart`.`employee`";
+    sql(query)
+        .withMysql()
+        .ok(expected);
+  }
+
+  @Test public void testFloorMysqlSecond() {
+    String query = "SELECT floor(\"hire_date\" TO SECOND) FROM \"employee\"";
+    String expected = "SELECT DATE_FORMAT(`hire_date`, '%Y-%m-%d %H:%i:%s')\n"
+        + "FROM `foodmart`.`employee`";
+    sql(query)
+        .withMysql()
+        .ok(expected);
+  }
+
   /** Test case for
    * <a href="https://issues.apache.org/jira/browse/CALCITE-1826">[CALCITE-1826]
    * JDBC dialect-specific FLOOR fails when in GROUP BY</a>. */
@@ -1303,9 +1330,9 @@ public class RelToSqlConverterTest {
         + "FROM \"foodmart\".\"employee\"\n"
         + "GROUP BY DATE_TRUNC('MINUTE', \"hire_date\")";
     final String expectedMysql = "SELECT"
-        + " DATE_FORMAT(`hire_date`, '%Y-%m-%d %k:%i:00')\n"
+        + " DATE_FORMAT(`hire_date`, '%Y-%m-%d %H:%i:00')\n"
         + "FROM `foodmart`.`employee`\n"
-        + "GROUP BY DATE_FORMAT(`hire_date`, '%Y-%m-%d %k:%i:00')";
+        + "GROUP BY DATE_FORMAT(`hire_date`, '%Y-%m-%d %H:%i:00')";
     sql(query)
         .withHsqldb()
         .ok(expected)


[07/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
index d710661..d1f0ee6 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
@@ -43,7 +43,6 @@ import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.Bug;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Ordering;
 
@@ -61,6 +60,7 @@ import java.util.Comparator;
 import java.util.List;
 import java.util.Locale;
 import java.util.Objects;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
@@ -5988,16 +5988,10 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
    * lurking in the validation process.
    */
   @Test public void testLarge() {
-    checkLarge(700,
-        new Function<String, Void>() {
-          public Void apply(String input) {
-            check(input);
-            return null;
-          }
-        });
+    checkLarge(700, this::check);
   }
 
-  static void checkLarge(int x, Function<String, Void> f) {
+  static void checkLarge(int x, Consumer<String> f) {
     if (System.getProperty("os.name").startsWith("Windows")) {
       // NOTE jvs 1-Nov-2006:  Default thread stack size
       // on Windows is too small, so avoid stack overflow
@@ -6006,24 +6000,24 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
 
     // E.g. large = "deptno * 1 + deptno * 2 + deptno * 3".
     String large = list(" + ", "deptno * ", x);
-    f.apply("select " + large + "from emp");
-    f.apply("select distinct " + large + "from emp");
-    f.apply("select " + large + " from emp " + "group by deptno");
-    f.apply("select * from emp where " + large + " > 5");
-    f.apply("select * from emp order by " + large + " desc");
-    f.apply("select " + large + " from emp order by 1");
-    f.apply("select distinct " + large + " from emp order by " + large);
+    f.accept("select " + large + "from emp");
+    f.accept("select distinct " + large + "from emp");
+    f.accept("select " + large + " from emp " + "group by deptno");
+    f.accept("select * from emp where " + large + " > 5");
+    f.accept("select * from emp order by " + large + " desc");
+    f.accept("select " + large + " from emp order by 1");
+    f.accept("select distinct " + large + " from emp order by " + large);
 
     // E.g. "in (0, 1, 2, ...)"
-    f.apply("select * from emp where deptno in (" + list(", ", "", x) + ")");
+    f.accept("select * from emp where deptno in (" + list(", ", "", x) + ")");
 
     // E.g. "where x = 1 or x = 2 or x = 3 ..."
-    f.apply("select * from emp where " + list(" or ", "deptno = ", x));
+    f.accept("select * from emp where " + list(" or ", "deptno = ", x));
 
     // E.g. "select x1, x2 ... from (
     // select 'a' as x1, 'a' as x2, ... from emp union
     // select 'bb' as x1, 'bb' as x2, ... from dept)"
-    f.apply("select " + list(", ", "x", x)
+    f.accept("select " + list(", ", "x", x)
         + " from (select " + list(", ", "'a' as x", x) + " from emp "
         + "union all select " + list(", ", "'bb' as x", x) + " from dept)");
   }
@@ -8544,20 +8538,17 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
    * the documentation</a>. */
   @Test public void testOperatorsSortedByPrecedence() {
     final StringBuilder b = new StringBuilder();
-    final Comparator<SqlOperator> comparator =
-        new Comparator<SqlOperator>() {
-          public int compare(SqlOperator o1, SqlOperator o2) {
-            int c = Integer.compare(prec(o1), prec(o2));
-            if (c != 0) {
-              return -c;
-            }
-            c = o1.getName().compareTo(o2.getName());
-            if (c != 0) {
-              return c;
-            }
-            return o1.getSyntax().compareTo(o2.getSyntax());
-          }
-        };
+    final Comparator<SqlOperator> comparator = (o1, o2) -> {
+      int c = Integer.compare(prec(o1), prec(o2));
+      if (c != 0) {
+        return -c;
+      }
+      c = o1.getName().compareTo(o2.getName());
+      if (c != 0) {
+        return c;
+      }
+      return o1.getSyntax().compareTo(o2.getSyntax());
+    };
     final List<SqlOperator> operators =
         SqlStdOperatorTable.instance().getOperatorList();
     int p = -1;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
index b78df79..7e983dd 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
@@ -28,7 +28,6 @@ import org.apache.calcite.sql.test.DelegatingSqlTestFactory;
 import org.apache.calcite.sql.test.SqlTestFactory;
 import org.apache.calcite.sql.test.SqlTester;
 import org.apache.calcite.sql.test.SqlTesterImpl;
-import org.apache.calcite.sql.test.SqlTests;
 import org.apache.calcite.sql.validate.SqlConformance;
 import org.apache.calcite.sql.validate.SqlConformanceEnum;
 import org.apache.calcite.sql.validate.SqlMonotonicity;
@@ -620,13 +619,9 @@ public class SqlValidatorTestCase {
     }
 
     public Sql bindType(final String bindType) {
-      tester.check(sql, null,
-          new SqlTester.ParameterChecker() {
-            public void checkParameters(RelDataType parameterRowType) {
-              assertThat(parameterRowType.toString(), is(bindType));
-            }
-          },
-          SqlTests.ANY_RESULT_CHECKER);
+      tester.check(sql, null, parameterRowType ->
+          assertThat(parameterRowType.toString(), is(bindType)),
+          result -> { });
       return this;
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/StreamTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/StreamTest.java b/core/src/test/java/org/apache/calcite/test/StreamTest.java
index d425f30..b25da6d 100644
--- a/core/src/test/java/org/apache/calcite/test/StreamTest.java
+++ b/core/src/test/java/org/apache/calcite/test/StreamTest.java
@@ -37,9 +37,7 @@ import org.apache.calcite.schema.TableFactory;
 import org.apache.calcite.sql.SqlCall;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.type.SqlTypeName;
-import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
@@ -51,6 +49,7 @@ import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
@@ -246,36 +245,29 @@ public class StreamTest {
         .withDefaultSchema(INFINITE_STREAM_SCHEMA_NAME)
         .query("select stream * from orders")
         .explainContains(explain)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(final ResultSet resultSet) {
-                int n = 0;
-                try {
-                  while (resultSet.next()) {
-                    if (++n == 5) {
-                      new Thread(
-                          new Runnable() {
-                            @Override public void run() {
-                              try {
-                                Thread.sleep(3);
-                                resultSet.getStatement().cancel();
-                              } catch (InterruptedException | SQLException e) {
-                                // ignore
-                              }
-                            }
-                          }).start();
-                    }
+        .returns(resultSet -> {
+          int n = 0;
+          try {
+            while (resultSet.next()) {
+              if (++n == 5) {
+                new Thread(() -> {
+                  try {
+                    Thread.sleep(3);
+                    resultSet.getStatement().cancel();
+                  } catch (InterruptedException | SQLException e) {
+                    // ignore
                   }
-                  fail("expected cancel, got end-of-data");
-                } catch (SQLException e) {
-                  assertThat(e.getMessage(), is("Statement canceled"));
-                }
-                // With a 3 millisecond delay, typically n is between 200 - 400
-                // before cancel takes effect.
-                assertTrue("n is " + n, n > 5);
-                return null;
+                }).start();
               }
-            });
+            }
+            fail("expected cancel, got end-of-data");
+          } catch (SQLException e) {
+            assertThat(e.getMessage(), is("Statement canceled"));
+          }
+          // With a 3 millisecond delay, typically n is between 200 - 400
+          // before cancel takes effect.
+          assertTrue("n is " + n, n > 5);
+        });
   }
 
   @Test public void testStreamToRelationJoin() {
@@ -332,26 +324,23 @@ public class StreamTest {
         .query(sql);
   }
 
-  private Function<ResultSet, Void> startsWith(String... rows) {
+  private Consumer<ResultSet> startsWith(String... rows) {
     final ImmutableList<String> rowList = ImmutableList.copyOf(rows);
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet input) {
-        try {
-          final CalciteAssert.ResultSetFormatter formatter =
-              new CalciteAssert.ResultSetFormatter();
-          final ResultSetMetaData metaData = input.getMetaData();
-          for (String expectedRow : rowList) {
-            if (!input.next()) {
-              throw new AssertionError("input ended too soon");
-            }
-            formatter.rowToString(input, metaData);
-            String actualRow = formatter.string();
-            assertThat(actualRow, equalTo(expectedRow));
+    return resultSet -> {
+      try {
+        final CalciteAssert.ResultSetFormatter formatter =
+            new CalciteAssert.ResultSetFormatter();
+        final ResultSetMetaData metaData = resultSet.getMetaData();
+        for (String expectedRow : rowList) {
+          if (!resultSet.next()) {
+            throw new AssertionError("input ended too soon");
           }
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+          formatter.rowToString(resultSet, metaData);
+          String actualRow = formatter.string();
+          assertThat(actualRow, equalTo(expectedRow));
         }
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
@@ -361,24 +350,19 @@ public class StreamTest {
    * functions.
    */
   private abstract static class BaseOrderStreamTable implements ScannableTable {
-    protected final RelProtoDataType protoRowType = new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory a0) {
-        return a0.builder()
-            .add("ROWTIME", SqlTypeName.TIMESTAMP)
-            .add("ID", SqlTypeName.INTEGER)
-            .add("PRODUCT", SqlTypeName.VARCHAR, 10)
-            .add("UNITS", SqlTypeName.INTEGER)
-            .build();
-      }
-    };
+    protected final RelProtoDataType protoRowType = a0 -> a0.builder()
+        .add("ROWTIME", SqlTypeName.TIMESTAMP)
+        .add("ID", SqlTypeName.INTEGER)
+        .add("PRODUCT", SqlTypeName.VARCHAR, 10)
+        .add("UNITS", SqlTypeName.INTEGER)
+        .build();
 
     public RelDataType getRowType(RelDataTypeFactory typeFactory) {
       return protoRowType.apply(typeFactory);
     }
 
     public Statistic getStatistic() {
-      return Statistics.of(100d,
-        ImmutableList.<ImmutableBitSet>of(),
+      return Statistics.of(100d, ImmutableList.of(),
         RelCollations.createSingleton(0));
     }
 
@@ -391,8 +375,7 @@ public class StreamTest {
     }
 
     @Override public boolean rolledUpColumnValidInsideAgg(String column,
-                                                          SqlCall call, SqlNode parent,
-                                                          CalciteConnectionConfig config) {
+        SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
       return false;
     }
   }
@@ -447,8 +430,7 @@ public class StreamTest {
     }
 
     @Override public boolean rolledUpColumnValidInsideAgg(String column,
-                                                          SqlCall call, SqlNode parent,
-                                                          CalciteConnectionConfig config) {
+        SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
       return false;
     }
   }
@@ -485,21 +467,17 @@ public class StreamTest {
   public static class InfiniteOrdersTable extends BaseOrderStreamTable
       implements StreamableTable {
     public Enumerable<Object[]> scan(DataContext root) {
-      return Linq4j.asEnumerable(new Iterable<Object[]>() {
-        @Override public Iterator<Object[]> iterator() {
-          return new Iterator<Object[]>() {
-            public boolean hasNext() {
-              return true;
-            }
+      return Linq4j.asEnumerable(() -> new Iterator<Object[]>() {
+        public boolean hasNext() {
+          return true;
+        }
 
-            public Object[] next() {
-              return ROW_GENERATOR.apply();
-            }
+        public Object[] next() {
+          return ROW_GENERATOR.apply();
+        }
 
-            public void remove() {
-              throw new UnsupportedOperationException();
-            }
-          };
+        public void remove() {
+          throw new UnsupportedOperationException();
         }
       });
     }
@@ -547,14 +525,10 @@ public class StreamTest {
       this.rows = rows;
     }
 
-    private final RelProtoDataType protoRowType = new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory a0) {
-        return a0.builder()
-            .add("ID", SqlTypeName.VARCHAR, 32)
-            .add("SUPPLIER", SqlTypeName.INTEGER)
-            .build();
-      }
-    };
+    private final RelProtoDataType protoRowType = a0 -> a0.builder()
+        .add("ID", SqlTypeName.VARCHAR, 32)
+        .add("SUPPLIER", SqlTypeName.INTEGER)
+        .build();
 
     public Enumerable<Object[]> scan(DataContext root) {
       return Linq4j.asEnumerable(rows);
@@ -565,7 +539,7 @@ public class StreamTest {
     }
 
     public Statistic getStatistic() {
-      return Statistics.of(200d, ImmutableList.<ImmutableBitSet>of());
+      return Statistics.of(200d, ImmutableList.of());
     }
 
     public Schema.TableType getJdbcTableType() {
@@ -577,8 +551,7 @@ public class StreamTest {
     }
 
     @Override public boolean rolledUpColumnValidInsideAgg(String column,
-                                                          SqlCall call, SqlNode parent,
-                                                          CalciteConnectionConfig config) {
+        SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
       return false;
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/TableFunctionTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/TableFunctionTest.java b/core/src/test/java/org/apache/calcite/test/TableFunctionTest.java
index b56d2f6..55ba318 100644
--- a/core/src/test/java/org/apache/calcite/test/TableFunctionTest.java
+++ b/core/src/test/java/org/apache/calcite/test/TableFunctionTest.java
@@ -27,8 +27,6 @@ import org.apache.calcite.schema.impl.TableFunctionImpl;
 import org.apache.calcite.sql.validate.SqlConformanceEnum;
 import org.apache.calcite.util.Smalls;
 
-import com.google.common.base.Function;
-
 import org.junit.Ignore;
 import org.junit.Test;
 
@@ -382,22 +380,18 @@ public class TableFunctionTest {
     final String q = "select *\n"
         + "from table(\"s\".\"fibonacci\"())";
     with().query(q)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet r) {
-                try {
-                  final List<Long> numbers = new ArrayList<>();
-                  while (r.next() && numbers.size() < 13) {
-                    numbers.add(r.getLong(1));
-                  }
-                  assertThat(numbers.toString(),
-                      is("[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]"));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .returns(r -> {
+          try {
+            final List<Long> numbers = new ArrayList<>();
+            while (r.next() && numbers.size() < 13) {
+              numbers.add(r.getLong(1));
+            }
+            assertThat(numbers.toString(),
+                is("[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]"));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testUserDefinedTableFunction7() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/UdfTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/UdfTest.java b/core/src/test/java/org/apache/calcite/test/UdfTest.java
index 6dc822a..10c7458 100644
--- a/core/src/test/java/org/apache/calcite/test/UdfTest.java
+++ b/core/src/test/java/org/apache/calcite/test/UdfTest.java
@@ -17,19 +17,15 @@
 package org.apache.calcite.test;
 
 import org.apache.calcite.adapter.enumerable.CallImplementor;
-import org.apache.calcite.adapter.enumerable.RexImpTable.NullAs;
-import org.apache.calcite.adapter.enumerable.RexToLixTranslator;
 import org.apache.calcite.adapter.java.ReflectiveSchema;
 import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.linq4j.Ord;
 import org.apache.calcite.linq4j.function.SemiStrict;
-import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.Types;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelProtoDataType;
-import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.schema.FunctionParameter;
 import org.apache.calcite.schema.ImplementableFunction;
 import org.apache.calcite.schema.ScalarFunction;
@@ -244,7 +240,7 @@ public class UdfTest {
         + "  POST.MY_INCREMENT(\"empid\", 10) as INCREMENTED_SALARY\n"
         + "from \"hr\".\"emps\"";
     post.add("V_EMP",
-        ViewTable.viewMacro(post, viewSql, ImmutableList.<String>of(),
+        ViewTable.viewMacro(post, viewSql, ImmutableList.of(),
             ImmutableList.of("POST", "V_EMP"), null));
 
     final String result = ""
@@ -998,14 +994,12 @@ public class UdfTest {
     protected abstract List<RelProtoDataType> getParams();
 
     @Override public CallImplementor getImplementor() {
-      return new CallImplementor() {
-        public Expression implement(RexToLixTranslator translator, RexCall call, NullAs nullAs) {
-          Method lookupMethod =
-              Types.lookupMethod(Smalls.AllTypesFunction.class,
-                  "arrayAppendFun", List.class, Integer.class);
-          return Expressions.call(lookupMethod,
-              translator.translateList(call.getOperands(), nullAs));
-        }
+      return (translator, call, nullAs) -> {
+        Method lookupMethod =
+            Types.lookupMethod(Smalls.AllTypesFunction.class,
+                "arrayAppendFun", List.class, Integer.class);
+        return Expressions.call(lookupMethod,
+            translator.translateList(call.getOperands(), nullAs));
       };
     }
   }
@@ -1020,17 +1014,9 @@ public class UdfTest {
 
     @Override public List<RelProtoDataType> getParams() {
       return ImmutableList.of(
-          new RelProtoDataType() {
-            public RelDataType apply(RelDataTypeFactory typeFactory) {
-              return typeFactory.createArrayType(
-                  typeFactory.createSqlType(SqlTypeName.INTEGER), -1);
-            }
-          },
-          new RelProtoDataType() {
-            public RelDataType apply(RelDataTypeFactory typeFactory) {
-              return typeFactory.createSqlType(SqlTypeName.INTEGER);
-            }
-          });
+          typeFactory -> typeFactory.createArrayType(
+              typeFactory.createSqlType(SqlTypeName.INTEGER), -1),
+          typeFactory -> typeFactory.createSqlType(SqlTypeName.INTEGER));
     }
   }
 
@@ -1044,17 +1030,9 @@ public class UdfTest {
 
     public List<RelProtoDataType> getParams() {
       return ImmutableList.of(
-          new RelProtoDataType() {
-            public RelDataType apply(RelDataTypeFactory typeFactory) {
-              return typeFactory.createArrayType(
-                  typeFactory.createSqlType(SqlTypeName.DOUBLE), -1);
-            }
-          },
-          new RelProtoDataType() {
-            public RelDataType apply(RelDataTypeFactory typeFactory) {
-              return typeFactory.createSqlType(SqlTypeName.INTEGER);
-            }
-          });
+          typeFactory -> typeFactory.createArrayType(
+              typeFactory.createSqlType(SqlTypeName.DOUBLE), -1),
+          typeFactory -> typeFactory.createSqlType(SqlTypeName.INTEGER));
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/concurrent/ConcurrentTestTimedCommandGenerator.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/concurrent/ConcurrentTestTimedCommandGenerator.java b/core/src/test/java/org/apache/calcite/test/concurrent/ConcurrentTestTimedCommandGenerator.java
index 4c48d35..ef48003 100644
--- a/core/src/test/java/org/apache/calcite/test/concurrent/ConcurrentTestTimedCommandGenerator.java
+++ b/core/src/test/java/org/apache/calcite/test/concurrent/ConcurrentTestTimedCommandGenerator.java
@@ -79,13 +79,9 @@ public class ConcurrentTestTimedCommandGenerator
       }
     }
 
-    return new Iterable<ConcurrentTestCommand>() {
-      public Iterator<ConcurrentTestCommand> iterator() {
-        return new TimedIterator<ConcurrentTestCommand>(
-            getCommands(threadId),
-            endTimeMillis);
-      }
-    };
+    return () -> new TimedIterator<ConcurrentTestCommand>(
+        getCommands(threadId),
+        endTimeMillis);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/tools/FrameworksTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/tools/FrameworksTest.java b/core/src/test/java/org/apache/calcite/tools/FrameworksTest.java
index 684cfe7..3aa4998 100644
--- a/core/src/test/java/org/apache/calcite/tools/FrameworksTest.java
+++ b/core/src/test/java/org/apache/calcite/tools/FrameworksTest.java
@@ -19,7 +19,6 @@ package org.apache.calcite.tools;
 import org.apache.calcite.DataContext;
 import org.apache.calcite.adapter.enumerable.EnumerableConvention;
 import org.apache.calcite.adapter.enumerable.EnumerableTableScan;
-import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.QueryProvider;
 import org.apache.calcite.linq4j.Queryable;
@@ -36,7 +35,6 @@ import org.apache.calcite.plan.RelTraitSet;
 import org.apache.calcite.plan.volcano.AbstractConverter;
 import org.apache.calcite.prepare.CalcitePrepareImpl;
 import org.apache.calcite.prepare.Prepare;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.TableModify;
@@ -72,7 +70,6 @@ import org.apache.calcite.test.CalciteAssert;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 
 import org.junit.Test;
@@ -95,55 +92,51 @@ import static org.junit.Assert.fail;
 public class FrameworksTest {
   @Test public void testOptimize() {
     RelNode x =
-        Frameworks.withPlanner(new Frameworks.PlannerAction<RelNode>() {
-          public RelNode apply(RelOptCluster cluster,
-              RelOptSchema relOptSchema,
-              SchemaPlus rootSchema) {
-            final RelDataTypeFactory typeFactory = cluster.getTypeFactory();
-            final Table table = new AbstractTable() {
-              public RelDataType getRowType(RelDataTypeFactory typeFactory) {
-                final RelDataType stringType =
-                    typeFactory.createJavaType(String.class);
-                final RelDataType integerType =
-                    typeFactory.createJavaType(Integer.class);
-                return typeFactory.builder()
-                    .add("s", stringType)
-                    .add("i", integerType)
-                    .build();
-              }
-            };
-
-            // "SELECT * FROM myTable"
-            final RelOptAbstractTable relOptTable = new RelOptAbstractTable(
-                relOptSchema,
-                "myTable",
-                table.getRowType(typeFactory)) {
-            };
-            final EnumerableTableScan tableRel =
-                EnumerableTableScan.create(cluster, relOptTable);
-
-            // "WHERE i > 1"
-            final RexBuilder rexBuilder = cluster.getRexBuilder();
-            final RexNode condition =
-                rexBuilder.makeCall(SqlStdOperatorTable.GREATER_THAN,
-                    rexBuilder.makeFieldAccess(
-                        rexBuilder.makeRangeReference(tableRel), "i", true),
-                    rexBuilder.makeExactLiteral(BigDecimal.ONE));
-            final LogicalFilter filter =
-                LogicalFilter.create(tableRel, condition);
-
-            // Specify that the result should be in Enumerable convention.
-            final RelNode rootRel = filter;
-            final RelOptPlanner planner = cluster.getPlanner();
-            RelTraitSet desiredTraits =
-                cluster.traitSet().replace(EnumerableConvention.INSTANCE);
-            final RelNode rootRel2 = planner.changeTraits(rootRel,
-                desiredTraits);
-            planner.setRoot(rootRel2);
-
-            // Now, plan.
-            return planner.findBestExp();
-          }
+        Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
+          final RelDataTypeFactory typeFactory = cluster.getTypeFactory();
+          final Table table = new AbstractTable() {
+            public RelDataType getRowType(RelDataTypeFactory typeFactory) {
+              final RelDataType stringType =
+                  typeFactory.createJavaType(String.class);
+              final RelDataType integerType =
+                  typeFactory.createJavaType(Integer.class);
+              return typeFactory.builder()
+                  .add("s", stringType)
+                  .add("i", integerType)
+                  .build();
+            }
+          };
+
+          // "SELECT * FROM myTable"
+          final RelOptAbstractTable relOptTable = new RelOptAbstractTable(
+              relOptSchema,
+              "myTable",
+              table.getRowType(typeFactory)) {
+          };
+          final EnumerableTableScan tableRel =
+              EnumerableTableScan.create(cluster, relOptTable);
+
+          // "WHERE i > 1"
+          final RexBuilder rexBuilder = cluster.getRexBuilder();
+          final RexNode condition =
+              rexBuilder.makeCall(SqlStdOperatorTable.GREATER_THAN,
+                  rexBuilder.makeFieldAccess(
+                      rexBuilder.makeRangeReference(tableRel), "i", true),
+                  rexBuilder.makeExactLiteral(BigDecimal.ONE));
+          final LogicalFilter filter =
+              LogicalFilter.create(tableRel, condition);
+
+          // Specify that the result should be in Enumerable convention.
+          final RelNode rootRel = filter;
+          final RelOptPlanner planner = cluster.getPlanner();
+          RelTraitSet desiredTraits =
+              cluster.traitSet().replace(EnumerableConvention.INSTANCE);
+          final RelNode rootRel2 = planner.changeTraits(rootRel,
+              desiredTraits);
+          planner.setRoot(rootRel2);
+
+          // Now, plan.
+          return planner.findBestExp();
         });
     String s =
         RelOptUtil.dumpPlan("", x, SqlExplainFormat.TEXT,
@@ -271,38 +264,35 @@ public class FrameworksTest {
   @Test public void testJdbcValues() throws Exception {
     CalciteAssert.that()
         .with(CalciteAssert.SchemaSpec.JDBC_SCOTT)
-        .doWithConnection(new Function<CalciteConnection, Void>() {
-          public Void apply(CalciteConnection conn) {
-            try {
-              final FrameworkConfig config = Frameworks.newConfigBuilder()
-                  .defaultSchema(conn.getRootSchema())
-                  .build();
-              final RelBuilder builder = RelBuilder.create(config);
-              final RelRunner runner = conn.unwrap(RelRunner.class);
-
-              final RelNode values =
-                  builder.values(new String[]{"a", "b"}, "X", 1, "Y", 2)
-                      .project(builder.field("a"))
-                      .build();
-
-              // If you run the "values" query before the "scan" query,
-              // everything works fine. JdbcValues is never instantiated in any
-              // of the 3 queries.
-              if (false) {
-                runner.prepare(values).executeQuery();
-              }
-
-              final RelNode scan = builder.scan("JDBC_SCOTT", "EMP").build();
-              runner.prepare(scan).executeQuery();
-              builder.clear();
-
-              // running this after the scott query causes the exception
-              RelRunner runner2 = conn.unwrap(RelRunner.class);
-              runner2.prepare(values).executeQuery();
-              return null;
-            } catch (Exception e) {
-              throw new RuntimeException(e);
+        .doWithConnection(connection -> {
+          try {
+            final FrameworkConfig config = Frameworks.newConfigBuilder()
+                .defaultSchema(connection.getRootSchema())
+                .build();
+            final RelBuilder builder = RelBuilder.create(config);
+            final RelRunner runner = connection.unwrap(RelRunner.class);
+
+            final RelNode values =
+                builder.values(new String[]{"a", "b"}, "X", 1, "Y", 2)
+                    .project(builder.field("a"))
+                    .build();
+
+            // If you run the "values" query before the "scan" query,
+            // everything works fine. JdbcValues is never instantiated in any
+            // of the 3 queries.
+            if (false) {
+              runner.prepare(values).executeQuery();
             }
+
+            final RelNode scan = builder.scan("JDBC_SCOTT", "EMP").build();
+            runner.prepare(scan).executeQuery();
+            builder.clear();
+
+            // running this after the scott query causes the exception
+            RelRunner runner2 = connection.unwrap(RelRunner.class);
+            runner2.prepare(values).executeQuery();
+          } catch (Exception e) {
+            throw new RuntimeException(e);
           }
         });
   }
@@ -387,7 +377,7 @@ public class FrameworksTest {
     public Statistic getStatistic() {
       return Statistics.of(15D,
           ImmutableList.of(ImmutableBitSet.of(0)),
-          ImmutableList.<RelCollation>of());
+          ImmutableList.of());
     }
 
     public Enumerable<Object[]> scan(DataContext root, List<RexNode> filters,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/tools/PlannerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/tools/PlannerTest.java b/core/src/test/java/org/apache/calcite/tools/PlannerTest.java
index 4150d85..da54ee8 100644
--- a/core/src/test/java/org/apache/calcite/tools/PlannerTest.java
+++ b/core/src/test/java/org/apache/calcite/tools/PlannerTest.java
@@ -60,7 +60,6 @@ import org.apache.calcite.sql.SqlExplainLevel;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.SqlNode;
-import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlOperatorTable;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.parser.SqlParseException;
@@ -196,7 +195,7 @@ public class PlannerTest {
     SqlOperatorTable opTab =
         ChainedSqlOperatorTable.of(stdOpTab,
             new ListSqlOperatorTable(
-                ImmutableList.<SqlOperator>of(new MyCountAggFunction())));
+                ImmutableList.of(new MyCountAggFunction())));
     final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
     final FrameworkConfig config = Frameworks.newConfigBuilder()
         .defaultSchema(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/BitSetsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/BitSetsTest.java b/core/src/test/java/org/apache/calcite/util/BitSetsTest.java
index 4581e9a..fc16c86 100644
--- a/core/src/test/java/org/apache/calcite/util/BitSetsTest.java
+++ b/core/src/test/java/org/apache/calcite/util/BitSetsTest.java
@@ -16,14 +16,13 @@
  */
 package org.apache.calcite.util;
 
-import com.google.common.collect.Maps;
-
 import org.junit.Test;
 
 import java.util.Arrays;
 import java.util.BitSet;
 import java.util.Collections;
 import java.util.SortedMap;
+import java.util.TreeMap;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.junit.Assert.assertEquals;
@@ -192,11 +191,11 @@ public class BitSetsTest {
    * Tests the method {@link BitSets#closure(java.util.SortedMap)}
    */
   @Test public void testClosure() {
-    final SortedMap<Integer, BitSet> empty = Maps.newTreeMap();
+    final SortedMap<Integer, BitSet> empty = new TreeMap<>();
     assertThat(BitSets.closure(empty), equalTo(empty));
 
     // Map with an an entry for each position.
-    final SortedMap<Integer, BitSet> map = Maps.newTreeMap();
+    final SortedMap<Integer, BitSet> map = new TreeMap<>();
     map.put(0, BitSets.of(3));
     map.put(1, BitSets.of());
     map.put(2, BitSets.of(7));
@@ -217,7 +216,7 @@ public class BitSetsTest {
     assertThat("argument modified", map.toString(), equalTo(original));
 
     // Now a similar map with missing entries. Same result.
-    final SortedMap<Integer, BitSet> map2 = Maps.newTreeMap();
+    final SortedMap<Integer, BitSet> map2 = new TreeMap<>();
     map2.put(0, BitSets.of(3));
     map2.put(2, BitSets.of(7));
     map2.put(3, BitSets.of(4, 12));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/ChunkListTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/ChunkListTest.java b/core/src/test/java/org/apache/calcite/util/ChunkListTest.java
index efb1b09..4069c3e 100644
--- a/core/src/test/java/org/apache/calcite/util/ChunkListTest.java
+++ b/core/src/test/java/org/apache/calcite/util/ChunkListTest.java
@@ -17,7 +17,6 @@
 package org.apache.calcite.util;
 
 import org.apache.calcite.linq4j.function.Function0;
-import org.apache.calcite.linq4j.function.Function1;
 
 import com.google.common.collect.ImmutableList;
 
@@ -383,22 +382,7 @@ public class ChunkListTest {
     //noinspection unchecked
     final Iterable<Pair<Function0<List<Integer>>, String>> factories0 =
         Pair.zip(
-            Arrays.asList(
-                new Function0<List<Integer>>() {
-                  public List<Integer> apply() {
-                    return new ArrayList<>();
-                  }
-                },
-                new Function0<List<Integer>>() {
-                  public List<Integer> apply() {
-                    return new LinkedList<>();
-                  }
-                },
-                new Function0<List<Integer>>() {
-                  public List<Integer> apply() {
-                    return new ChunkList<>();
-                  }
-                }),
+            Arrays.asList(ArrayList::new, LinkedList::new, ChunkList::new),
             Arrays.asList("ArrayList", "LinkedList", "ChunkList-64"));
     final List<Pair<Function0<List<Integer>>, String>> factories1 =
         new ArrayList<>();
@@ -412,63 +396,52 @@ public class ChunkListTest {
             Arrays.asList(100000, 1000000, 10000000),
             Arrays.asList("100k", "1m", "10m"));
     for (final Pair<Function0<List<Integer>>, String> pair : factories) {
-      new Benchmark(
-          "add 10m values, " + pair.right,
-          new Function1<Benchmark.Statistician, Void>() {
-            public Void apply(Benchmark.Statistician statistician) {
-              final List<Integer> list = pair.left.apply();
-              long start = System.currentTimeMillis();
-              for (int i = 0; i < 10000000; i++) {
-                list.add(1);
-              }
-              statistician.record(start);
-              return null;
-            }
-          },
-          10).run();
+      new Benchmark("add 10m values, " + pair.right, statistician -> {
+        final List<Integer> list = pair.left.apply();
+        long start = System.currentTimeMillis();
+        for (int i = 0; i < 10000000; i++) {
+          list.add(1);
+        }
+        statistician.record(start);
+        return null;
+      },
+      10).run();
     }
     for (final Pair<Function0<List<Integer>>, String> pair : factories) {
-      new Benchmark(
-          "iterate over 10m values, " + pair.right,
-          new Function1<Benchmark.Statistician, Void>() {
-            public Void apply(Benchmark.Statistician statistician) {
-              final List<Integer> list = pair.left.apply();
-              list.addAll(Collections.nCopies(10000000, 1));
-              long start = System.currentTimeMillis();
-              int count = 0;
-              for (Integer integer : list) {
-                count += integer;
-              }
-              statistician.record(start);
-              assert count == 10000000;
-              return null;
-            }
-          },
-          10).run();
+      new Benchmark("iterate over 10m values, " + pair.right, statistician -> {
+        final List<Integer> list = pair.left.apply();
+        list.addAll(Collections.nCopies(10000000, 1));
+        long start = System.currentTimeMillis();
+        int count = 0;
+        for (Integer integer : list) {
+          count += integer;
+        }
+        statistician.record(start);
+        assert count == 10000000;
+        return null;
+      },
+      10).run();
     }
     for (final Pair<Function0<List<Integer>>, String> pair : factories) {
       for (final Pair<Integer, String> size : sizes) {
         if (size.left > 1000000) {
           continue;
         }
-        new Benchmark(
-            "delete 10% of " + size.right + " values, " + pair.right,
-            new Function1<Benchmark.Statistician, Void>() {
-              public Void apply(Benchmark.Statistician statistician) {
-                final List<Integer> list = pair.left.apply();
-                list.addAll(Collections.nCopies(size.left, 1));
-                long start = System.currentTimeMillis();
-                int n = 0;
-                for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
-                  Integer integer = it.next();
-                  Util.discard(integer);
-                  if (n++ % 10 == 0) {
-                    it.remove();
-                  }
+        new Benchmark("delete 10% of " + size.right + " values, " + pair.right,
+            statistician -> {
+              final List<Integer> list = pair.left.apply();
+              list.addAll(Collections.nCopies(size.left, 1));
+              long start = System.currentTimeMillis();
+              int n = 0;
+              for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
+                Integer integer = it.next();
+                Util.discard(integer);
+                if (n++ % 10 == 0) {
+                  it.remove();
                 }
-                statistician.record(start);
-                return null;
               }
+              statistician.record(start);
+              return null;
             },
             10).run();
       }
@@ -479,24 +452,21 @@ public class ChunkListTest {
           continue;
         }
         new Benchmark("get from " + size.right + " values, "
-            + (size.left / 1000) + " times, " + pair.right,
-            new Function1<Benchmark.Statistician, Void>() {
-              public Void apply(Benchmark.Statistician statistician) {
-                final List<Integer> list = pair.left.apply();
-                list.addAll(Collections.nCopies(size.left, 1));
-                final int probeCount = size.left / 1000;
-                final Random random = new Random(1);
-                long start = System.currentTimeMillis();
-                int n = 0;
-                for (int i = 0; i < probeCount; i++) {
-                  n += list.get(random.nextInt(list.size()));
-                }
-                assert n == probeCount;
-                statistician.record(start);
-                return null;
-              }
-            },
-            10).run();
+            + (size.left / 1000) + " times, " + pair.right, statistician -> {
+          final List<Integer> list = pair.left.apply();
+          list.addAll(Collections.nCopies(size.left, 1));
+          final int probeCount = size.left / 1000;
+          final Random random = new Random(1);
+          long start = System.currentTimeMillis();
+          int n = 0;
+          for (int i = 0; i < probeCount; i++) {
+            n += list.get(random.nextInt(list.size()));
+          }
+          assert n == probeCount;
+          statistician.record(start);
+          return null;
+        },
+        10).run();
       }
     }
     for (final Pair<Function0<List<Integer>>, String> pair : factories) {
@@ -507,40 +477,37 @@ public class ChunkListTest {
         new Benchmark(
             "add " + size.right
             + " values, delete 10%, insert 20%, get 1%, using "
-            + pair.right,
-            new Function1<Benchmark.Statistician, Void>() {
-              public Void apply(Benchmark.Statistician statistician) {
-                final List<Integer> list = pair.left.apply();
-                final int probeCount = size.left / 100;
-                long start = System.currentTimeMillis();
-                list.addAll(Collections.nCopies(size.left, 1));
-                final Random random = new Random(1);
-                for (Iterator<Integer> it = list.iterator();
-                     it.hasNext();) {
-                  Integer integer = it.next();
-                  Util.discard(integer);
-                  if (random.nextInt(10) == 0) {
-                    it.remove();
-                  }
-                }
-                for (ListIterator<Integer> it = list.listIterator();
-                     it.hasNext();) {
-                  Integer integer = it.next();
-                  Util.discard(integer);
-                  if (random.nextInt(5) == 0) {
-                    it.add(2);
-                  }
-                }
-                int n = 0;
-                for (int i = 0; i < probeCount; i++) {
-                  n += list.get(random.nextInt(list.size()));
-                }
-                assert n > probeCount;
-                statistician.record(start);
-                return null;
-              }
-            },
-            10).run();
+            + pair.right, statistician -> {
+          final List<Integer> list = pair.left.apply();
+          final int probeCount = size.left / 100;
+          long start = System.currentTimeMillis();
+          list.addAll(Collections.nCopies(size.left, 1));
+          final Random random = new Random(1);
+          for (Iterator<Integer> it = list.iterator();
+               it.hasNext();) {
+            Integer integer = it.next();
+            Util.discard(integer);
+            if (random.nextInt(10) == 0) {
+              it.remove();
+            }
+          }
+          for (ListIterator<Integer> it = list.listIterator();
+               it.hasNext();) {
+            Integer integer = it.next();
+            Util.discard(integer);
+            if (random.nextInt(5) == 0) {
+              it.add(2);
+            }
+          }
+          int n = 0;
+          for (int i = 0; i < probeCount; i++) {
+            n += list.get(random.nextInt(list.size()));
+          }
+          assert n > probeCount;
+          statistician.record(start);
+          return null;
+        },
+        10).run();
       }
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/ImmutableBitSetTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/ImmutableBitSetTest.java b/core/src/test/java/org/apache/calcite/util/ImmutableBitSetTest.java
index 680bed4..b8dd2e6 100644
--- a/core/src/test/java/org/apache/calcite/util/ImmutableBitSetTest.java
+++ b/core/src/test/java/org/apache/calcite/util/ImmutableBitSetTest.java
@@ -19,7 +19,6 @@ package org.apache.calcite.util;
 import org.apache.calcite.runtime.Utilities;
 
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
 
 import org.junit.Test;
 
@@ -30,6 +29,7 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.SortedMap;
+import java.util.TreeMap;
 
 import static org.hamcrest.CoreMatchers.anyOf;
 import static org.hamcrest.CoreMatchers.equalTo;
@@ -154,7 +154,7 @@ public class ImmutableBitSetTest {
 
   @Test public void testCompare2() {
     final List<ImmutableBitSet> sorted = getSortedList();
-    Collections.sort(sorted, ImmutableBitSet.COMPARATOR);
+    sorted.sort(ImmutableBitSet.COMPARATOR);
     assertThat(sorted.toString(),
         equalTo("[{0, 1, 3}, {0, 1}, {1, 1000}, {1}, {1}, {2, 3}, {}]"));
   }
@@ -390,12 +390,12 @@ public class ImmutableBitSetTest {
   /** Tests the method
    * {@link org.apache.calcite.util.BitSets#closure(java.util.SortedMap)}. */
   @Test public void testClosure() {
-    final SortedMap<Integer, ImmutableBitSet> empty = Maps.newTreeMap();
+    final SortedMap<Integer, ImmutableBitSet> empty = new TreeMap<>();
     assertThat(ImmutableBitSet.closure(empty), equalTo(empty));
 
     // Currently you need an entry for each position, otherwise you get an NPE.
     // We should fix that.
-    final SortedMap<Integer, ImmutableBitSet> map = Maps.newTreeMap();
+    final SortedMap<Integer, ImmutableBitSet> map = new TreeMap<>();
     map.put(0, ImmutableBitSet.of(3));
     map.put(1, ImmutableBitSet.of());
     map.put(2, ImmutableBitSet.of(7));
@@ -416,7 +416,7 @@ public class ImmutableBitSetTest {
     assertThat("argument modified", map.toString(), equalTo(original));
 
     // Now a similar map with missing entries. Same result.
-    final SortedMap<Integer, ImmutableBitSet> map2 = Maps.newTreeMap();
+    final SortedMap<Integer, ImmutableBitSet> map2 = new TreeMap<>();
     map2.put(0, ImmutableBitSet.of(3));
     map2.put(2, ImmutableBitSet.of(7));
     map2.put(3, ImmutableBitSet.of(4, 12));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/PartiallyOrderedSetTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/PartiallyOrderedSetTest.java b/core/src/test/java/org/apache/calcite/util/PartiallyOrderedSetTest.java
index 8a6a9da..586562b 100644
--- a/core/src/test/java/org/apache/calcite/util/PartiallyOrderedSetTest.java
+++ b/core/src/test/java/org/apache/calcite/util/PartiallyOrderedSetTest.java
@@ -18,8 +18,6 @@ package org.apache.calcite.util;
 
 import org.apache.calcite.test.CalciteAssert;
 
-import com.google.common.base.Function;
-
 import org.junit.Assume;
 import org.junit.Test;
 
@@ -28,9 +26,11 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Objects;
 import java.util.Random;
 import java.util.Set;
 import java.util.TreeSet;
+import java.util.function.Function;
 
 import static org.hamcrest.CoreMatchers.nullValue;
 import static org.hamcrest.core.Is.is;
@@ -51,58 +51,44 @@ public class PartiallyOrderedSetTest {
   final Random random = new Random(seed);
 
   static final PartiallyOrderedSet.Ordering<String> STRING_SUBSET_ORDERING =
-      new PartiallyOrderedSet.Ordering<String>() {
-        public boolean lessThan(String e1, String e2) {
-          // e1 < e2 if every char in e1 is also in e2
-          for (int i = 0; i < e1.length(); i++) {
-            if (e2.indexOf(e1.charAt(i)) < 0) {
-              return false;
-            }
+      (e1, e2) -> {
+        // e1 < e2 if every char in e1 is also in e2
+        for (int i = 0; i < e1.length(); i++) {
+          if (e2.indexOf(e1.charAt(i)) < 0) {
+            return false;
           }
-          return true;
         }
+        return true;
       };
 
-  // Integers, ordered by division. Top is 1, its children are primes,
-  // etc.
-  static final PartiallyOrderedSet.Ordering<Integer> IS_DIVISOR =
-      new PartiallyOrderedSet.Ordering<Integer>() {
-        public boolean lessThan(Integer e1, Integer e2) {
-          return e2 % e1 == 0;
-        }
-      };
+  /** As an ordering, integers are ordered by division.
+   * Top is 1, its children are primes, etc. */
+  private static boolean isDivisor(int e1, int e2) {
+    return e2 % e1 == 0;
+  }
 
-  // Bottom is 1, parents are primes, etc.
-  static final PartiallyOrderedSet.Ordering<Integer> IS_DIVISOR_INVERSE =
-      new PartiallyOrderedSet.Ordering<Integer>() {
-        public boolean lessThan(Integer e1, Integer e2) {
-          return e1 % e2 == 0;
-        }
-      };
+  /** As an ordering, bottom is 1, parents are primes, etc. */
+  private static boolean isDivisorInverse(Integer e1, Integer e2) {
+    return isDivisor(e2, e1);
+  }
 
-  // Ordered by bit inclusion. E.g. the children of 14 (1110) are
-  // 12 (1100), 10 (1010) and 6 (0110).
-  static final PartiallyOrderedSet.Ordering<Integer> IS_BIT_SUBSET =
-      new PartiallyOrderedSet.Ordering<Integer>() {
-        public boolean lessThan(Integer e1, Integer e2) {
-          return (e2 & e1) == e2;
-        }
-      };
+  /** As an ordering, integers are ordered by bit inclusion.
+   * E.g. the children of 14 (1110) are 12 (1100), 10 (1010) and 6 (0110). */
+  private static boolean isBitSubset(int e1, int e2) {
+    return (e2 & e1) == e2;
+  }
 
-  // Ordered by bit inclusion. E.g. the children of 14 (1110) are
-  // 12 (1100), 10 (1010) and 6 (0110).
-  static final PartiallyOrderedSet.Ordering<Integer> IS_BIT_SUPERSET =
-      new PartiallyOrderedSet.Ordering<Integer>() {
-        public boolean lessThan(Integer e1, Integer e2) {
-          return (e2 & e1) == e1;
-        }
-      };
+  /** As an ordering, integers are ordered by bit inclusion.
+   * E.g. the parents of 14 (1110) are 12 (1100), 10 (1010) and 6 (0110). */
+  private static boolean isBitSuperset(Integer e1, Integer e2) {
+    return (e2 & e1) == e1;
+  }
 
   @Test public void testPoset() {
     String empty = "''";
     String abcd = "'abcd'";
-    PartiallyOrderedSet<String> poset =
-        new PartiallyOrderedSet<String>(STRING_SUBSET_ORDERING);
+    final PartiallyOrderedSet<String> poset =
+        new PartiallyOrderedSet<>(STRING_SUBSET_ORDERING);
     assertEquals(0, poset.size());
 
     final StringBuilder buf = new StringBuilder();
@@ -195,8 +181,8 @@ public class PartiallyOrderedSetTest {
   }
 
   @Test public void testPosetTricky() {
-    PartiallyOrderedSet<String> poset =
-        new PartiallyOrderedSet<String>(STRING_SUBSET_ORDERING);
+    final PartiallyOrderedSet<String> poset =
+        new PartiallyOrderedSet<>(STRING_SUBSET_ORDERING);
 
     // A tricky little poset with 4 elements:
     // {a <= ab and ac, b < ab, ab, ac}
@@ -213,7 +199,7 @@ public class PartiallyOrderedSetTest {
 
   @Test public void testPosetBits() {
     final PartiallyOrderedSet<Integer> poset =
-        new PartiallyOrderedSet<Integer>(IS_BIT_SUPERSET);
+        new PartiallyOrderedSet<>(PartiallyOrderedSetTest::isBitSuperset);
     poset.add(2112); // {6, 11} i.e. 64 + 2048
     poset.add(2240); // {6, 7, 11} i.e. 64 + 128 + 2048
     poset.add(2496); // {6, 7, 8, 11} i.e. 64 + 128 + 256 + 2048
@@ -226,7 +212,7 @@ public class PartiallyOrderedSetTest {
 
   @Test public void testPosetBitsLarge() {
     final PartiallyOrderedSet<Integer> poset =
-        new PartiallyOrderedSet<>(IS_BIT_SUPERSET);
+        new PartiallyOrderedSet<>(PartiallyOrderedSetTest::isBitSuperset);
     checkPosetBitsLarge(poset, 30000, 2921, 164782);
   }
 
@@ -234,11 +220,9 @@ public class PartiallyOrderedSetTest {
     Assume.assumeTrue("too slow to run every day", CalciteAssert.ENABLE_SLOW);
     final int n = 30000;
     final PartiallyOrderedSet<Integer> poset =
-        new PartiallyOrderedSet<>(IS_BIT_SUPERSET,
-          new Function<Integer, Iterable<Integer>>() {
-            public Iterable<Integer> apply(Integer input) {
-              final int i = input;
-              int r = i; // bits not yet cleared
+        new PartiallyOrderedSet<>(PartiallyOrderedSetTest::isBitSuperset,
+            (Function<Integer, Iterable<Integer>>) i -> {
+              int r = Objects.requireNonNull(i); // bits not yet cleared
               final List<Integer> list = new ArrayList<>();
               for (int z = 1; r != 0; z <<= 1) {
                 if ((i & z) != 0) {
@@ -247,11 +231,9 @@ public class PartiallyOrderedSetTest {
                 }
               }
               return list;
-            }
-          },
-          new Function<Integer, Iterable<Integer>>() {
-            public Iterable<Integer> apply(Integer input) {
-              final int i = input;
+            },
+            i -> {
+              Objects.requireNonNull(i);
               final List<Integer> list = new ArrayList<>();
               for (int z = 1; z <= n; z <<= 1) {
                 if ((i & z) == 0) {
@@ -259,8 +241,7 @@ public class PartiallyOrderedSetTest {
                 }
               }
               return list;
-            }
-          });
+            });
     checkPosetBitsLarge(poset, n, 2921, 11961);
   }
 
@@ -286,7 +267,7 @@ public class PartiallyOrderedSetTest {
 
   @Test public void testPosetBitsRemoveParent() {
     final PartiallyOrderedSet<Integer> poset =
-        new PartiallyOrderedSet<Integer>(IS_BIT_SUPERSET);
+        new PartiallyOrderedSet<>(PartiallyOrderedSetTest::isBitSuperset);
     poset.add(66); // {bit 2, bit 6}
     poset.add(68); // {bit 3, bit 6}
     poset.add(72); // {bit 4, bit 6}
@@ -298,13 +279,14 @@ public class PartiallyOrderedSetTest {
 
   @Test public void testDivisorPoset() {
     PartiallyOrderedSet<Integer> integers =
-        new PartiallyOrderedSet<Integer>(IS_DIVISOR, range(1, 1000));
+        new PartiallyOrderedSet<>(PartiallyOrderedSetTest::isDivisor,
+            range(1, 1000));
     assertEquals(
         "[1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60]",
-        new TreeSet<Integer>(integers.getDescendants(120)).toString());
+        new TreeSet<>(integers.getDescendants(120)).toString());
     assertEquals(
         "[240, 360, 480, 600, 720, 840, 960]",
-        new TreeSet<Integer>(integers.getAncestors(120)).toString());
+        new TreeSet<>(integers.getAncestors(120)).toString());
     assertTrue(integers.getDescendants(1).isEmpty());
     assertEquals(
         998,
@@ -313,14 +295,15 @@ public class PartiallyOrderedSetTest {
   }
 
   @Test public void testDivisorSeries() {
-    checkPoset(IS_DIVISOR, DEBUG, range(1, SCALE * 3), false);
+    checkPoset(PartiallyOrderedSetTest::isDivisor, DEBUG, range(1, SCALE * 3),
+        false);
   }
 
   @Test public void testDivisorRandom() {
     boolean ok = false;
     try {
-      checkPoset(
-          IS_DIVISOR, DEBUG, random(random, SCALE, SCALE * 3), false);
+      checkPoset(PartiallyOrderedSetTest::isDivisor, DEBUG,
+          random(random, SCALE, SCALE * 3), false);
       ok = true;
     } finally {
       if (!ok) {
@@ -332,8 +315,8 @@ public class PartiallyOrderedSetTest {
   @Test public void testDivisorRandomWithRemoval() {
     boolean ok = false;
     try {
-      checkPoset(
-          IS_DIVISOR, DEBUG, random(random, SCALE, SCALE * 3), true);
+      checkPoset(PartiallyOrderedSetTest::isDivisor, DEBUG,
+          random(random, SCALE, SCALE * 3), true);
       ok = true;
     } finally {
       if (!ok) {
@@ -343,14 +326,14 @@ public class PartiallyOrderedSetTest {
   }
 
   @Test public void testDivisorInverseSeries() {
-    checkPoset(IS_DIVISOR_INVERSE, DEBUG, range(1, SCALE * 3), false);
+    checkPoset(PartiallyOrderedSetTest::isDivisorInverse, DEBUG,
+        range(1, SCALE * 3), false);
   }
 
   @Test public void testDivisorInverseRandom() {
     boolean ok = false;
     try {
-      checkPoset(
-          IS_DIVISOR_INVERSE, DEBUG, random(random, SCALE, SCALE * 3),
+      checkPoset(PartiallyOrderedSetTest::isDivisorInverse, DEBUG, random(random, SCALE, SCALE * 3),
           false);
       ok = true;
     } finally {
@@ -363,8 +346,7 @@ public class PartiallyOrderedSetTest {
   @Test public void testDivisorInverseRandomWithRemoval() {
     boolean ok = false;
     try {
-      checkPoset(
-          IS_DIVISOR_INVERSE, DEBUG, random(random, SCALE, SCALE * 3),
+      checkPoset(PartiallyOrderedSetTest::isDivisorInverse, DEBUG, random(random, SCALE, SCALE * 3),
           true);
       ok = true;
     } finally {
@@ -375,14 +357,14 @@ public class PartiallyOrderedSetTest {
   }
 
   @Test public void testSubsetSeries() {
-    checkPoset(IS_BIT_SUBSET, DEBUG, range(1, SCALE / 2), false);
+    checkPoset(PartiallyOrderedSetTest::isBitSubset, DEBUG, range(1, SCALE / 2), false);
   }
 
   @Test public void testSubsetRandom() {
     boolean ok = false;
     try {
-      checkPoset(
-          IS_BIT_SUBSET, DEBUG, random(random, SCALE / 4, SCALE), false);
+      checkPoset(PartiallyOrderedSetTest::isBitSubset, DEBUG,
+          random(random, SCALE / 4, SCALE), false);
       ok = true;
     } finally {
       if (!ok) {
@@ -404,7 +386,7 @@ public class PartiallyOrderedSetTest {
       Iterable<Integer> generator,
       boolean remove) {
     final PartiallyOrderedSet<Integer> poset =
-        new PartiallyOrderedSet<Integer>(ordering);
+        new PartiallyOrderedSet<>(ordering);
     int n = 0;
     int z = 0;
     if (debug) {
@@ -464,7 +446,7 @@ public class PartiallyOrderedSetTest {
 
   private static Iterable<Integer> random(
       Random random, final int size, final int max) {
-    final Set<Integer> set = new LinkedHashSet<Integer>();
+    final Set<Integer> set = new LinkedHashSet<>();
     while (set.size() < size) {
       set.add(random.nextInt(max) + 1);
     }
@@ -472,9 +454,7 @@ public class PartiallyOrderedSetTest {
   }
 
   private static void assertEqualsList(String expected, List<String> ss) {
-    assertEquals(
-        expected,
-        new TreeSet<String>(ss).toString());
+    assertEquals(expected, new TreeSet<>(ss).toString());
   }
 
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/PermutationTestCase.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/PermutationTestCase.java b/core/src/test/java/org/apache/calcite/util/PermutationTestCase.java
index 75c78c0..2fe6ed2 100644
--- a/core/src/test/java/org/apache/calcite/util/PermutationTestCase.java
+++ b/core/src/test/java/org/apache/calcite/util/PermutationTestCase.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.util;
 
-
 import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
 import org.apache.calcite.rel.core.Project;
 import org.apache.calcite.rel.type.RelDataType;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/PrecedenceClimbingParserTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/PrecedenceClimbingParserTest.java b/core/src/test/java/org/apache/calcite/util/PrecedenceClimbingParserTest.java
index 3fbeac4..0988430 100644
--- a/core/src/test/java/org/apache/calcite/util/PrecedenceClimbingParserTest.java
+++ b/core/src/test/java/org/apache/calcite/util/PrecedenceClimbingParserTest.java
@@ -134,17 +134,12 @@ public class PrecedenceClimbingParserTest {
         .infix("and", 2, true)
         .atom("price")
         .special("between", 3, 3,
-            new PrecedenceClimbingParser.Special() {
-              public PrecedenceClimbingParser.Result apply(
-                  PrecedenceClimbingParser parser,
-                  PrecedenceClimbingParser.SpecialOp op) {
-                return new PrecedenceClimbingParser.Result(op.previous,
+            (parser, op) ->
+                new PrecedenceClimbingParser.Result(op.previous,
                     op.next.next.next,
                     parser.call(op,
                         ImmutableList.of(op.previous, op.next,
-                            op.next.next.next)));
-              }
-            })
+                            op.next.next.next))))
         .atom("1")
         .infix("+", 5, true)
         .atom("2")

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/Smalls.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/Smalls.java b/core/src/test/java/org/apache/calcite/util/Smalls.java
index bffeca6..46ae6a3 100644
--- a/core/src/test/java/org/apache/calcite/util/Smalls.java
+++ b/core/src/test/java/org/apache/calcite/util/Smalls.java
@@ -27,14 +27,11 @@ import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.QueryProvider;
 import org.apache.calcite.linq4j.Queryable;
 import org.apache.calcite.linq4j.function.Deterministic;
-import org.apache.calcite.linq4j.function.Function1;
-import org.apache.calcite.linq4j.function.Function2;
 import org.apache.calcite.linq4j.function.Parameter;
 import org.apache.calcite.linq4j.function.SemiStrict;
 import org.apache.calcite.linq4j.tree.Types;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
-import org.apache.calcite.rel.type.RelProtoDataType;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.runtime.SqlFunctions;
 import org.apache.calcite.schema.QueryableTable;
@@ -67,7 +64,6 @@ import java.util.concurrent.atomic.AtomicInteger;
 import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.assertThat;
 
-
 /**
  * Holder for various classes and functions used in tests as user-defined
  * functions and so forth.
@@ -303,11 +299,7 @@ public class Smalls {
       public <T> Queryable<T> asQueryable(QueryProvider queryProvider,
           SchemaPlus schema, String tableName) {
         final Enumerable<Integer> enumerable =
-            a.select(new Function1<Object[], Integer>() {
-              public Integer apply(Object[] a0) {
-                return offset + ((Integer) a0[0]);
-              }
-            });
+            a.select(a0 -> offset + ((Integer) a0[0]));
         //noinspection unchecked
         return (Queryable) enumerable.asQueryable();
       }
@@ -330,11 +322,7 @@ public class Smalls {
       public <T> Queryable<T> asQueryable(QueryProvider queryProvider,
           SchemaPlus schema, String tableName) {
         final Enumerable<Integer> enumerable =
-            a.zip(b, new Function2<Object[], IntString, Integer>() {
-              public Integer apply(Object[] v0, IntString v1) {
-                return ((Integer) v0[1]) + v1.n + offset;
-              }
-            });
+            a.zip(b, (v0, v1) -> ((Integer) v0[1]) + v1.n + offset);
         //noinspection unchecked
         return (Queryable) enumerable.asQueryable();
       }
@@ -342,39 +330,26 @@ public class Smalls {
   }
 
   public static TranslatableTable view(String s) {
-    return new ViewTable(Object.class,
-        new RelProtoDataType() {
-          public RelDataType apply(RelDataTypeFactory typeFactory) {
-            return typeFactory.builder().add("c", SqlTypeName.INTEGER)
-                .build();
-          }
-        }, "values (1), (3), " + s, ImmutableList.<String>of(), Arrays.asList("view"));
+    return new ViewTable(Object.class, typeFactory ->
+        typeFactory.builder().add("c", SqlTypeName.INTEGER).build(),
+        "values (1), (3), " + s, ImmutableList.of(), Arrays.asList("view"));
   }
 
   public static TranslatableTable strView(String s) {
-    return new ViewTable(Object.class,
-        new RelProtoDataType() {
-          public RelDataType apply(RelDataTypeFactory typeFactory) {
-            return typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100)
-                    .build();
-          }
-        }, "values (" + CalciteSqlDialect.DEFAULT.quoteStringLiteral(s) + ")",
-        ImmutableList.<String>of(), Arrays.asList("view"));
+    return new ViewTable(Object.class, typeFactory ->
+        typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100).build(),
+        "values (" + CalciteSqlDialect.DEFAULT.quoteStringLiteral(s) + ")",
+        ImmutableList.of(), Arrays.asList("view"));
   }
 
   public static TranslatableTable str(Object o, Object p) {
     assertThat(RexLiteral.validConstant(o, Litmus.THROW), is(true));
     assertThat(RexLiteral.validConstant(p, Litmus.THROW), is(true));
-    return new ViewTable(Object.class,
-        new RelProtoDataType() {
-          public RelDataType apply(RelDataTypeFactory typeFactory) {
-            return typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100)
-                .build();
-          }
-        },
+    return new ViewTable(Object.class, typeFactory ->
+        typeFactory.builder().add("c", SqlTypeName.VARCHAR, 100).build(),
         "values " + CalciteSqlDialect.DEFAULT.quoteStringLiteral(o.toString())
             + ", " + CalciteSqlDialect.DEFAULT.quoteStringLiteral(p.toString()),
-        ImmutableList.<String>of(), Arrays.asList("view"));
+        ImmutableList.of(), Arrays.asList("view"));
   }
 
   /** Class with int and String fields. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/UtilTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/UtilTest.java b/core/src/test/java/org/apache/calcite/util/UtilTest.java
index 4560fd5..e9159a9 100644
--- a/core/src/test/java/org/apache/calcite/util/UtilTest.java
+++ b/core/src/test/java/org/apache/calcite/util/UtilTest.java
@@ -23,7 +23,6 @@ import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Enumerator;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.Ord;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.linq4j.function.Parameter;
 import org.apache.calcite.runtime.ConsList;
 import org.apache.calcite.runtime.FlatLists;
@@ -37,7 +36,6 @@ import org.apache.calcite.sql.util.SqlString;
 import org.apache.calcite.test.DiffTestCase;
 import org.apache.calcite.test.Matchers;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMultiset;
 import com.google.common.collect.ImmutableSortedSet;
@@ -70,17 +68,19 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.NavigableSet;
 import java.util.Properties;
 import java.util.Random;
+import java.util.RandomAccess;
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.TimeZone;
 import java.util.TreeSet;
-import javax.annotation.Nullable;
+import java.util.function.Function;
 
 import static org.apache.calcite.test.Matchers.isLinux;
 
@@ -455,7 +455,7 @@ public class UtilTest {
       // ok
     }
 
-    final List<String> a = ConsList.of("a", ImmutableList.<String>of());
+    final List<String> a = ConsList.of("a", ImmutableList.of());
     assertThat(a.size(), is(1));
     assertThat(a, is(Collections.singletonList("a")));
   }
@@ -1419,11 +1419,11 @@ public class UtilTest {
     checkCompositeMap(beatles, map);
 
     map = CompositeMap.of(
-        beatleMap, Collections.<String, Integer>emptyMap());
+        beatleMap, Collections.emptyMap());
     checkCompositeMap(beatles, map);
 
     map = CompositeMap.of(
-        Collections.<String, Integer>emptyMap(), beatleMap);
+        Collections.emptyMap(), beatleMap);
     checkCompositeMap(beatles, map);
 
     map = CompositeMap.of(beatleMap, beatleMap);
@@ -1471,7 +1471,7 @@ public class UtilTest {
     } catch (NullPointerException e) {
       // ok
     }
-    assertThat(Util.commaList(ImmutableList.<Object>of()), equalTo(""));
+    assertThat(Util.commaList(ImmutableList.of()), equalTo(""));
     assertThat(Util.commaList(ImmutableList.of(1)), equalTo("1"));
     assertThat(Util.commaList(ImmutableList.of(2, 3)), equalTo("2, 3"));
     assertThat(Util.commaList(Arrays.asList(2, null, 3)),
@@ -1503,28 +1503,25 @@ public class UtilTest {
     final int zMax = 100;
     for (int i = 0; i < 30; i++) {
       final int size = i;
-      new Benchmark("isDistinct " + i + " (set)",
-          new Function1<Benchmark.Statistician, Void>() {
-            public Void apply(Benchmark.Statistician statistician) {
-              final Random random = new Random(0);
-              final List<List<Integer>> lists = new ArrayList<List<Integer>>();
-              for (int z = 0; z < zMax; z++) {
-                final List<Integer> list = new ArrayList<Integer>();
-                for (int k = 0; k < size; k++) {
-                  list.add(random.nextInt(size * size));
-                }
-                lists.add(list);
-              }
-              long nanos = System.nanoTime();
-              int n = 0;
-              for (int j = 0; j < limit; j++) {
-                n += Util.firstDuplicate(lists.get(j % zMax));
-              }
-              statistician.record(nanos);
-              Util.discard(n);
-              return null;
-            }
-          },
+      new Benchmark("isDistinct " + i + " (set)", statistician -> {
+        final Random random = new Random(0);
+        final List<List<Integer>> lists = new ArrayList<List<Integer>>();
+        for (int z = 0; z < zMax; z++) {
+          final List<Integer> list = new ArrayList<Integer>();
+          for (int k = 0; k < size; k++) {
+            list.add(random.nextInt(size * size));
+          }
+          lists.add(list);
+        }
+        long nanos = System.nanoTime();
+        int n = 0;
+        for (int j = 0; j < limit; j++) {
+          n += Util.firstDuplicate(lists.get(j % zMax));
+        }
+        statistician.record(nanos);
+        Util.discard(n);
+        return null;
+      },
           5).run();
     }
   }
@@ -1622,16 +1619,14 @@ public class UtilTest {
     treeSet2.addAll(treeSet);
     assertThat(treeSet2.size(), equalTo(3));
 
-    final Comparator<String> comparator = new Comparator<String>() {
-      public int compare(String o1, String o2) {
-        String u1 = o1.toUpperCase(Locale.ROOT);
-        String u2 = o2.toUpperCase(Locale.ROOT);
-        int c = u1.compareTo(u2);
-        if (c == 0) {
-          c = o1.compareTo(o2);
-        }
-        return c;
+    final Comparator<String> comparator = (o1, o2) -> {
+      String u1 = o1.toUpperCase(Locale.ROOT);
+      String u2 = o2.toUpperCase(Locale.ROOT);
+      int c = u1.compareTo(u2);
+      if (c == 0) {
+        c = o1.compareTo(o2);
       }
+      return c;
     };
     final TreeSet<String> treeSet3 = new TreeSet<String>(comparator);
     treeSet3.addAll(treeSet);
@@ -1702,24 +1697,14 @@ public class UtilTest {
         isA((Class) ImmutableList.class));
 
     // list with no nulls uses ImmutableList
-    final Iterable<String> abc =
-        new Iterable<String>() {
-          public Iterator<String> iterator() {
-            return abcList.iterator();
-          }
-        };
+    final Iterable<String> abc = abcList::iterator;
     assertThat(ImmutableNullableList.copyOf(abc),
         isA((Class) ImmutableList.class));
     assertThat(ImmutableNullableList.copyOf(abc), equalTo(abcList));
 
     // list with no nulls uses ImmutableList
     final List<String> ab0cList = Arrays.asList("a", "b", null, "c");
-    final Iterable<String> ab0c =
-        new Iterable<String>() {
-          public Iterator<String> iterator() {
-            return ab0cList.iterator();
-          }
-        };
+    final Iterable<String> ab0c = ab0cList::iterator;
     assertThat(ImmutableNullableList.copyOf(ab0c),
         not(isA((Class) ImmutableList.class)));
     assertThat(ImmutableNullableList.copyOf(ab0c), equalTo(ab0cList));
@@ -1850,12 +1835,8 @@ public class UtilTest {
 
   @Test public void testAsIndexView() {
     final List<String> values  = Lists.newArrayList("abCde", "X", "y");
-    final Map<String, String> map = Util.asIndexMap(values,
-        new Function<String, String>() {
-          public String apply(@Nullable String input) {
-            return input.toUpperCase(Locale.ROOT);
-          }
-        });
+    final Map<String, String> map =
+        Util.asIndexMapJ(values, input -> input.toUpperCase(Locale.ROOT));
     assertThat(map.size(), equalTo(values.size()));
     assertThat(map.get("X"), equalTo("X"));
     assertThat(map.get("Y"), equalTo("y"));
@@ -2149,12 +2130,7 @@ public class UtilTest {
     assertThat("x", is("x"));
     assertThat(is("x").matches("x"), is(true));
     assertThat(is("X").matches("x"), is(false));
-    final Function<String, String> toUpper =
-        new Function<String, String>() {
-          public String apply(String input) {
-            return input.toUpperCase(Locale.ROOT);
-          }
-        };
+    final Function<String, String> toUpper = s -> s.toUpperCase(Locale.ROOT);
     assertThat(Matchers.compose(is("A"), toUpper).matches("a"), is(true));
     assertThat(Matchers.compose(is("A"), toUpper).matches("A"), is(true));
     assertThat(Matchers.compose(is("a"), toUpper).matches("A"), is(false));
@@ -2182,6 +2158,23 @@ public class UtilTest {
     assertThat(isLinux("x\r\ny").matches("x\ny"), is(false));
   }
 
+  /** Tests {@link Util#transform(List, java.util.function.Function)}. */
+  @Test public void testTransform() {
+    final List<String> beatles =
+        Arrays.asList("John", "Paul", "George", "Ringo");
+    final List<String> empty = Collections.emptyList();
+    assertThat(Util.transform(beatles, s -> s.toUpperCase(Locale.ROOT)),
+        is(Arrays.asList("JOHN", "PAUL", "GEORGE", "RINGO")));
+    assertThat(Util.transform(empty, s -> s.toUpperCase(Locale.ROOT)), is(empty));
+    assertThat(Util.transform(beatles, String::length),
+        is(Arrays.asList(4, 4, 6, 5)));
+    assertThat(Util.transform(beatles, String::length),
+        instanceOf(RandomAccess.class));
+    final List<String> beatles2 = new LinkedList<>(beatles);
+    assertThat(Util.transform(beatles2, String::length),
+        not(instanceOf(RandomAccess.class)));
+  }
+
   static String mismatchDescription(Matcher m, Object item) {
     final StringDescription d = new StringDescription();
     m.describeMismatch(item, d);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/graph/DirectedGraphTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/graph/DirectedGraphTest.java b/core/src/test/java/org/apache/calcite/util/graph/DirectedGraphTest.java
index 6724ffc..483a704 100644
--- a/core/src/test/java/org/apache/calcite/util/graph/DirectedGraphTest.java
+++ b/core/src/test/java/org/apache/calcite/util/graph/DirectedGraphTest.java
@@ -221,7 +221,7 @@ public class DirectedGraphTest {
     //   +- E - F
     DefaultDirectedGraph<String, DefaultEdge> graph = createDag();
     assertThat(new CycleDetector<String, DefaultEdge>(graph).findCycles(),
-        CoreMatchers.<Set<String>>equalTo(ImmutableSet.<String>of()));
+        CoreMatchers.equalTo(ImmutableSet.of()));
 
     // Add cycle C-D-E-C
     //
@@ -232,8 +232,8 @@ public class DirectedGraphTest {
     //      \_____/
     graph.addEdge("D", "E");
     assertThat(new CycleDetector<String, DefaultEdge>(graph).findCycles(),
-        CoreMatchers.<Set<String>>equalTo(
-            ImmutableSet.<String>of("C", "D", "E", "F")));
+        CoreMatchers.equalTo(
+            ImmutableSet.of("C", "D", "E", "F")));
 
     // Add another cycle, D-C-D in addition to C-D-E-C.
     //           __
@@ -245,8 +245,8 @@ public class DirectedGraphTest {
     //      \_____/
     graph.addEdge("D", "C");
     assertThat(new CycleDetector<String, DefaultEdge>(graph).findCycles(),
-        CoreMatchers.<Set<String>>equalTo(
-            ImmutableSet.<String>of("C", "D", "E", "F")));
+        CoreMatchers.equalTo(
+            ImmutableSet.of("C", "D", "E", "F")));
 
     graph.removeEdge("D", "E");
     graph.removeEdge("D", "C");
@@ -262,8 +262,8 @@ public class DirectedGraphTest {
     // Detected cycle contains "D", which is downstream from the cycle but not
     // in the cycle. Not sure whether that is correct.
     assertThat(new CycleDetector<String, DefaultEdge>(graph).findCycles(),
-        CoreMatchers.<Set<String>>equalTo(
-            ImmutableSet.<String>of("B", "C", "D")));
+        CoreMatchers.equalTo(
+            ImmutableSet.of("B", "C", "D")));
 
     // Add single-node cycle, C-C
     //
@@ -275,13 +275,13 @@ public class DirectedGraphTest {
     graph.removeEdge("C", "B");
     graph.addEdge("C", "C");
     assertThat(new CycleDetector<String, DefaultEdge>(graph).findCycles(),
-        CoreMatchers.<Set<String>>equalTo(
-            ImmutableSet.<String>of("C", "D")));
+        CoreMatchers.equalTo(
+            ImmutableSet.of("C", "D")));
 
     // Empty graph is not cyclic.
     graph.removeAllVertices(graph.vertexSet());
     assertThat(new CycleDetector<String, DefaultEdge>(graph).findCycles(),
-        CoreMatchers.<Set<String>>equalTo(ImmutableSet.<String>of()));
+        CoreMatchers.equalTo(ImmutableSet.of()));
   }
 
   /** Unit test for

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/util/mapping/MappingTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/util/mapping/MappingTest.java b/core/src/test/java/org/apache/calcite/util/mapping/MappingTest.java
index 2155294..e9817fb 100644
--- a/core/src/test/java/org/apache/calcite/util/mapping/MappingTest.java
+++ b/core/src/test/java/org/apache/calcite/util/mapping/MappingTest.java
@@ -204,7 +204,7 @@ public class MappingTest {
     assertThat(mapping.inverse().toString(), equalTo("[1, 2, 3, 0]"));
 
     // empty is OK
-    final Mapping empty = Mappings.bijection(Collections.<Integer>emptyList());
+    final Mapping empty = Mappings.bijection(Collections.emptyList());
     assertThat(empty.size(), equalTo(0));
     assertThat(empty.iterator().hasNext(), equalTo(false));
     assertThat(empty.toString(), equalTo("[]"));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DefaultDimensionSpec.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DefaultDimensionSpec.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DefaultDimensionSpec.java
index 28f99da..446b26b 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DefaultDimensionSpec.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DefaultDimensionSpec.java
@@ -17,9 +17,9 @@
 package org.apache.calcite.adapter.druid;
 
 import com.fasterxml.jackson.core.JsonGenerator;
-import com.google.common.base.Preconditions;
 
 import java.io.IOException;
+import java.util.Objects;
 
 /**
  * Default implementation of DimensionSpec.
@@ -34,8 +34,8 @@ public class DefaultDimensionSpec implements DimensionSpec {
   private final DruidType outputType;
 
   public DefaultDimensionSpec(String dimension, String outputName, DruidType outputType) {
-    this.dimension = Preconditions.checkNotNull(dimension);
-    this.outputName = Preconditions.checkNotNull(outputName);
+    this.dimension = Objects.requireNonNull(dimension);
+    this.outputName = Objects.requireNonNull(outputName);
     this.outputType = outputType == null ? DruidType.STRING : outputType;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidConnectionImpl.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidConnectionImpl.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidConnectionImpl.java
index 6d57438..175a16d 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidConnectionImpl.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidConnectionImpl.java
@@ -37,7 +37,6 @@ import com.fasterxml.jackson.core.JsonToken;
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.type.CollectionType;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 
@@ -56,6 +55,7 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.NoSuchElementException;
+import java.util.Objects;
 import java.util.Set;
 import java.util.TimeZone;
 import java.util.concurrent.ArrayBlockingQueue;
@@ -84,8 +84,8 @@ class DruidConnectionImpl implements DruidConnection {
   }
 
   DruidConnectionImpl(String url, String coordinatorUrl) {
-    this.url = Preconditions.checkNotNull(url);
-    this.coordinatorUrl = Preconditions.checkNotNull(coordinatorUrl);
+    this.url = Objects.requireNonNull(url);
+    this.coordinatorUrl = Objects.requireNonNull(coordinatorUrl);
   }
 
   /** Executes a query request.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidDateTimeUtils.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidDateTimeUtils.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidDateTimeUtils.java
index 20da334..efaab36 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidDateTimeUtils.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidDateTimeUtils.java
@@ -29,7 +29,6 @@ import org.apache.calcite.util.TimestampString;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
 
-import com.google.common.base.Function;
 import com.google.common.collect.BoundType;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
@@ -83,29 +82,26 @@ public class DruidDateTimeUtils {
 
   protected static List<Interval> toInterval(
       List<Range<Long>> ranges) {
-    List<Interval> intervals = Lists.transform(ranges,
-        new Function<Range<Long>, Interval>() {
-          public Interval apply(Range<Long> range) {
-            if (!range.hasLowerBound() && !range.hasUpperBound()) {
-              return DruidTable.DEFAULT_INTERVAL;
-            }
-            long start = range.hasLowerBound()
-                ? range.lowerEndpoint().longValue()
-                : DruidTable.DEFAULT_INTERVAL.getStartMillis();
-            long end = range.hasUpperBound()
-                ? range.upperEndpoint().longValue()
-                : DruidTable.DEFAULT_INTERVAL.getEndMillis();
-            if (range.hasLowerBound()
-                && range.lowerBoundType() == BoundType.OPEN) {
-              start++;
-            }
-            if (range.hasUpperBound()
-                && range.upperBoundType() == BoundType.CLOSED) {
-              end++;
-            }
-            return new Interval(start, end, ISOChronology.getInstanceUTC());
-          }
-        });
+    List<Interval> intervals = Lists.transform(ranges, range -> {
+      if (!range.hasLowerBound() && !range.hasUpperBound()) {
+        return DruidTable.DEFAULT_INTERVAL;
+      }
+      long start = range.hasLowerBound()
+          ? range.lowerEndpoint().longValue()
+          : DruidTable.DEFAULT_INTERVAL.getStartMillis();
+      long end = range.hasUpperBound()
+          ? range.upperEndpoint().longValue()
+          : DruidTable.DEFAULT_INTERVAL.getEndMillis();
+      if (range.hasLowerBound()
+          && range.lowerBoundType() == BoundType.OPEN) {
+        start++;
+      }
+      if (range.hasUpperBound()
+          && range.upperBoundType() == BoundType.CLOSED) {
+        end++;
+      }
+      return new Interval(start, end, ISOChronology.getInstanceUTC());
+    });
     if (LOGGER.isDebugEnabled()) {
       LOGGER.debug("Converted time ranges " + ranges + " to interval " + intervals);
     }
@@ -129,7 +125,7 @@ public class DruidDateTimeUtils {
 
     case OR: {
       RexCall call = (RexCall) node;
-      List<Range<Long>> intervals = Lists.newArrayList();
+      List<Range<Long>> intervals = new ArrayList<>();
       for (RexNode child : call.getOperands()) {
         List<Range<Long>> extracted =
             extractRanges(child, withNot);


[12/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
index e5fb2aa..491be00 100644
--- a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
+++ b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
@@ -31,12 +31,21 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.AggregateCall;
 import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.core.Intersect;
+import org.apache.calcite.rel.core.Join;
 import org.apache.calcite.rel.core.JoinRelType;
+import org.apache.calcite.rel.core.Match;
+import org.apache.calcite.rel.core.Minus;
 import org.apache.calcite.rel.core.Project;
 import org.apache.calcite.rel.core.RelFactories;
+import org.apache.calcite.rel.core.SemiJoin;
 import org.apache.calcite.rel.core.Sort;
 import org.apache.calcite.rel.core.TableScan;
+import org.apache.calcite.rel.core.Union;
 import org.apache.calcite.rel.core.Values;
+import org.apache.calcite.rel.logical.LogicalFilter;
+import org.apache.calcite.rel.logical.LogicalProject;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
@@ -73,8 +82,6 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -109,21 +116,14 @@ import static org.apache.calcite.util.Static.RESOURCE;
  *
  * <p>{@code RelBuilder} uses factories to create relational expressions.
  * By default, it uses the default factories, which create logical relational
- * expressions ({@link org.apache.calcite.rel.logical.LogicalFilter},
- * {@link org.apache.calcite.rel.logical.LogicalProject} and so forth).
+ * expressions ({@link LogicalFilter},
+ * {@link LogicalProject} and so forth).
  * But you could override those factories so that, say, {@code filter} creates
  * instead a {@code HiveFilter}.
  *
  * <p>It is not thread-safe.
  */
 public class RelBuilder {
-  private static final Function<RexNode, String> FN_TYPE =
-      new Function<RexNode, String>() {
-        public String apply(RexNode input) {
-          return input + ": " + input.getType();
-        }
-      };
-
   protected final RelOptCluster cluster;
   protected final RelOptSchema relOptSchema;
   private final RelFactories.FilterFactory filterFactory;
@@ -222,11 +222,7 @@ public class RelBuilder {
   /** Creates a {@link RelBuilderFactory}, a partially-created RelBuilder.
    * Just add a {@link RelOptCluster} and a {@link RelOptSchema} */
   public static RelBuilderFactory proto(final Context context) {
-    return new RelBuilderFactory() {
-      public RelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
-        return new RelBuilder(context, cluster, schema);
-      }
-    };
+    return (cluster, schema) -> new RelBuilder(context, cluster, schema);
   }
 
   /** Creates a {@link RelBuilderFactory} that uses a given set of factories. */
@@ -434,8 +430,8 @@ public class RelBuilder {
    * given alias. Searches for the relation starting at the top of the
    * stack. */
   public RexNode field(int inputCount, String alias, String fieldName) {
-    Preconditions.checkNotNull(alias);
-    Preconditions.checkNotNull(fieldName);
+    Objects.requireNonNull(alias);
+    Objects.requireNonNull(fieldName);
     final List<String> fields = new ArrayList<>();
     for (int inputOrdinal = 0; inputOrdinal < inputCount; ++inputOrdinal) {
       final Frame frame = peek_(inputOrdinal);
@@ -545,7 +541,8 @@ public class RelBuilder {
     final RelDataType type = builder.deriveReturnType(operator, operandList);
     if (type == null) {
       throw new IllegalArgumentException("cannot derive type: " + operator
-          + "; operands: " + Lists.transform(operandList, FN_TYPE));
+          + "; operands: "
+          + Lists.transform(operandList, e -> e + ": " + e.getType()));
     }
     return builder.makeCall(type, operator, operandList);
   }
@@ -656,7 +653,7 @@ public class RelBuilder {
 
   /** Creates an empty group key. */
   public GroupKey groupKey() {
-    return groupKey(ImmutableList.<RexNode>of());
+    return groupKey(ImmutableList.of());
   }
 
   /** Creates a group key. */
@@ -720,11 +717,7 @@ public class RelBuilder {
         fields(ImmutableIntList.of(groupSet.toArray()));
     final List<ImmutableList<RexNode>> nodeLists =
         Lists.transform(groupSets,
-            new Function<ImmutableBitSet, ImmutableList<RexNode>>() {
-              public ImmutableList<RexNode> apply(ImmutableBitSet input) {
-                return fields(ImmutableIntList.of(input.toArray()));
-              }
-            });
+            bitSet -> fields(ImmutableIntList.of(bitSet.toArray())));
     return groupKey(nodes, indicator, nodeLists);
   }
 
@@ -884,7 +877,7 @@ public class RelBuilder {
 
   // Methods that create relational expressions
 
-  /** Creates a {@link org.apache.calcite.rel.core.TableScan} of the table
+  /** Creates a {@link TableScan} of the table
    * with a given name.
    *
    * <p>Throws if the table does not exist.
@@ -897,14 +890,14 @@ public class RelBuilder {
     final List<String> names = ImmutableList.copyOf(tableNames);
     final RelOptTable relOptTable = relOptSchema.getTableForMember(names);
     if (relOptTable == null) {
-      throw RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex();
+      throw RESOURCE.tableNotFound(String.join(".", names)).ex();
     }
     final RelNode scan = scanFactory.createScan(cluster, relOptTable);
     push(scan);
     return this;
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.TableScan} of the table
+  /** Creates a {@link TableScan} of the table
    * with a given name.
    *
    * <p>Throws if the table does not exist.
@@ -917,7 +910,7 @@ public class RelBuilder {
     return scan(ImmutableList.copyOf(tableNames));
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Filter} of an array of
+  /** Creates a {@link Filter} of an array of
    * predicates.
    *
    * <p>The predicates are combined using AND,
@@ -927,7 +920,7 @@ public class RelBuilder {
     return filter(ImmutableList.copyOf(predicates));
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Filter} of a list of
+  /** Creates a {@link Filter} of a list of
    * predicates.
    *
    * <p>The predicates are combined using AND,
@@ -948,7 +941,7 @@ public class RelBuilder {
     return this;
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Project} of the given list
+  /** Creates a {@link Project} of the given list
    * of expressions.
    *
    * <p>Infers names as would {@link #project(Iterable, Iterable)} if all
@@ -957,10 +950,10 @@ public class RelBuilder {
    * @param nodes Expressions
    */
   public RelBuilder project(Iterable<? extends RexNode> nodes) {
-    return project(nodes, ImmutableList.<String>of());
+    return project(nodes, ImmutableList.of());
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Project} of the given list
+  /** Creates a {@link Project} of the given list
    * of expressions and field names.
    *
    * @param nodes Expressions
@@ -971,7 +964,7 @@ public class RelBuilder {
     return project(nodes, fieldNames, false);
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Project} of the given list
+  /** Creates a {@link Project} of the given list
    * of expressions, using the given names.
    *
    * <p>Names are deduced as follows:
@@ -983,7 +976,7 @@ public class RelBuilder {
    *     or is a cast an input field,
    *     uses the input field name; otherwise
    *   <li>If an expression is a call to
-   *     {@link org.apache.calcite.sql.fun.SqlStdOperatorTable#AS}
+   *     {@link SqlStdOperatorTable#AS}
    *     (see {@link #alias}), removes the call but uses the intended alias.
    * </ul>
    *
@@ -1039,7 +1032,7 @@ public class RelBuilder {
         field = new Field(frame.fields.get(index).left, fieldType);
         break;
       default:
-        field = new Field(ImmutableSet.<String>of(), fieldType);
+        field = new Field(ImmutableSet.of(), fieldType);
         break;
       }
       uniqueNameList.add(name);
@@ -1065,13 +1058,13 @@ public class RelBuilder {
     return this;
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Project} of the given
+  /** Creates a {@link Project} of the given
    * expressions. */
   public RelBuilder project(RexNode... nodes) {
     return project(ImmutableList.copyOf(nodes));
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Project} of the given
+  /** Creates a {@link Project} of the given
    * expressions and field names, and optionally optimizing.
    *
    * <p>If {@code fieldNames} is null, or if a particular entry in
@@ -1195,19 +1188,19 @@ public class RelBuilder {
     }
   }
 
-  /** Creates an {@link org.apache.calcite.rel.core.Aggregate} that makes the
+  /** Creates an {@link Aggregate} that makes the
    * relational expression distinct on all fields. */
   public RelBuilder distinct() {
     return aggregate(groupKey(fields()));
   }
 
-  /** Creates an {@link org.apache.calcite.rel.core.Aggregate} with an array of
+  /** Creates an {@link Aggregate} with an array of
    * calls. */
   public RelBuilder aggregate(GroupKey groupKey, AggCall... aggCalls) {
     return aggregate(groupKey, ImmutableList.copyOf(aggCalls));
   }
 
-  /** Creates an {@link org.apache.calcite.rel.core.Aggregate} with a list of
+  /** Creates an {@link Aggregate} with a list of
    * calls. */
   public RelBuilder aggregate(GroupKey groupKey, Iterable<AggCall> aggCalls) {
     final Registrar registrar = new Registrar();
@@ -1326,7 +1319,7 @@ public class RelBuilder {
         String name = aggregateFields.get(i).getName();
         RelDataTypeField fieldType =
             new RelDataTypeFieldImpl(name, i, node.getType());
-        fields.add(new Field(ImmutableSet.<String>of(), fieldType));
+        fields.add(new Field(ImmutableSet.of(), fieldType));
         break;
       }
       i++;
@@ -1337,7 +1330,7 @@ public class RelBuilder {
         final RelDataTypeField field = aggregateFields.get(i);
         final RelDataTypeField fieldType =
             new RelDataTypeFieldImpl(field.getName(), i, field.getType());
-        fields.add(new Field(ImmutableSet.<String>of(), fieldType));
+        fields.add(new Field(ImmutableSet.of(), fieldType));
         i++;
       }
     }
@@ -1347,7 +1340,7 @@ public class RelBuilder {
       final RelDataTypeField fieldType =
           new RelDataTypeFieldImpl(aggregateFields.get(i + j).getName(), i + j,
               call.getType());
-      fields.add(new Field(ImmutableSet.<String>of(), fieldType));
+      fields.add(new Field(ImmutableSet.of(), fieldType));
     }
     stack.push(new Frame(aggregate, fields.build()));
     return this;
@@ -1378,7 +1371,7 @@ public class RelBuilder {
     }
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Union} of the two most recent
+  /** Creates a {@link Union} of the two most recent
    * relational expressions on the stack.
    *
    * @param all Whether to create UNION ALL
@@ -1387,7 +1380,7 @@ public class RelBuilder {
     return union(all, 2);
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Union} of the {@code n}
+  /** Creates a {@link Union} of the {@code n}
    * most recent relational expressions on the stack.
    *
    * @param all Whether to create UNION ALL
@@ -1397,7 +1390,7 @@ public class RelBuilder {
     return setOp(all, SqlKind.UNION, n);
   }
 
-  /** Creates an {@link org.apache.calcite.rel.core.Intersect} of the two most
+  /** Creates an {@link Intersect} of the two most
    * recent relational expressions on the stack.
    *
    * @param all Whether to create INTERSECT ALL
@@ -1406,7 +1399,7 @@ public class RelBuilder {
     return intersect(all, 2);
   }
 
-  /** Creates an {@link org.apache.calcite.rel.core.Intersect} of the {@code n}
+  /** Creates an {@link Intersect} of the {@code n}
    * most recent relational expressions on the stack.
    *
    * @param all Whether to create INTERSECT ALL
@@ -1416,7 +1409,7 @@ public class RelBuilder {
     return setOp(all, SqlKind.INTERSECT, n);
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Minus} of the two most recent
+  /** Creates a {@link Minus} of the two most recent
    * relational expressions on the stack.
    *
    * @param all Whether to create EXCEPT ALL
@@ -1425,7 +1418,7 @@ public class RelBuilder {
     return minus(all, 2);
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Minus} of the {@code n}
+  /** Creates a {@link Minus} of the {@code n}
    * most recent relational expressions on the stack.
    *
    * @param all Whether to create EXCEPT ALL
@@ -1434,25 +1427,25 @@ public class RelBuilder {
     return setOp(all, SqlKind.EXCEPT, n);
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Join}. */
+  /** Creates a {@link Join}. */
   public RelBuilder join(JoinRelType joinType, RexNode condition0,
       RexNode... conditions) {
     return join(joinType, Lists.asList(condition0, conditions));
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Join} with multiple
+  /** Creates a {@link Join} with multiple
    * conditions. */
   public RelBuilder join(JoinRelType joinType,
       Iterable<? extends RexNode> conditions) {
     return join(joinType, and(conditions),
-        ImmutableSet.<CorrelationId>of());
+        ImmutableSet.of());
   }
 
   public RelBuilder join(JoinRelType joinType, RexNode condition) {
-    return join(joinType, condition, ImmutableSet.<CorrelationId>of());
+    return join(joinType, condition, ImmutableSet.of());
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Join} with correlating
+  /** Creates a {@link Join} with correlating
    * variables. */
   public RelBuilder join(JoinRelType joinType, RexNode condition,
       Set<CorrelationId> variablesSet) {
@@ -1495,7 +1488,7 @@ public class RelBuilder {
     return this;
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Join} using USING syntax.
+  /** Creates a {@link Join} using USING syntax.
    *
    * <p>For each of the field names, both left and right inputs must have a
    * field of that name. Constructs a join condition that the left and right
@@ -1515,7 +1508,7 @@ public class RelBuilder {
     return join(joinType, conditions);
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.SemiJoin}. */
+  /** Creates a {@link SemiJoin}. */
   public RelBuilder semiJoin(Iterable<? extends RexNode> conditions) {
     final Frame right = stack.pop();
     final RelNode semiJoin =
@@ -1524,7 +1517,7 @@ public class RelBuilder {
     return this;
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.SemiJoin}. */
+  /** Creates a {@link SemiJoin}. */
   public RelBuilder semiJoin(RexNode... conditions) {
     return semiJoin(ImmutableList.copyOf(conditions));
   }
@@ -1533,12 +1526,9 @@ public class RelBuilder {
   public RelBuilder as(final String alias) {
     final Frame pair = stack.pop();
     List<Field> newFields =
-        Lists.transform(pair.fields, new Function<Field, Field>() {
-          public Field apply(Field field) {
-            return new Field(ImmutableSet.<String>builder().addAll(field.left)
-                .add(alias).build(), field.right);
-          }
-        });
+        Lists.transform(pair.fields, field ->
+            new Field(ImmutableSet.<String>builder().addAll(field.left)
+                .add(alias).build(), field.right));
     stack.push(new Frame(pair.rel, ImmutableList.copyOf(newFields)));
     return this;
   }
@@ -1707,7 +1697,7 @@ public class RelBuilder {
 
   /** Creates a limit without a sort. */
   public RelBuilder limit(int offset, int fetch) {
-    return sortLimit(offset, fetch, ImmutableList.<RexNode>of());
+    return sortLimit(offset, fetch, ImmutableList.of());
   }
 
   /** Creates a {@link Sort} by field ordinals.
@@ -1859,7 +1849,7 @@ public class RelBuilder {
     if (mapping.isIdentity()) {
       return this;
     }
-    final List<RexNode> exprList = Lists.newArrayList();
+    final List<RexNode> exprList = new ArrayList<>();
     for (int i = 0; i < mapping.getTargetCount(); i++) {
       exprList.add(field(mapping.getSource(i)));
     }
@@ -1869,15 +1859,10 @@ public class RelBuilder {
   public RelBuilder aggregate(GroupKey groupKey,
       List<AggregateCall> aggregateCalls) {
     return aggregate(groupKey,
-        Lists.transform(
-            aggregateCalls, new Function<AggregateCall, AggCall>() {
-              public AggCall apply(AggregateCall input) {
-                return new AggCallImpl2(input);
-              }
-            }));
+        Lists.transform(aggregateCalls, AggCallImpl2::new));
   }
 
-  /** Creates a {@link org.apache.calcite.rel.core.Match}. */
+  /** Creates a {@link Match}. */
   public RelBuilder match(RexNode pattern, boolean strictStart,
       boolean strictEnd, Map<String, RexNode> patternDefinitions,
       Iterable<? extends RexNode> measureList, RexNode after,
@@ -1965,7 +1950,7 @@ public class RelBuilder {
     GroupKey alias(String alias);
   }
 
-  /** Implementation of {@link RelBuilder.GroupKey}. */
+  /** Implementation of {@link GroupKey}. */
   protected static class GroupKeyImpl implements GroupKey {
     final ImmutableList<RexNode> nodes;
     final boolean indicator;
@@ -1974,7 +1959,7 @@ public class RelBuilder {
 
     GroupKeyImpl(ImmutableList<RexNode> nodes, boolean indicator,
         ImmutableList<ImmutableList<RexNode>> nodeLists, String alias) {
-      this.nodes = Preconditions.checkNotNull(nodes);
+      this.nodes = Objects.requireNonNull(nodes);
       assert !indicator;
       this.indicator = indicator;
       this.nodeLists = nodeLists;
@@ -1992,7 +1977,7 @@ public class RelBuilder {
     }
   }
 
-  /** Implementation of {@link RelBuilder.AggCall}. */
+  /** Implementation of {@link AggCall}. */
   private static class AggCallImpl implements AggCall {
     private final SqlAggFunction aggFunction;
     private final boolean distinct;
@@ -2013,13 +1998,13 @@ public class RelBuilder {
     }
   }
 
-  /** Implementation of {@link RelBuilder.AggCall} that wraps an
+  /** Implementation of {@link AggCall} that wraps an
    * {@link AggregateCall}. */
   private static class AggCallImpl2 implements AggCall {
     private final AggregateCall aggregateCall;
 
     AggCallImpl2(AggregateCall aggregateCall) {
-      this.aggregateCall = Preconditions.checkNotNull(aggregateCall);
+      this.aggregateCall = Objects.requireNonNull(aggregateCall);
     }
   }
 
@@ -2075,7 +2060,7 @@ public class RelBuilder {
       String tableAlias = deriveAlias(rel);
       ImmutableList.Builder<Field> builder = ImmutableList.builder();
       ImmutableSet<String> aliases = tableAlias == null
-          ? ImmutableSet.<String>of()
+          ? ImmutableSet.of()
           : ImmutableSet.of(tableAlias);
       for (RelDataTypeField field : rel.getRowType().getFieldList()) {
         builder.add(new Field(aliases, field));
@@ -2109,7 +2094,7 @@ public class RelBuilder {
 
   /** Shuttle that shifts a predicate's inputs to the left, replacing early
    * ones with references to a
-   * {@link org.apache.calcite.rex.RexCorrelVariable}. */
+   * {@link RexCorrelVariable}. */
   private class Shifter extends RexShuttle {
     private final RelNode left;
     private final CorrelationId id;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/BitSets.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/BitSets.java b/core/src/main/java/org/apache/calcite/util/BitSets.java
index 492dcfb..50cd9c5 100644
--- a/core/src/main/java/org/apache/calcite/util/BitSets.java
+++ b/core/src/main/java/org/apache/calcite/util/BitSets.java
@@ -85,25 +85,21 @@ public final class BitSets {
    * @return Iterable
    */
   public static Iterable<Integer> toIter(final BitSet bitSet) {
-    return new Iterable<Integer>() {
-      public Iterator<Integer> iterator() {
-        return new Iterator<Integer>() {
-          int i = bitSet.nextSetBit(0);
+    return () -> new Iterator<Integer>() {
+      int i = bitSet.nextSetBit(0);
 
-          public boolean hasNext() {
-            return i >= 0;
-          }
+      public boolean hasNext() {
+        return i >= 0;
+      }
 
-          public Integer next() {
-            int prev = i;
-            i = bitSet.nextSetBit(i + 1);
-            return prev;
-          }
+      public Integer next() {
+        int prev = i;
+        i = bitSet.nextSetBit(i + 1);
+        return prev;
+      }
 
-          public void remove() {
-            throw new UnsupportedOperationException();
-          }
-        };
+      public void remove() {
+        throw new UnsupportedOperationException();
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/CancelFlag.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/CancelFlag.java b/core/src/main/java/org/apache/calcite/util/CancelFlag.java
index 61e678b..2a14dad 100644
--- a/core/src/main/java/org/apache/calcite/util/CancelFlag.java
+++ b/core/src/main/java/org/apache/calcite/util/CancelFlag.java
@@ -19,8 +19,7 @@ package org.apache.calcite.util;
 import org.apache.calcite.plan.Context;
 import org.apache.calcite.plan.RelOptPlanner;
 
-import com.google.common.base.Preconditions;
-
+import java.util.Objects;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
@@ -36,7 +35,7 @@ public class CancelFlag {
   public final AtomicBoolean atomicBoolean;
 
   public CancelFlag(AtomicBoolean atomicBoolean) {
-    this.atomicBoolean = Preconditions.checkNotNull(atomicBoolean);
+    this.atomicBoolean = Objects.requireNonNull(atomicBoolean);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/Compatible.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/Compatible.java b/core/src/main/java/org/apache/calcite/util/Compatible.java
index 761edb2..6146792 100644
--- a/core/src/main/java/org/apache/calcite/util/Compatible.java
+++ b/core/src/main/java/org/apache/calcite/util/Compatible.java
@@ -22,7 +22,6 @@ import com.google.common.collect.ImmutableSortedSet;
 import com.google.common.collect.Maps;
 
 import java.lang.reflect.Array;
-import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.sql.Connection;
@@ -74,59 +73,56 @@ public interface Compatible {
     Compatible create() {
       return (Compatible) Proxy.newProxyInstance(
           Compatible.class.getClassLoader(),
-          new Class<?>[] {Compatible.class},
-          new InvocationHandler() {
-            public Object invoke(Object proxy, Method method, Object[] args)
-                throws Throwable {
-              if (method.getName().equals("asMap")) {
-                // Use the Guava implementation Maps.asMap if it is available
-                try {
-                  //noinspection ConfusingArgumentToVarargsMethod
-                  final Method guavaMethod = Maps.class.getMethod(
-                      method.getName(), method.getParameterTypes());
-                  return guavaMethod.invoke(null, args);
-                } catch (NoSuchMethodException e) {
-                  Set set = (Set) args[0];
-                  Function function = (Function) args[1];
-                  return CompatibleGuava11.asMap(set, function);
-                }
+          new Class<?>[] {Compatible.class}, (proxy, method, args) -> {
+            if (method.getName().equals("asMap")) {
+              // Use the Guava implementation Maps.asMap if it is available
+              try {
+                //noinspection ConfusingArgumentToVarargsMethod
+                final Method guavaMethod = Maps.class.getMethod(
+                    method.getName(), method.getParameterTypes());
+                return guavaMethod.invoke(null, args);
+              } catch (NoSuchMethodException e) {
+                Set set = (Set) args[0];
+                Function function = (Function) args[1];
+                return CompatibleGuava11.asMap(set, function);
               }
-              if (method.getName().equals("navigableSet")) {
-                ImmutableSortedSet set = (ImmutableSortedSet) args[0];
-                return CompatibleGuava11.navigableSet(set);
-              }
-              if (method.getName().equals("navigableMap")) {
-                ImmutableSortedMap map = (ImmutableSortedMap) args[0];
-                return CompatibleGuava11.navigableMap(map);
-              }
-              if (method.getName().equals("immutableNavigableMap")) {
-                Map map = (Map) args[0];
-                ImmutableSortedMap sortedMap = ImmutableSortedMap.copyOf(map);
-                return CompatibleGuava11.navigableMap(sortedMap);
-              }
-              if (method.getName().equals("setSchema")) {
-                Connection connection = (Connection) args[0];
-                String schema = (String) args[1];
+            }
+            if (method.getName().equals("navigableSet")) {
+              ImmutableSortedSet set = (ImmutableSortedSet) args[0];
+              return CompatibleGuava11.navigableSet(set);
+            }
+            if (method.getName().equals("navigableMap")) {
+              ImmutableSortedMap map = (ImmutableSortedMap) args[0];
+              return CompatibleGuava11.navigableMap(map);
+            }
+            if (method.getName().equals("immutableNavigableMap")) {
+              Map map = (Map) args[0];
+              ImmutableSortedMap sortedMap = ImmutableSortedMap.copyOf(map);
+              return CompatibleGuava11.navigableMap(sortedMap);
+            }
+            if (method.getName().equals("setSchema")) {
+              Connection connection = (Connection) args[0];
+              String schema = (String) args[1];
+              final Method method1 =
+                  connection.getClass().getMethod("setSchema", String.class);
+              return method1.invoke(connection, schema);
+            }
+            if (method.getName().equals("getParameterName")) {
+              final Method m = (Method) args[0];
+              final int i = (Integer) args[1];
+              try {
                 final Method method1 =
-                    connection.getClass().getMethod("setSchema", String.class);
-                return method1.invoke(connection, schema);
-              }
-              if (method.getName().equals("getParameterName")) {
-                final Method m = (Method) args[0];
-                final int i = (Integer) args[1];
-                try {
-                  final Method method1 =
-                      m.getClass().getMethod("getParameters");
-                  Object parameters = method1.invoke(m);
-                  final Object parameter = Array.get(parameters, i);
-                  final Method method3 = parameter.getClass().getMethod("getName");
-                  return method3.invoke(parameter);
-                } catch (NoSuchMethodException e) {
-                  return "arg" + i;
-                }
+                    m.getClass().getMethod("getParameters");
+                Object parameters = method1.invoke(m);
+                final Object parameter = Array.get(parameters, i);
+                final Method method3 =
+                    parameter.getClass().getMethod("getName");
+                return method3.invoke(parameter);
+              } catch (NoSuchMethodException e) {
+                return "arg" + i;
               }
-              return null;
             }
+            return null;
           });
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/CompatibleGuava11.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/CompatibleGuava11.java b/core/src/main/java/org/apache/calcite/util/CompatibleGuava11.java
index 21b437a..6b9dc61 100644
--- a/core/src/main/java/org/apache/calcite/util/CompatibleGuava11.java
+++ b/core/src/main/java/org/apache/calcite/util/CompatibleGuava11.java
@@ -17,7 +17,6 @@
 package org.apache.calcite.util;
 
 import com.google.common.base.Function;
-import com.google.common.base.Objects;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.ForwardingSet;
 import com.google.common.collect.ImmutableSortedMap;
@@ -30,16 +29,16 @@ import java.util.AbstractCollection;
 import java.util.AbstractMap;
 import java.util.AbstractSet;
 import java.util.Collection;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.NavigableMap;
 import java.util.NavigableSet;
+import java.util.Objects;
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.TreeSet;
 
-import static com.google.common.base.Preconditions.checkNotNull;
-
 /** Helper methods to provide modern Guava functionality based on Guava 11.
  *
  * @see Compatible
@@ -64,7 +63,7 @@ class CompatibleGuava11 {
     }
 
     @Override public boolean retainAll(Collection<?> c) {
-      return super.retainAll(checkNotNull(c)); // GWT compatibility
+      return super.retainAll(Objects.requireNonNull(c)); // GWT compatibility
     }
   }
 
@@ -80,7 +79,7 @@ class CompatibleGuava11 {
   }
 
   static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
-    checkNotNull(collection); // for GWT
+    Objects.requireNonNull(collection); // for GWT
     if (collection instanceof Multiset) {
       collection = ((Multiset<?>) collection).elementSet();
     }
@@ -239,8 +238,8 @@ class CompatibleGuava11 {
     }
 
     AsMapView(Set<K> set, Function<? super K, V> function) {
-      this.set = checkNotNull(set);
-      this.function = checkNotNull(function);
+      this.set = Objects.requireNonNull(set);
+      this.function = Objects.requireNonNull(function);
     }
 
     @Override public Set<K> keySet() {
@@ -319,7 +318,7 @@ class CompatibleGuava11 {
         Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
         Object key = entry.getKey();
         V value = map().get(key);
-        return Objects.equal(value, entry.getValue())
+        return Objects.equals(value, entry.getValue())
             && (value != null || map().containsKey(key));
       }
       return false;
@@ -339,7 +338,7 @@ class CompatibleGuava11 {
 
     @Override public boolean removeAll(Collection<?> c) {
       try {
-        return super.removeAll(checkNotNull(c));
+        return super.removeAll(Objects.requireNonNull(c));
       } catch (UnsupportedOperationException e) {
         // if the iterators don't support remove
         boolean changed = true;
@@ -352,7 +351,7 @@ class CompatibleGuava11 {
 
     @Override public boolean retainAll(Collection<?> c) {
       try {
-        return super.retainAll(checkNotNull(c));
+        return super.retainAll(Objects.requireNonNull(c));
       } catch (UnsupportedOperationException e) {
         // if the iterators don't support remove
         Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size());
@@ -392,7 +391,7 @@ class CompatibleGuava11 {
         return super.remove(o);
       } catch (UnsupportedOperationException e) {
         for (Map.Entry<K, V> entry : map().entrySet()) {
-          if (com.google.common.base.Objects.equal(o, entry.getValue())) {
+          if (Objects.equals(o, entry.getValue())) {
             map().remove(entry.getKey());
             return true;
           }
@@ -403,9 +402,9 @@ class CompatibleGuava11 {
 
     @Override public boolean removeAll(Collection<?> c) {
       try {
-        return super.removeAll(checkNotNull(c));
+        return super.removeAll(Objects.requireNonNull(c));
       } catch (UnsupportedOperationException e) {
-        Set<K> toRemove = Sets.newHashSet();
+        Set<K> toRemove = new HashSet<>();
         for (Map.Entry<K, V> entry : map().entrySet()) {
           if (c.contains(entry.getValue())) {
             toRemove.add(entry.getKey());
@@ -417,9 +416,9 @@ class CompatibleGuava11 {
 
     @Override public boolean retainAll(Collection<?> c) {
       try {
-        return super.retainAll(checkNotNull(c));
+        return super.retainAll(Objects.requireNonNull(c));
       } catch (UnsupportedOperationException e) {
-        Set<K> toRetain = Sets.newHashSet();
+        Set<K> toRetain = new HashSet<>();
         for (Map.Entry<K, V> entry : map().entrySet()) {
           if (c.contains(entry.getValue())) {
             toRetain.add(entry.getKey());
@@ -454,7 +453,7 @@ class CompatibleGuava11 {
     final Iterator<? extends F> backingIterator;
 
     TransformedIterator(Iterator<? extends F> backingIterator) {
-      this.backingIterator = checkNotNull(backingIterator);
+      this.backingIterator = Objects.requireNonNull(backingIterator);
     }
 
     abstract T transform(F from);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java b/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java
index 4f514bb..ef49e80 100644
--- a/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java
+++ b/core/src/main/java/org/apache/calcite/util/ImmutableBitSet.java
@@ -19,12 +19,9 @@ package org.apache.calcite.util;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.runtime.Utilities;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSortedMap;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Ordering;
 
 import java.io.Serializable;
@@ -50,21 +47,18 @@ public class ImmutableBitSet
     implements Iterable<Integer>, Serializable, Comparable<ImmutableBitSet> {
   /** Compares bit sets topologically, so that enclosing bit sets come first,
    * using natural ordering to break ties. */
-  public static final Comparator<ImmutableBitSet> COMPARATOR =
-      new Comparator<ImmutableBitSet>() {
-        public int compare(ImmutableBitSet o1, ImmutableBitSet o2) {
-          if (o1.equals(o2)) {
-            return 0;
-          }
-          if (o1.contains(o2)) {
-            return -1;
-          }
-          if (o2.contains(o1)) {
-            return 1;
-          }
-          return o1.compareTo(o2);
-        }
-      };
+  public static final Comparator<ImmutableBitSet> COMPARATOR = (o1, o2) -> {
+    if (o1.equals(o2)) {
+      return 0;
+    }
+    if (o1.contains(o2)) {
+      return -1;
+    }
+    if (o2.contains(o1)) {
+      return 1;
+    }
+    return o1.compareTo(o2);
+  };
 
   public static final Ordering<ImmutableBitSet> ORDERING =
       Ordering.from(COMPARATOR);
@@ -83,12 +77,11 @@ public class ImmutableBitSet
   private static final ImmutableBitSet EMPTY =
       new ImmutableBitSet(EMPTY_LONGS);
 
-  public static final Function<? super BitSet, ImmutableBitSet> FROM_BIT_SET =
-      new Function<BitSet, ImmutableBitSet>() {
-        public ImmutableBitSet apply(BitSet input) {
-          return ImmutableBitSet.of(BitSets.toIter(input));
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final
+      com.google.common.base.Function<? super BitSet, ImmutableBitSet>
+      FROM_BIT_SET = ImmutableBitSet::fromBitSet;
 
   private final long[] words;
 
@@ -203,6 +196,14 @@ public class ImmutableBitSet
   }
 
   /**
+   * Returns a new immutable bit set containing all the bits in the given
+   * {@link BitSet}.
+   */
+  public static ImmutableBitSet fromBitSet(BitSet input) {
+    return ImmutableBitSet.of(BitSets.toIter(input));
+  }
+
+  /**
    * Creates an ImmutableBitSet with bits from {@code fromIndex} (inclusive) to
    * specified {@code toIndex} (exclusive) set to {@code true}.
    *
@@ -257,17 +258,13 @@ public class ImmutableBitSet
 
   /** Computes the power set (set of all sets) of this bit set. */
   public Iterable<ImmutableBitSet> powerSet() {
-    List<List<ImmutableBitSet>> singletons = Lists.newArrayList();
-    for (Integer bit : this) {
+    List<List<ImmutableBitSet>> singletons = new ArrayList<>();
+    for (int bit : this) {
       singletons.add(
           ImmutableList.of(ImmutableBitSet.of(), ImmutableBitSet.of(bit)));
     }
     return Iterables.transform(Linq4j.product(singletons),
-        new Function<List<ImmutableBitSet>, ImmutableBitSet>() {
-          public ImmutableBitSet apply(List<ImmutableBitSet> input) {
-            return ImmutableBitSet.union(input);
-          }
-        });
+        ImmutableBitSet::union);
   }
 
   /**
@@ -465,7 +462,7 @@ public class ImmutableBitSet
    * <p>Bit sets {@code (), (0), (0, 1), (0, 1, 3), (1), (2, 3)} are in sorted
    * order.</p>
    */
-  public int compareTo(ImmutableBitSet o) {
+  public int compareTo(@Nonnull ImmutableBitSet o) {
     int i = 0;
     for (;;) {
       int n0 = nextSetBit(i);
@@ -888,12 +885,7 @@ public class ImmutableBitSet
   public static Iterable<ImmutableBitSet> permute(
       Iterable<ImmutableBitSet> bitSets,
       final Map<Integer, Integer> map) {
-    return Iterables.transform(bitSets,
-        new Function<ImmutableBitSet, ImmutableBitSet>() {
-          public ImmutableBitSet apply(ImmutableBitSet bitSet) {
-            return bitSet.permute(map);
-          }
-        });
+    return Iterables.transform(bitSets, bitSet -> bitSet.permute(map));
   }
 
   /** Returns a bit set with every bit moved up {@code offset} positions.
@@ -921,7 +913,7 @@ public class ImmutableBitSet
   private static class Closure {
     private SortedMap<Integer, ImmutableBitSet> equivalence;
     private final SortedMap<Integer, ImmutableBitSet> closure =
-        Maps.newTreeMap();
+        new TreeMap<>();
 
     Closure(SortedMap<Integer, ImmutableBitSet> equivalence) {
       this.equivalence = equivalence;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/ImmutableNullableList.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/ImmutableNullableList.java b/core/src/main/java/org/apache/calcite/util/ImmutableNullableList.java
index 9345214..109153d 100644
--- a/core/src/main/java/org/apache/calcite/util/ImmutableNullableList.java
+++ b/core/src/main/java/org/apache/calcite/util/ImmutableNullableList.java
@@ -19,7 +19,6 @@ package org.apache.calcite.util;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Iterators;
-import com.google.common.collect.Lists;
 
 import java.util.AbstractList;
 import java.util.ArrayList;
@@ -60,6 +59,9 @@ public class ImmutableNullableList<E> extends AbstractList<E> {
       //noinspection unchecked
       return (List<E>) elements;
     }
+    if (elements == Collections.EMPTY_LIST) {
+      return ImmutableList.of();
+    }
     // If there are no nulls, ImmutableList is better.
     for (E object : elements) {
       if (object == null) {
@@ -204,7 +206,7 @@ public class ImmutableNullableList<E> extends AbstractList<E> {
    * @param <E> element type
    */
   public static final class Builder<E> {
-    private final List<E> contents = Lists.newArrayList();
+    private final List<E> contents = new ArrayList<>();
 
     /**
      * Creates a new builder. The returned builder is equivalent to the builder

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/IntegerIntervalSet.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/IntegerIntervalSet.java b/core/src/main/java/org/apache/calcite/util/IntegerIntervalSet.java
index 1105461..37ef25d 100644
--- a/core/src/main/java/org/apache/calcite/util/IntegerIntervalSet.java
+++ b/core/src/main/java/org/apache/calcite/util/IntegerIntervalSet.java
@@ -91,13 +91,10 @@ public class IntegerIntervalSet extends AbstractSet<Integer> {
   private Enumerator<Integer> enumerator() {
     final int[] bounds = {Integer.MAX_VALUE, Integer.MIN_VALUE};
     visit(
-        s,
-        new Handler() {
-          public void range(int start, int end, boolean exclude) {
-            if (!exclude) {
-              bounds[0] = Math.min(bounds[0], start);
-              bounds[1] = Math.max(bounds[1], end);
-            }
+        s, (start, end, exclude) -> {
+          if (!exclude) {
+            bounds[0] = Math.min(bounds[0], start);
+            bounds[1] = Math.max(bounds[1], end);
           }
         });
     return new Enumerator<Integer>() {
@@ -136,12 +133,9 @@ public class IntegerIntervalSet extends AbstractSet<Integer> {
   public boolean contains(final int n) {
     final boolean[] bs = {false};
     visit(
-        s,
-        new Handler() {
-          public void range(int start, int end, boolean exclude) {
-            if (start <= n && n <= end) {
-              bs[0] = !exclude;
-            }
+        s, (start, end, exclude) -> {
+          if (start <= n && n <= end) {
+            bs[0] = !exclude;
           }
         });
     return bs[0];

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/NameSet.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/NameSet.java b/core/src/main/java/org/apache/calcite/util/NameSet.java
index a51f949..22b7da0 100644
--- a/core/src/main/java/org/apache/calcite/util/NameSet.java
+++ b/core/src/main/java/org/apache/calcite/util/NameSet.java
@@ -34,16 +34,13 @@ public class NameSet {
    * collection sorted on this comparator, we can find case-insensitive matches
    * for a given string using a range scan between the upper-case string and
    * the lower-case string. */
-  public static final Comparator<String> COMPARATOR =
-      new Comparator<String>() {
-        public int compare(String o1, String o2) {
-          int c = o1.compareToIgnoreCase(o2);
-          if (c == 0) {
-            c = o1.compareTo(o2);
-          }
-          return c;
-        }
-      };
+  public static final Comparator<String> COMPARATOR = (o1, o2) -> {
+    int c = o1.compareToIgnoreCase(o2);
+    if (c == 0) {
+      c = o1.compareTo(o2);
+    }
+    return c;
+  };
 
   private final NavigableSet<String> names;
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/Pair.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/Pair.java b/core/src/main/java/org/apache/calcite/util/Pair.java
index bb2521e..fedaa2d 100644
--- a/core/src/main/java/org/apache/calcite/util/Pair.java
+++ b/core/src/main/java/org/apache/calcite/util/Pair.java
@@ -229,27 +229,11 @@ public class Pair<T1, T2>
   public static <K, V> Iterable<Pair<K, V>> zip(
       final Iterable<? extends K> ks,
       final Iterable<? extends V> vs) {
-    return new Iterable<Pair<K, V>>() {
-      public Iterator<Pair<K, V>> iterator() {
-        final Iterator<? extends K> kIterator = ks.iterator();
-        final Iterator<? extends V> vIterator = vs.iterator();
-
-        return new Iterator<Pair<K, V>>() {
-          public boolean hasNext() {
-            return kIterator.hasNext() && vIterator.hasNext();
-          }
-
-          @SuppressWarnings("unchecked")
-          public Pair<K, V> next() {
-            return (Pair<K, V>) Pair.of(kIterator.next(), vIterator.next());
-          }
-
-          public void remove() {
-            kIterator.remove();
-            vIterator.remove();
-          }
-        };
-      }
+    return () -> {
+      final Iterator<? extends K> kIterator = ks.iterator();
+      final Iterator<? extends V> vIterator = vs.iterator();
+
+      return new ZipIterator<>(kIterator, vIterator);
     };
   }
 
@@ -288,25 +272,7 @@ public class Pair<T1, T2>
    */
   public static <L, R> Iterable<L> left(
       final Iterable<? extends Map.Entry<L, R>> iterable) {
-    return new Iterable<L>() {
-      public Iterator<L> iterator() {
-        final Iterator<? extends Map.Entry<L, R>> iterator =
-            iterable.iterator();
-        return new Iterator<L>() {
-          public boolean hasNext() {
-            return iterator.hasNext();
-          }
-
-          public L next() {
-            return iterator.next().getKey();
-          }
-
-          public void remove() {
-            iterator.remove();
-          }
-        };
-      }
-    };
+    return () -> new LeftIterator<>(iterable.iterator());
   }
 
   /**
@@ -319,25 +285,7 @@ public class Pair<T1, T2>
    */
   public static <L, R> Iterable<R> right(
       final Iterable<? extends Map.Entry<L, R>> iterable) {
-    return new Iterable<R>() {
-      public Iterator<R> iterator() {
-        final Iterator<? extends Map.Entry<L, R>> iterator =
-            iterable.iterator();
-        return new Iterator<R>() {
-          public boolean hasNext() {
-            return iterator.hasNext();
-          }
-
-          public R next() {
-            return iterator.next().getValue();
-          }
-
-          public void remove() {
-            iterator.remove();
-          }
-        };
-      }
-    };
+    return () -> new RightIterator<>(iterable.iterator());
   }
 
   public static <K, V> List<K> left(
@@ -376,32 +324,12 @@ public class Pair<T1, T2>
    * @return Iterable over adjacent element pairs
    */
   public static <T> Iterable<Pair<T, T>> adjacents(final Iterable<T> iterable) {
-    return new Iterable<Pair<T, T>>() {
-      public Iterator<Pair<T, T>> iterator() {
-        final Iterator<T> iterator = iterable.iterator();
-        if (!iterator.hasNext()) {
-          return Collections.emptyIterator();
-        }
-        final T first = iterator.next();
-        return new Iterator<Pair<T, T>>() {
-          T previous = first;
-
-          public boolean hasNext() {
-            return iterator.hasNext();
-          }
-
-          public Pair<T, T> next() {
-            final T current = iterator.next();
-            final Pair<T, T> pair = of(previous, current);
-            previous = current;
-            return pair;
-          }
-
-          public void remove() {
-            throw new UnsupportedOperationException("remove");
-          }
-        };
+    return () -> {
+      final Iterator<T> iterator = iterable.iterator();
+      if (!iterator.hasNext()) {
+        return Collections.emptyIterator();
       }
+      return new AdjacentIterator<>(iterator);
     };
   }
 
@@ -416,29 +344,148 @@ public class Pair<T1, T2>
    * @return Iterable over pairs of the first element and all other elements
    */
   public static <T> Iterable<Pair<T, T>> firstAnd(final Iterable<T> iterable) {
-    return new Iterable<Pair<T, T>>() {
-      public Iterator<Pair<T, T>> iterator() {
-        final Iterator<T> iterator = iterable.iterator();
-        if (!iterator.hasNext()) {
-          return Collections.emptyIterator();
-        }
-        final T first = iterator.next();
-        return new Iterator<Pair<T, T>>() {
-          public boolean hasNext() {
-            return iterator.hasNext();
-          }
-
-          public Pair<T, T> next() {
-            return of(first, iterator.next());
-          }
-
-          public void remove() {
-            throw new UnsupportedOperationException("remove");
-          }
-        };
+    return () -> {
+      final Iterator<T> iterator = iterable.iterator();
+      if (!iterator.hasNext()) {
+        return Collections.emptyIterator();
       }
+      final T first = iterator.next();
+      return new FirstAndIterator<>(iterator, first);
     };
   }
+
+  /** Iterator that returns the left field of each pair.
+   *
+   * @param <L> Left-hand type
+   * @param <R> Right-hand type */
+  private static class LeftIterator<L, R> implements Iterator<L> {
+    private final Iterator<? extends Map.Entry<L, R>> iterator;
+
+    LeftIterator(Iterator<? extends Map.Entry<L, R>> iterator) {
+      this.iterator = Objects.requireNonNull(iterator);
+    }
+
+    public boolean hasNext() {
+      return iterator.hasNext();
+    }
+
+    public L next() {
+      return iterator.next().getKey();
+    }
+
+    public void remove() {
+      iterator.remove();
+    }
+  }
+
+  /** Iterator that returns the right field of each pair.
+   *
+   * @param <L> Left-hand type
+   * @param <R> Right-hand type */
+  private static class RightIterator<L, R> implements Iterator<R> {
+    private final Iterator<? extends Map.Entry<L, R>> iterator;
+
+    RightIterator(Iterator<? extends Map.Entry<L, R>> iterator) {
+      this.iterator = Objects.requireNonNull(iterator);
+    }
+
+    public boolean hasNext() {
+      return iterator.hasNext();
+    }
+
+    public R next() {
+      return iterator.next().getValue();
+    }
+
+    public void remove() {
+      iterator.remove();
+    }
+  }
+
+  /** Iterator that returns the first element of a collection paired with every
+   * other element.
+   *
+   * @param <E> Element type */
+  private static class FirstAndIterator<E> implements Iterator<Pair<E, E>> {
+    private final Iterator<E> iterator;
+    private final E first;
+
+    FirstAndIterator(Iterator<E> iterator, E first) {
+      this.iterator = Objects.requireNonNull(iterator);
+      this.first = first;
+    }
+
+    public boolean hasNext() {
+      return iterator.hasNext();
+    }
+
+    public Pair<E, E> next() {
+      return of(first, iterator.next());
+    }
+
+    public void remove() {
+      throw new UnsupportedOperationException("remove");
+    }
+  }
+
+  /** Iterator that pairs elements from two iterators.
+   *
+   * @param <L> Left-hand type
+   * @param <R> Right-hand type */
+  private static class ZipIterator<L, R> implements Iterator<Pair<L, R>> {
+    private final Iterator<? extends L> leftIterator;
+    private final Iterator<? extends R> rightIterator;
+
+    ZipIterator(Iterator<? extends L> leftIterator,
+        Iterator<? extends R> rightIterator) {
+      this.leftIterator = Objects.requireNonNull(leftIterator);
+      this.rightIterator = Objects.requireNonNull(rightIterator);
+    }
+
+    public boolean hasNext() {
+      return leftIterator.hasNext() && rightIterator.hasNext();
+    }
+
+    public Pair<L, R> next() {
+      return Pair.of(leftIterator.next(), rightIterator.next());
+    }
+
+    public void remove() {
+      leftIterator.remove();
+      rightIterator.remove();
+    }
+  }
+
+  /** Iterator that returns consecutive pairs of elements from an underlying
+   * iterator.
+   *
+   * @param <E> Element type */
+  private static class AdjacentIterator<E> implements Iterator<Pair<E, E>> {
+    private final E first;
+    private final Iterator<E> iterator;
+    E previous;
+
+    AdjacentIterator(Iterator<E> iterator) {
+      this.iterator = Objects.requireNonNull(iterator);
+      this.first = iterator.next();
+      previous = first;
+    }
+
+    public boolean hasNext() {
+      return iterator.hasNext();
+    }
+
+    public Pair<E, E> next() {
+      final E current = iterator.next();
+      final Pair<E, E> pair = of(previous, current);
+      previous = current;
+      return pair;
+    }
+
+    public void remove() {
+      throw new UnsupportedOperationException("remove");
+    }
+  }
 }
 
 // End Pair.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/PartiallyOrderedSet.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/PartiallyOrderedSet.java b/core/src/main/java/org/apache/calcite/util/PartiallyOrderedSet.java
index a3db6db..313b033 100644
--- a/core/src/main/java/org/apache/calcite/util/PartiallyOrderedSet.java
+++ b/core/src/main/java/org/apache/calcite/util/PartiallyOrderedSet.java
@@ -16,10 +16,7 @@
  */
 package org.apache.calcite.util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.util.AbstractSet;
 import java.util.ArrayDeque;
@@ -32,7 +29,9 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
+import java.util.function.Function;
 
 /**
  * Partially-ordered set.
@@ -71,11 +70,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
    * 6 (0110).
    */
   public static final Ordering<ImmutableBitSet> BIT_SET_INCLUSION_ORDERING =
-      new Ordering<ImmutableBitSet>() {
-        public boolean lessThan(ImmutableBitSet e1, ImmutableBitSet e2) {
-          return e1.contains(e2);
-        }
-      };
+      ImmutableBitSet::contains;
 
   private final Map<E, Node<E>> map;
   private final Function<E, Iterable<E>> parentFunction;
@@ -99,7 +94,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
    * @param ordering Ordering relation
    */
   public PartiallyOrderedSet(Ordering<E> ordering) {
-    this(ordering, new HashMap<E, Node<E>>(), null, null);
+    this(ordering, new HashMap<>(), null, null);
   }
 
   /**
@@ -111,7 +106,16 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
   public PartiallyOrderedSet(Ordering<E> ordering,
       Function<E, Iterable<E>> childFunction,
       Function<E, Iterable<E>> parentFunction) {
-    this(ordering, new HashMap<E, Node<E>>(), childFunction, parentFunction);
+    this(ordering, new HashMap<>(), childFunction, parentFunction);
+  }
+
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public PartiallyOrderedSet(Ordering<E> ordering,
+      com.google.common.base.Function<E, Iterable<E>> childFunction,
+      com.google.common.base.Function<E, Iterable<E>> parentFunction) {
+    this(ordering, (Function<E, Iterable<E>>) childFunction::apply,
+        parentFunction::apply);
   }
 
   /**
@@ -122,8 +126,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
    * @param collection Initial contents of partially-ordered set
    */
   public PartiallyOrderedSet(Ordering<E> ordering, Collection<E> collection) {
-    this(ordering, new HashMap<E, Node<E>>(collection.size() * 3 / 2), null,
-        null);
+    this(ordering, new HashMap<>(collection.size() * 3 / 2), null, null);
     addAll(collection);
   }
 
@@ -539,8 +542,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
     // breadth-first search, to iterate over every element once, printing
     // those nearest the top element first
     final Set<E> seen = new HashSet<>();
-    final Deque<E> unseen = new ArrayDeque<>();
-    unseen.addAll(getNonChildren());
+    final Deque<E> unseen = new ArrayDeque<>(getNonChildren());
     while (!unseen.isEmpty()) {
       E e = unseen.pop();
       buf.append("  ");
@@ -641,7 +643,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
       if (hypothetical) {
         if (parentFunction != null) {
           final List<E> list = new ArrayList<>();
-          closure(parentFunction, e, list, new HashSet<E>());
+          closure(parentFunction, e, list, new HashSet<>());
           return list;
         } else {
           return ImmutableList.copyOf(strip(findParents(e)));
@@ -656,7 +658,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
 
   private void closure(Function<E, Iterable<E>> generator, E e, List<E> list,
       Set<E> set) {
-    for (E p : Preconditions.checkNotNull(generator.apply(e))) {
+    for (E p : Objects.requireNonNull(generator.apply(e))) {
       if (set.add(e)) {
         if (map.containsKey(p)) {
           list.add(p);
@@ -711,12 +713,7 @@ public class PartiallyOrderedSet<E> extends AbstractSet<E> {
       // Similarly child list and bottom element.
       return ImmutableList.of();
     }
-    return Lists.transform(list,
-      new Function<Node<E>, E>() {
-        public E apply(Node<E> node) {
-          return node.e;
-        }
-      });
+    return Util.transform(list, node -> node.e);
   }
 
   /** Converts an iterable of nodes into the list of the elements inside.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/PrecedenceClimbingParser.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/PrecedenceClimbingParser.java b/core/src/main/java/org/apache/calcite/util/PrecedenceClimbingParser.java
index 68b8be5..e25e459 100644
--- a/core/src/main/java/org/apache/calcite/util/PrecedenceClimbingParser.java
+++ b/core/src/main/java/org/apache/calcite/util/PrecedenceClimbingParser.java
@@ -18,13 +18,13 @@ package org.apache.calcite.util;
 
 import org.apache.calcite.linq4j.Ord;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 
 import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
+import java.util.function.Predicate;
 
 /**
  * Parser that takes a collection of tokens (atoms and operators)
@@ -107,7 +107,7 @@ public class PrecedenceClimbingParser {
         break;
       case SPECIAL:
         Result r = ((SpecialOp) op).special.apply(this, (SpecialOp) op);
-        Preconditions.checkNotNull(r);
+        Objects.requireNonNull(r);
         replace(r.replacement, r.first.previous, r.last.next);
         break;
       default:
@@ -188,7 +188,7 @@ public class PrecedenceClimbingParser {
   public PrecedenceClimbingParser copy(int start, Predicate<Token> predicate) {
     final List<Token> tokens = new ArrayList<>();
     for (Token token : Util.skip(all(), start)) {
-      if (predicate.apply(token)) {
+      if (predicate.test(token)) {
         break;
       }
       tokens.add(token.copy());
@@ -352,7 +352,7 @@ public class PrecedenceClimbingParser {
   public static class Builder {
     final List<Token> tokens = new ArrayList<>();
     private final PrecedenceClimbingParser dummy =
-        new PrecedenceClimbingParser(ImmutableList.<Token>of());
+        new PrecedenceClimbingParser(ImmutableList.of());
 
     private Builder add(Token t) {
       tokens.add(t);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/ReflectUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/ReflectUtil.java b/core/src/main/java/org/apache/calcite/util/ReflectUtil.java
index 8dc2f2e..17f80d6 100644
--- a/core/src/main/java/org/apache/calcite/util/ReflectUtil.java
+++ b/core/src/main/java/org/apache/calcite/util/ReflectUtil.java
@@ -286,7 +286,7 @@ public abstract class ReflectUtil {
         visitorClass,
         visiteeClass,
         visitMethodName,
-        Collections.<Class>emptyList());
+        Collections.emptyList());
   }
 
   /**
@@ -426,7 +426,7 @@ public abstract class ReflectUtil {
             visitorClass,
             visiteeClass,
             visitMethodName,
-            Collections.<Class>emptyList());
+            Collections.emptyList());
       }
 
       public Method lookupVisitMethod(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/Sources.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/Sources.java b/core/src/main/java/org/apache/calcite/util/Sources.java
index 6f04b90..ae6e9da 100644
--- a/core/src/main/java/org/apache/calcite/util/Sources.java
+++ b/core/src/main/java/org/apache/calcite/util/Sources.java
@@ -16,8 +16,6 @@
  */
 package org.apache.calcite.util;
 
-import com.google.common.base.Preconditions;
-
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
@@ -27,6 +25,7 @@ import java.io.Reader;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
+import java.util.Objects;
 import java.util.zip.GZIPInputStream;
 
 /**
@@ -76,7 +75,7 @@ public abstract class Sources {
     private final URL url;
 
     private FileSource(URL url) {
-      this.url = Preconditions.checkNotNull(url);
+      this.url = Objects.requireNonNull(url);
       if (url.getProtocol().equals("file")) {
         this.file = new File(url.getFile());
       } else {
@@ -85,7 +84,7 @@ public abstract class Sources {
     }
 
     private FileSource(File file) {
-      this.file = Preconditions.checkNotNull(file);
+      this.file = Objects.requireNonNull(file);
       this.url = null;
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/TryThreadLocal.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/TryThreadLocal.java b/core/src/main/java/org/apache/calcite/util/TryThreadLocal.java
index b278174..2fd4f2a 100644
--- a/core/src/main/java/org/apache/calcite/util/TryThreadLocal.java
+++ b/core/src/main/java/org/apache/calcite/util/TryThreadLocal.java
@@ -50,13 +50,11 @@ public class TryThreadLocal<T> extends ThreadLocal<T> {
   public Memo push(T value) {
     final T previous = get();
     set(value);
-    return new Memo() {
-      public void close() {
-        if (previous == initialValue) {
-          remove();
-        } else {
-          set(previous);
-        }
+    return () -> {
+      if (previous == initialValue) {
+        remove();
+      } else {
+        set(previous);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/UnmodifiableArrayList.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/UnmodifiableArrayList.java b/core/src/main/java/org/apache/calcite/util/UnmodifiableArrayList.java
index 3a27b02..d7a58fd 100644
--- a/core/src/main/java/org/apache/calcite/util/UnmodifiableArrayList.java
+++ b/core/src/main/java/org/apache/calcite/util/UnmodifiableArrayList.java
@@ -16,9 +16,8 @@
  */
 package org.apache.calcite.util;
 
-import com.google.common.base.Preconditions;
-
 import java.util.AbstractList;
+import java.util.Objects;
 import java.util.RandomAccess;
 
 /**
@@ -40,7 +39,7 @@ public class UnmodifiableArrayList<E>
   private final E[] elements;
 
   private UnmodifiableArrayList(E[] elements) {
-    this.elements = Preconditions.checkNotNull(elements);
+    this.elements = Objects.requireNonNull(elements);
   }
 
   public static <E> UnmodifiableArrayList<E> of(E... elements) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/Util.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/Util.java b/core/src/main/java/org/apache/calcite/util/Util.java
index 307879c..b90bbbd 100644
--- a/core/src/main/java/org/apache/calcite/util/Util.java
+++ b/core/src/main/java/org/apache/calcite/util/Util.java
@@ -29,7 +29,6 @@ import org.apache.calcite.sql.SqlValuesOperator;
 import org.apache.calcite.sql.fun.SqlRowOperator;
 import org.apache.calcite.sql.util.SqlBasicVisitor;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Throwables;
 import com.google.common.cache.CacheBuilder;
@@ -91,16 +90,16 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
+import java.util.RandomAccess;
 import java.util.Set;
 import java.util.StringTokenizer;
 import java.util.TimeZone;
+import java.util.function.Function;
 import java.util.jar.JarFile;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.stream.Collector;
-import javax.annotation.Nullable;
-
-import static com.google.common.base.Preconditions.checkNotNull;
+import javax.annotation.Nonnull;
 
 /**
  * Miscellaneous utility functions.
@@ -147,16 +146,11 @@ public class Util {
    * Maps classes to the map of their enum values. Uses a weak map so that
    * classes are not prevented from being unloaded.
    */
+  @SuppressWarnings("unchecked")
   private static final LoadingCache<Class, Map<String, Enum>> ENUM_CONSTANTS =
       CacheBuilder.newBuilder()
           .weakKeys()
-          .build(
-              new CacheLoader<Class, Map<String, Enum>>() {
-                @Override public Map<String, Enum> load(Class clazz) {
-                  //noinspection unchecked
-                  return enumConstants(clazz);
-                }
-              });
+          .build(CacheLoader.from(Util::enumConstants));
 
   //~ Methods ----------------------------------------------------------------
   /**
@@ -819,7 +813,7 @@ public class Util {
    * but we don't require Guava version 20 yet. */
   public static void throwIfUnchecked(Throwable throwable) {
     Bug.upgrade("Remove when minimum Guava version is 20");
-    checkNotNull(throwable);
+    Objects.requireNonNull(throwable);
     if (throwable instanceof RuntimeException) {
       throw (RuntimeException) throwable;
     }
@@ -868,7 +862,7 @@ public class Util {
   }
 
   /** @deprecated Use {@link Preconditions#checkArgument}
-   * or {@link Preconditions#checkNotNull(Object)} */
+   * or {@link Objects#requireNonNull(Object)} */
   @Deprecated // to be removed before 2.0
   public static void pre(boolean b, String description) {
     if (!b) {
@@ -877,7 +871,7 @@ public class Util {
   }
 
   /** @deprecated Use {@link Preconditions#checkArgument}
-   * or {@link Preconditions#checkNotNull(Object)} */
+   * or {@link Objects#requireNonNull(Object)} */
   @Deprecated // to be removed before 2.0
   public static void post(boolean b, String description) {
     if (!b) {
@@ -1603,11 +1597,7 @@ public class Util {
   public static <E> Iterable<E> cast(
       final Iterable<? super E> iterable,
       final Class<E> clazz) {
-    return new Iterable<E>() {
-      public Iterator<E> iterator() {
-        return cast(iterable.iterator(), clazz);
-      }
-    };
+    return () -> cast(iterable.iterator(), clazz);
   }
 
   /**
@@ -1631,11 +1621,7 @@ public class Util {
   public static <E> Iterable<E> filter(
       final Iterable<?> iterable,
       final Class<E> includeFilter) {
-    return new Iterable<E>() {
-      public Iterator<E> iterator() {
-        return new Filterator<>(iterable.iterator(), includeFilter);
-      }
-    };
+    return () -> new Filterator<>(iterable.iterator(), includeFilter);
   }
 
   public static <E> Collection<E> filter(
@@ -1898,7 +1884,7 @@ public class Util {
   }
 
   public static <T> Iterable<T> orEmpty(Iterable<T> v0) {
-    return v0 != null ? v0 : ImmutableList.<T>of();
+    return v0 != null ? v0 : ImmutableList.of();
   }
 
   /** Returns the last element of a list.
@@ -2199,16 +2185,11 @@ public class Util {
    * @param <V> Value type
    * @return Map that is a view onto the values
    */
-  public static <K, V> Map<K, V> asIndexMap(
+  public static <K, V> Map<K, V> asIndexMapJ(
       final Collection<V> values,
       final Function<V, K> function) {
     final Collection<Map.Entry<K, V>> entries =
-        Collections2.transform(values,
-            new Function<V, Map.Entry<K, V>>() {
-              public Map.Entry<K, V> apply(@Nullable V input) {
-                return Pair.of(function.apply(input), input);
-              }
-            });
+        Collections2.transform(values, v -> Pair.of(function.apply(v), v));
     final Set<Map.Entry<K, V>> entrySet =
         new AbstractSet<Map.Entry<K, V>>() {
           public Iterator<Map.Entry<K, V>> iterator() {
@@ -2226,6 +2207,14 @@ public class Util {
     };
   }
 
+  @SuppressWarnings("Guava")
+  @Deprecated
+  public static <K, V> Map<K, V> asIndexMap(
+      final Collection<V> values,
+      final com.google.common.base.Function<V, K> function) {
+    return asIndexMapJ(values, function::apply);
+  }
+
   /**
    * Prints the given code with line numbering.
    */
@@ -2287,7 +2276,8 @@ public class Util {
     if (n == 0) {
       // Lists are already immutable. Furthermore, if the outer list is
       // immutable we will just return "lists" unchanged.
-      return ImmutableList.copyOf((Iterable) lists);
+      //noinspection unchecked
+      return ImmutableList.copyOf((Iterable<List<E>>) lists);
     }
     final ImmutableList.Builder<List<E>> builder =
         ImmutableList.builder();
@@ -2351,6 +2341,9 @@ public class Util {
    * Returns a {@code Collector} that accumulates the input elements into a
    * Guava {@link ImmutableList} via a {@link ImmutableList.Builder}.
    *
+   * <p>It will be obsolete when we move to {@link Bug#upgrade Guava 21.0},
+   * which has {@code ImmutableList.toImmutableList()}.
+   *
    * @param <T> Type of the input elements
    *
    * @return a {@code Collector} that collects all the input elements into an
@@ -2366,6 +2359,16 @@ public class Util {
         ImmutableList.Builder::build);
   }
 
+  /** Transforms a list, applying a function to each element. */
+  public static <F, T> List<T> transform(List<F> list,
+      java.util.function.Function<F, T> function) {
+    if (list instanceof RandomAccess) {
+      return new RandomAccessTransformingList<>(list, function);
+    } else {
+      return new TransformingList<>(list, function);
+    }
+  }
+
   //~ Inner Classes ----------------------------------------------------------
 
   /**
@@ -2401,6 +2404,49 @@ public class Util {
       return super.visit(call);
     }
   }
+
+  /** List that returns the same number of elements as a backing list,
+   * applying a transformation function to each one.
+   *
+   * @param <F> Element type of backing list
+   * @param <T> Element type of this list
+   */
+  private static class TransformingList<F, T> extends AbstractList<T> {
+    private final java.util.function.Function<F, T> function;
+    private final List<F> list;
+
+    TransformingList(List<F> list,
+        java.util.function.Function<F, T> function) {
+      this.function = function;
+      this.list = list;
+    }
+
+    public T get(int i) {
+      return function.apply(list.get(i));
+    }
+
+    public int size() {
+      return list.size();
+    }
+
+    @Override @Nonnull public Iterator<T> iterator() {
+      return listIterator();
+    }
+  }
+
+  /** Extension to {@link TransformingList} that implements
+   * {@link RandomAccess}.
+   *
+   * @param <F> Element type of backing list
+   * @param <T> Element type of this list
+   */
+  private static class RandomAccessTransformingList<F, T>
+      extends TransformingList<F, T> implements RandomAccess {
+    RandomAccessTransformingList(List<F> list,
+        java.util.function.Function<F, T> function) {
+      super(list, function);
+    }
+  }
 }
 
 // End Util.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/XmlOutput.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/XmlOutput.java b/core/src/main/java/org/apache/calcite/util/XmlOutput.java
index e58cae0..1a32205 100644
--- a/core/src/main/java/org/apache/calcite/util/XmlOutput.java
+++ b/core/src/main/java/org/apache/calcite/util/XmlOutput.java
@@ -558,7 +558,7 @@ public class XmlOutput {
       if (i >= translationVector.size()) {
         // Extend list by adding the requisite number of nulls.
         final int count = i + 1 - translationVector.size();
-        translationVector.addAll(Collections.<String>nCopies(count, null));
+        translationVector.addAll(Collections.nCopies(count, null));
       }
       translationVector.set(i, to);
     }
@@ -569,7 +569,7 @@ public class XmlOutput {
      */
     public void makeImmutable() {
       translationTable =
-          translationVector.toArray(new String[translationVector.size()]);
+          translationVector.toArray(new String[0]);
       translationVector = null;
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/graph/BreadthFirstIterator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/graph/BreadthFirstIterator.java b/core/src/main/java/org/apache/calcite/util/graph/BreadthFirstIterator.java
index 21aed24..3a7260f 100644
--- a/core/src/main/java/org/apache/calcite/util/graph/BreadthFirstIterator.java
+++ b/core/src/main/java/org/apache/calcite/util/graph/BreadthFirstIterator.java
@@ -41,11 +41,7 @@ public class BreadthFirstIterator<V, E extends DefaultEdge>
 
   public static <V, E extends DefaultEdge> Iterable<V> of(
       final DirectedGraph<V, E> graph, final V root) {
-    return new Iterable<V>() {
-      public Iterator<V> iterator() {
-        return new BreadthFirstIterator<V, E>(graph, root);
-      }
-    };
+    return () -> new BreadthFirstIterator<V, E>(graph, root);
   }
 
   /** Populates a set with the nodes reachable from a given node. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/graph/DefaultDirectedGraph.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/graph/DefaultDirectedGraph.java b/core/src/main/java/org/apache/calcite/util/graph/DefaultDirectedGraph.java
index f093393..77eef3e 100644
--- a/core/src/main/java/org/apache/calcite/util/graph/DefaultDirectedGraph.java
+++ b/core/src/main/java/org/apache/calcite/util/graph/DefaultDirectedGraph.java
@@ -45,7 +45,7 @@ public class DefaultDirectedGraph<V, E extends DefaultEdge>
   }
 
   public static <V> DefaultDirectedGraph<V, DefaultEdge> create() {
-    return create(DefaultEdge.<V>factory());
+    return create(DefaultEdge.factory());
   }
 
   public static <V, E extends DefaultEdge> DefaultDirectedGraph<V, E> create(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/graph/DefaultEdge.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/graph/DefaultEdge.java b/core/src/main/java/org/apache/calcite/util/graph/DefaultEdge.java
index 3f32bdf..d288d02 100644
--- a/core/src/main/java/org/apache/calcite/util/graph/DefaultEdge.java
+++ b/core/src/main/java/org/apache/calcite/util/graph/DefaultEdge.java
@@ -40,11 +40,7 @@ public class DefaultEdge {
   }
 
   public static <V> DirectedGraph.EdgeFactory<V, DefaultEdge> factory() {
-    return new DirectedGraph.EdgeFactory<V, DefaultEdge>() {
-      public DefaultEdge createEdge(V v0, V v1) {
-        return new DefaultEdge(v0, v1);
-      }
-    };
+    return DefaultEdge::new;
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/graph/DepthFirstIterator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/graph/DepthFirstIterator.java b/core/src/main/java/org/apache/calcite/util/graph/DepthFirstIterator.java
index 1631d38..50d6b95 100644
--- a/core/src/main/java/org/apache/calcite/util/graph/DepthFirstIterator.java
+++ b/core/src/main/java/org/apache/calcite/util/graph/DepthFirstIterator.java
@@ -16,9 +16,7 @@
  */
 package org.apache.calcite.util.graph;
 
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -42,8 +40,8 @@ public class DepthFirstIterator<V, E extends DefaultEdge>
 
   private static <V, E extends DefaultEdge> List<V> buildList(
       DirectedGraph<V, E> graph, V start) {
-    final List<V> list = Lists.newArrayList();
-    buildListRecurse(list, Sets.<V>newHashSet(), graph, start);
+    final List<V> list = new ArrayList<>();
+    buildListRecurse(list, new HashSet<>(), graph, start);
     return list;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/graph/TopologicalOrderIterator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/graph/TopologicalOrderIterator.java b/core/src/main/java/org/apache/calcite/util/graph/TopologicalOrderIterator.java
index db7154f..69a6fdf 100644
--- a/core/src/main/java/org/apache/calcite/util/graph/TopologicalOrderIterator.java
+++ b/core/src/main/java/org/apache/calcite/util/graph/TopologicalOrderIterator.java
@@ -42,11 +42,7 @@ public class TopologicalOrderIterator<V, E extends DefaultEdge>
 
   public static <V, E extends DefaultEdge> Iterable<V> of(
       final DirectedGraph<V, E> graph) {
-    return new Iterable<V>() {
-      public Iterator<V> iterator() {
-        return new TopologicalOrderIterator<V, E>(graph);
-      }
-    };
+    return () -> new TopologicalOrderIterator<V, E>(graph);
   }
 
   private void populate(Map<V, int[]> countMap, List<V> empties) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/javac/JavaCompilerArgs.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/javac/JavaCompilerArgs.java b/core/src/main/java/org/apache/calcite/util/javac/JavaCompilerArgs.java
index e687a25..e3b03d3 100644
--- a/core/src/main/java/org/apache/calcite/util/javac/JavaCompilerArgs.java
+++ b/core/src/main/java/org/apache/calcite/util/javac/JavaCompilerArgs.java
@@ -61,7 +61,7 @@ public class JavaCompilerArgs {
     while (tok.hasMoreTokens()) {
       list.add(tok.nextToken());
     }
-    setStringArray(list.toArray(new String[list.size()]));
+    setStringArray(list.toArray(new String[0]));
   }
 
   /**
@@ -90,7 +90,7 @@ public class JavaCompilerArgs {
 
   public String[] getStringArray() {
     argsList.addAll(fileNameList);
-    return argsList.toArray(new String[argsList.size()]);
+    return argsList.toArray(new String[0]);
   }
 
   public void addFile(String fileName) {
@@ -98,7 +98,7 @@ public class JavaCompilerArgs {
   }
 
   public String[] getFileNames() {
-    return fileNameList.toArray(new String[fileNameList.size()]);
+    return fileNameList.toArray(new String[0]);
   }
 
   public void setVerbose(boolean verbose) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/mapping/Mappings.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/mapping/Mappings.java b/core/src/main/java/org/apache/calcite/util/mapping/Mappings.java
index 79a7216..8381d1c 100644
--- a/core/src/main/java/org/apache/calcite/util/mapping/Mappings.java
+++ b/core/src/main/java/org/apache/calcite/util/mapping/Mappings.java
@@ -21,7 +21,6 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Permutation;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.primitives.Ints;
@@ -33,6 +32,7 @@ import java.util.BitSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.function.IntFunction;
 
 /**
  * Utility functions related to mappings.
@@ -219,12 +219,7 @@ public abstract class Mappings {
   public static ImmutableList<ImmutableBitSet> apply2(final Mapping mapping,
       Iterable<ImmutableBitSet> bitSets) {
     return ImmutableList.copyOf(
-        Iterables.transform(bitSets,
-            new Function<ImmutableBitSet, ImmutableBitSet>() {
-              public ImmutableBitSet apply(ImmutableBitSet input1) {
-                return Mappings.apply(mapping, input1);
-              }
-            }));
+        Iterables.transform(bitSets, input1 -> apply(mapping, input1)));
   }
 
   /**
@@ -346,7 +341,7 @@ public abstract class Mappings {
   }
 
   public static TargetMapping target(
-      Function<Integer, Integer> function,
+      IntFunction<Integer> function,
       int sourceCount,
       int targetCount) {
     final PartialFunctionImpl mapping =
@@ -606,13 +601,11 @@ public abstract class Mappings {
       throw new IllegalArgumentException("new source count too low");
     }
     return target(
-        new Function<Integer, Integer>() {
-          public Integer apply(Integer source) {
-            int source2 = source - offset;
-            return source2 < 0 || source2 >= mapping.getSourceCount()
-                ? null
-                : mapping.getTargetOpt(source2);
-          }
+        (IntFunction<Integer>) source -> {
+          int source2 = source - offset;
+          return source2 < 0 || source2 >= mapping.getSourceCount()
+              ? null
+              : mapping.getTargetOpt(source2);
         },
         sourceCount,
         mapping.getTargetCount());
@@ -652,12 +645,11 @@ public abstract class Mappings {
       throw new IllegalArgumentException("new target count too low");
     }
     return target(
-        new Function<Integer, Integer>() {
-          public Integer apply(Integer source) {
-            int target = mapping.getTargetOpt(source);
-            return target < 0 ? null : target + offset;
-          }
-        }, mapping.getSourceCount(), targetCount);
+        (IntFunction<Integer>) source -> {
+          int target = mapping.getTargetOpt(source);
+          return target < 0 ? null : target + offset;
+        },
+        mapping.getSourceCount(), targetCount);
   }
 
   /**
@@ -681,18 +673,16 @@ public abstract class Mappings {
       throw new IllegalArgumentException("new source count too low");
     }
     return target(
-        new Function<Integer, Integer>() {
-          public Integer apply(Integer source) {
-            final int source2 = source - offset;
-            if (source2 < 0 || source2 >= mapping.getSourceCount()) {
-              return null;
-            }
-            int target = mapping.getTargetOpt(source2);
-            if (target < 0) {
-              return null;
-            }
-            return target + offset;
+        (IntFunction<Integer>) source -> {
+          final int source2 = source - offset;
+          if (source2 < 0 || source2 >= mapping.getSourceCount()) {
+            return null;
+          }
+          int target = mapping.getTargetOpt(source2);
+          if (target < 0) {
+            return null;
           }
+          return target + offset;
         },
         sourceCount,
         mapping.getTargetCount() + offset);
@@ -716,11 +706,7 @@ public abstract class Mappings {
   /** Inverts an {@link java.lang.Iterable} over
    * {@link org.apache.calcite.util.mapping.IntPair}s. */
   public static Iterable<IntPair> invert(final Iterable<IntPair> pairs) {
-    return new Iterable<IntPair>() {
-      public Iterator<IntPair> iterator() {
-        return invert(pairs.iterator());
-      }
-    };
+    return () -> invert(pairs.iterator());
   }
 
   /** Inverts an {@link java.util.Iterator} over

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/util/trace/CalciteTrace.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/util/trace/CalciteTrace.java b/core/src/main/java/org/apache/calcite/util/trace/CalciteTrace.java
index 2e01742..70d77af 100644
--- a/core/src/main/java/org/apache/calcite/util/trace/CalciteTrace.java
+++ b/core/src/main/java/org/apache/calcite/util/trace/CalciteTrace.java
@@ -56,11 +56,7 @@ public abstract class CalciteTrace {
   public static final Logger PARSER_LOGGER = getParserTracer();
 
   private static final ThreadLocal<Function2<Void, File, String>> DYNAMIC_HANDLER =
-      new ThreadLocal<Function2<Void, File, String>>() {
-        @Override protected Function2<Void, File, String> initialValue() {
-          return Functions.ignore2();
-        }
-      };
+      ThreadLocal.withInitial(Functions::ignore2);
 
   //~ Methods ----------------------------------------------------------------
 


[21/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/Interpreter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/Interpreter.java b/core/src/main/java/org/apache/calcite/interpreter/Interpreter.java
index 6096630..2bff11c 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/Interpreter.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/Interpreter.java
@@ -46,7 +46,6 @@ import org.apache.calcite.util.ReflectiveVisitDispatcher;
 import org.apache.calcite.util.ReflectiveVisitor;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
@@ -65,6 +64,7 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.NoSuchElementException;
+import java.util.Objects;
 
 /**
  * Interpreter.
@@ -81,7 +81,7 @@ public class Interpreter extends AbstractEnumerable<Object[]>
 
   /** Creates an Interpreter. */
   public Interpreter(DataContext dataContext, RelNode rootRel) {
-    this.dataContext = Preconditions.checkNotNull(dataContext);
+    this.dataContext = Objects.requireNonNull(dataContext);
     final RelNode rel = optimize(rootRel);
     final CompilerImpl compiler =
         new Nodes.CoreCompiler(this, rootRel.getCluster());
@@ -266,7 +266,7 @@ public class Interpreter extends AbstractEnumerable<Object[]>
     private final Enumerator<Row> enumerator;
 
     EnumeratorSource(final Enumerator<Row> enumerator) {
-      this.enumerator = Preconditions.checkNotNull(enumerator);
+      this.enumerator = Objects.requireNonNull(enumerator);
     }
 
     @Override public Row receive() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/JaninoRexCompiler.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/JaninoRexCompiler.java b/core/src/main/java/org/apache/calcite/interpreter/JaninoRexCompiler.java
index e4cf9e6..7b2ddca 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/JaninoRexCompiler.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/JaninoRexCompiler.java
@@ -17,7 +17,6 @@
 package org.apache.calcite.interpreter;
 
 import org.apache.calcite.adapter.enumerable.JavaRowFormat;
-import org.apache.calcite.adapter.enumerable.PhysType;
 import org.apache.calcite.adapter.enumerable.PhysTypeImpl;
 import org.apache.calcite.adapter.enumerable.RexToLixTranslator;
 import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
@@ -40,7 +39,6 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import org.codehaus.commons.compiler.CompileException;
 import org.codehaus.commons.compiler.CompilerFactoryFactory;
@@ -50,7 +48,7 @@ import org.codehaus.commons.compiler.ICompilerFactory;
 import java.io.IOException;
 import java.io.StringReader;
 import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -85,17 +83,14 @@ public class JaninoRexCompiler implements Interpreter.ScalarCompiler {
     final RexToLixTranslator.InputGetter inputGetter =
         new RexToLixTranslator.InputGetterImpl(
             ImmutableList.of(
-                Pair.<Expression, PhysType>of(
+                Pair.of(
                     Expressions.field(context_,
                         BuiltInMethod.CONTEXT_VALUES.field),
                     PhysTypeImpl.of(javaTypeFactory, inputRowType,
                         JavaRowFormat.ARRAY, false))));
-    final Function1<String, RexToLixTranslator.InputGetter> correlates =
-        new Function1<String, RexToLixTranslator.InputGetter>() {
-          public RexToLixTranslator.InputGetter apply(String a0) {
-            throw new UnsupportedOperationException();
-          }
-        };
+    final Function1<String, RexToLixTranslator.InputGetter> correlates = a0 -> {
+      throw new UnsupportedOperationException();
+    };
     final Expression root =
         Expressions.field(context_, BuiltInMethod.CONTEXT_ROOT.field);
     final List<Expression> list =
@@ -117,7 +112,7 @@ public class JaninoRexCompiler implements Interpreter.ScalarCompiler {
    * compiles. */
   static Scalar baz(ParameterExpression context_,
       ParameterExpression outputValues_, BlockStatement block) {
-    final List<MemberDeclaration> declarations = Lists.newArrayList();
+    final List<MemberDeclaration> declarations = new ArrayList<>();
 
     // public void execute(Context, Object[] outputValues)
     declarations.add(
@@ -145,7 +140,7 @@ public class JaninoRexCompiler implements Interpreter.ScalarCompiler {
 
     final ClassDeclaration classDeclaration =
         Expressions.classDecl(Modifier.PUBLIC, "Buzz", null,
-            ImmutableList.<Type>of(Scalar.class), declarations);
+            ImmutableList.of(Scalar.class), declarations);
     String s = Expressions.toString(declarations, "\n", false);
     if (CalcitePrepareImpl.DEBUG) {
       Util.debugCode(System.out, s);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/JoinNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/JoinNode.java b/core/src/main/java/org/apache/calcite/interpreter/JoinNode.java
index 349e26f..a167254 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/JoinNode.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/JoinNode.java
@@ -19,8 +19,8 @@ package org.apache.calcite.interpreter;
 import org.apache.calcite.rel.core.Join;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -56,7 +56,7 @@ public class JoinNode implements Node {
     while ((left = leftSource.receive()) != null) {
       System.arraycopy(left.getValues(), 0, context.values, 0, leftCount);
       if (rightList == null) {
-        rightList = Lists.newArrayList();
+        rightList = new ArrayList<>();
         while ((right = rightSource.receive()) != null) {
           rightList.add(right);
         }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/NoneToBindableConverterRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/NoneToBindableConverterRule.java b/core/src/main/java/org/apache/calcite/interpreter/NoneToBindableConverterRule.java
index e352ca1..233b2ed 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/NoneToBindableConverterRule.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/NoneToBindableConverterRule.java
@@ -23,7 +23,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -40,7 +40,7 @@ public class NoneToBindableConverterRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public NoneToBindableConverterRule(RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+    super(RelNode.class, (Predicate<RelNode>) r -> true, Convention.NONE,
         BindableConvention.INSTANCE, relBuilderFactory,
         "NoneToBindableConverterRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/SortNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/SortNode.java b/core/src/main/java/org/apache/calcite/interpreter/SortNode.java
index 04c95bf..210a530 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/SortNode.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/SortNode.java
@@ -20,12 +20,10 @@ import org.apache.calcite.rel.RelFieldCollation;
 import org.apache.calcite.rel.core.Sort;
 import org.apache.calcite.rex.RexLiteral;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Ordering;
 
-import java.util.Collections;
+import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.List;
 
@@ -68,11 +66,11 @@ public class SortNode extends AbstractSingleNode<Sort> {
       }
     } else {
       // Build a sorted collection.
-      final List<Row> list = Lists.newArrayList();
+      final List<Row> list = new ArrayList<>();
       while ((row = source.receive()) != null) {
         list.add(row);
       }
-      Collections.sort(list, comparator());
+      list.sort(comparator());
       final int end = fetch < 0 || offset + fetch > list.size()
           ? list.size()
           : offset + fetch;
@@ -89,11 +87,7 @@ public class SortNode extends AbstractSingleNode<Sort> {
     }
     return Ordering.compound(
         Iterables.transform(rel.getCollation().getFieldCollations(),
-            new Function<RelFieldCollation, Comparator<Row>>() {
-              public Comparator<Row> apply(RelFieldCollation input) {
-                return comparator(input);
-              }
-            }));
+            this::comparator));
   }
 
   private Comparator<Row> comparator(RelFieldCollation fieldCollation) {
@@ -101,20 +95,16 @@ public class SortNode extends AbstractSingleNode<Sort> {
     final int x = fieldCollation.getFieldIndex();
     switch (fieldCollation.direction) {
     case ASCENDING:
-      return new Comparator<Row>() {
-        public int compare(Row o1, Row o2) {
-          final Comparable c1 = (Comparable) o1.getValues()[x];
-          final Comparable c2 = (Comparable) o2.getValues()[x];
-          return RelFieldCollation.compare(c1, c2, nullComparison);
-        }
+      return (o1, o2) -> {
+        final Comparable c1 = (Comparable) o1.getValues()[x];
+        final Comparable c2 = (Comparable) o2.getValues()[x];
+        return RelFieldCollation.compare(c1, c2, nullComparison);
       };
     default:
-      return new Comparator<Row>() {
-        public int compare(Row o1, Row o2) {
-          final Comparable c1 = (Comparable) o1.getValues()[x];
-          final Comparable c2 = (Comparable) o2.getValues()[x];
-          return RelFieldCollation.compare(c2, c1, -nullComparison);
-        }
+      return (o1, o2) -> {
+        final Comparable c1 = (Comparable) o1.getValues()[x];
+        final Comparable c2 = (Comparable) o2.getValues()[x];
+        return RelFieldCollation.compare(c2, c1, -nullComparison);
       };
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/TableScanNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/TableScanNode.java b/core/src/main/java/org/apache/calcite/interpreter/TableScanNode.java
index 9c8124e..54217c9 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/TableScanNode.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/TableScanNode.java
@@ -20,7 +20,6 @@ import org.apache.calcite.DataContext;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Queryable;
 import org.apache.calcite.linq4j.function.Function1;
-import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.core.TableScan;
@@ -144,21 +143,18 @@ public class TableScanNode implements Node {
         }
       }
       final List<Field> fields = fieldBuilder.build();
-      rowEnumerable = queryable.select(
-          new Function1<Object, Row>() {
-            public Row apply(Object o) {
-              final Object[] values = new Object[fields.size()];
-              for (int i = 0; i < fields.size(); i++) {
-                Field field = fields.get(i);
-                try {
-                  values[i] = field.get(o);
-                } catch (IllegalAccessException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-              return new Row(values);
-            }
-          });
+      rowEnumerable = queryable.select(o -> {
+        final Object[] values = new Object[fields.size()];
+        for (int i = 0; i < fields.size(); i++) {
+          Field field = fields.get(i);
+          try {
+            values[i] = field.get(o);
+          } catch (IllegalAccessException e) {
+            throw new RuntimeException(e);
+          }
+        }
+        return new Row(values);
+      });
     } else {
       rowEnumerable =
           Schemas.queryable(root, Row.class, relOptTable.getQualifiedName());
@@ -270,14 +266,11 @@ public class TableScanNode implements Node {
       final Scalar condition =
           compiler.compile(ImmutableList.of(filter2), inputRowType);
       final Context context = compiler.createContext();
-      enumerable = enumerable.where(
-          new Predicate1<Row>() {
-            @Override public boolean apply(Row row) {
-              context.values = row.getValues();
-              Boolean b = (Boolean) condition.execute(context);
-              return b != null && b;
-            }
-          });
+      enumerable = enumerable.where(row -> {
+        context.values = row.getValues();
+        Boolean b = (Boolean) condition.execute(context);
+        return b != null && b;
+      });
     }
     if (rejectedProjects != null) {
       enumerable = enumerable.select(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/UnionNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/UnionNode.java b/core/src/main/java/org/apache/calcite/interpreter/UnionNode.java
index 0f6fe4f..98d5c52 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/UnionNode.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/UnionNode.java
@@ -19,8 +19,8 @@ package org.apache.calcite.interpreter;
 import org.apache.calcite.rel.core.Union;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
 
+import java.util.HashSet;
 import java.util.Set;
 
 /**
@@ -43,7 +43,7 @@ public class UnionNode implements Node {
   }
 
   public void run() throws InterruptedException {
-    final Set<Row> rows = rel.all ? null : Sets.<Row>newHashSet();
+    final Set<Row> rows = rel.all ? null : new HashSet<>();
     for (Source source : sources) {
       Row row;
       while ((row = source.receive()) != null) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/ValuesNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/ValuesNode.java b/core/src/main/java/org/apache/calcite/interpreter/ValuesNode.java
index 1c6f255..83a510d 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/ValuesNode.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/ValuesNode.java
@@ -21,8 +21,8 @@ import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -42,7 +42,7 @@ public class ValuesNode implements Node {
 
   private ImmutableList<Row> createRows(Compiler compiler,
       ImmutableList<ImmutableList<RexLiteral>> tuples) {
-    final List<RexNode> nodes = Lists.newArrayList();
+    final List<RexNode> nodes = new ArrayList<>();
     for (ImmutableList<RexLiteral> tuple : tuples) {
       nodes.addAll(tuple);
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/CalciteConnectionImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/CalciteConnectionImpl.java b/core/src/main/java/org/apache/calcite/jdbc/CalciteConnectionImpl.java
index ec5d610..5db3421 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/CalciteConnectionImpl.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/CalciteConnectionImpl.java
@@ -44,7 +44,6 @@ import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.materialize.Lattice;
 import org.apache.calcite.materialize.MaterializationService;
 import org.apache.calcite.prepare.CalciteCatalogReader;
-import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.type.DelegatingTypeSystem;
 import org.apache.calcite.rel.type.RelDataTypeSystem;
 import org.apache.calcite.runtime.Hook;
@@ -67,16 +66,17 @@ import org.apache.calcite.util.Holder;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
 
 import java.io.Serializable;
 import java.lang.reflect.Type;
-import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.HashMap;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Properties;
 import java.util.TimeZone;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -135,7 +135,7 @@ abstract class CalciteConnectionImpl
       this.typeFactory = new JavaTypeFactoryImpl(typeSystem);
     }
     this.rootSchema =
-        Preconditions.checkNotNull(rootSchema != null
+        Objects.requireNonNull(rootSchema != null
             ? rootSchema
             : CalciteSchema.createRootSchema(true));
     Preconditions.checkArgument(this.rootSchema.isRoot(), "must be root schema");
@@ -172,18 +172,15 @@ abstract class CalciteConnectionImpl
 
   @Override public <T> T unwrap(Class<T> iface) throws SQLException {
     if (iface == RelRunner.class) {
-      return iface.cast(
-          new RelRunner() {
-            public PreparedStatement prepare(RelNode rel) {
-              try {
-                return prepareStatement_(CalcitePrepare.Query.of(rel),
-                    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
-                    getHoldability());
-              } catch (SQLException e) {
-                throw new RuntimeException(e);
-              }
-            }
-          });
+      return iface.cast((RelRunner) rel -> {
+        try {
+          return prepareStatement_(CalcitePrepare.Query.of(rel),
+              ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
+              getHoldability());
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
+        }
+      });
     }
     return super.unwrap(iface);
   }
@@ -288,7 +285,7 @@ abstract class CalciteConnectionImpl
 
   public <T> Enumerable<T> enumerable(Meta.StatementHandle handle,
       CalcitePrepare.CalciteSignature<T> signature) throws SQLException {
-    Map<String, Object> map = Maps.newLinkedHashMap();
+    Map<String, Object> map = new LinkedHashMap<>();
     AvaticaStatement statement = lookupStatement(handle);
     final List<TypedValue> parameterValues =
         TROJAN.getParameterValues(statement);
@@ -346,7 +343,7 @@ abstract class CalciteConnectionImpl
 
   /** Implementation of Server. */
   private static class CalciteServerImpl implements CalciteServer {
-    final Map<Integer, CalciteServerStatement> statementMap = Maps.newHashMap();
+    final Map<Integer, CalciteServerStatement> statementMap = new HashMap<>();
 
     public void removeStatement(Meta.StatementHandle h) {
       statementMap.remove(h.id);
@@ -455,7 +452,7 @@ abstract class CalciteConnectionImpl
       }
       final List<String> schemaPath =
           schemaName == null
-              ? ImmutableList.<String>of()
+              ? ImmutableList.of()
               : ImmutableList.of(schemaName);
       final SqlValidatorWithHints validator =
           new SqlAdvisorValidator(SqlStdOperatorTable.instance(),
@@ -485,7 +482,7 @@ abstract class CalciteConnectionImpl
     private final CalciteSchema rootSchema;
 
     ContextImpl(CalciteConnectionImpl connection) {
-      this.connection = Preconditions.checkNotNull(connection);
+      this.connection = Objects.requireNonNull(connection);
       long now = System.currentTimeMillis();
       SchemaVersion schemaVersion = new LongSchemaVersion(now);
       this.mutableRootSchema = connection.rootSchema;
@@ -512,7 +509,7 @@ abstract class CalciteConnectionImpl
         throw new RuntimeException(e);
       }
       return schemaName == null
-          ? ImmutableList.<String>of()
+          ? ImmutableList.of()
           : ImmutableList.of(schemaName);
     }
 
@@ -525,7 +522,7 @@ abstract class CalciteConnectionImpl
     }
 
     public DataContext getDataContext() {
-      return connection.createDataContext(ImmutableMap.<String, Object>of(),
+      return connection.createDataContext(ImmutableMap.of(),
           rootSchema);
     }
 
@@ -577,7 +574,7 @@ abstract class CalciteConnectionImpl
     private final AtomicBoolean cancelFlag = new AtomicBoolean();
 
     CalciteServerStatementImpl(CalciteConnectionImpl connection) {
-      this.connection = Preconditions.checkNotNull(connection);
+      this.connection = Objects.requireNonNull(connection);
     }
 
     public Context createPrepareContext() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/CalciteMetaImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/CalciteMetaImpl.java b/core/src/main/java/org/apache/calcite/jdbc/CalciteMetaImpl.java
index 837aece..0e9457b 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/CalciteMetaImpl.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/CalciteMetaImpl.java
@@ -19,7 +19,6 @@ package org.apache.calcite.jdbc;
 import org.apache.calcite.DataContext;
 import org.apache.calcite.adapter.java.AbstractQueryableTable;
 import org.apache.calcite.adapter.java.JavaTypeFactory;
-import org.apache.calcite.avatica.AvaticaParameter;
 import org.apache.calcite.avatica.AvaticaStatement;
 import org.apache.calcite.avatica.AvaticaUtils;
 import org.apache.calcite.avatica.ColumnMetaData;
@@ -37,11 +36,9 @@ import org.apache.calcite.linq4j.Queryable;
 import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.linq4j.function.Functions;
 import org.apache.calcite.linq4j.function.Predicate1;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeFactoryImpl;
-import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rel.type.RelDataTypeSystem;
 import org.apache.calcite.runtime.FlatLists;
 import org.apache.calcite.runtime.Hook;
@@ -60,7 +57,6 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.primitives.Ints;
@@ -75,6 +71,7 @@ import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.regex.Pattern;
 
 /**
@@ -98,11 +95,7 @@ public class CalciteMetaImpl extends MetaImpl {
       return Functions.truePredicate1();
     }
     final Pattern regex = likeToRegex(pattern);
-    return new Predicate1<T>() {
-      public boolean apply(T v1) {
-        return regex.matcher(v1.getName()).matches();
-      }
-    };
+    return v1 -> regex.matcher(v1.getName()).matches();
   }
 
   static Predicate1<String> matcher(final Pat pattern) {
@@ -110,11 +103,7 @@ public class CalciteMetaImpl extends MetaImpl {
       return Functions.truePredicate1();
     }
     final Pattern regex = likeToRegex(pattern);
-    return new Predicate1<String>() {
-      public boolean apply(String v1) {
-        return regex.matcher(v1).matches();
-      }
-    };
+    return v1 -> regex.matcher(v1).matches();
   }
 
   /** Converts a LIKE-style pattern (where '%' represents a wild-card, escaped
@@ -190,7 +179,7 @@ public class CalciteMetaImpl extends MetaImpl {
     }
     //noinspection unchecked
     final Iterable<Object> iterable = (Iterable<Object>) (Iterable) enumerable;
-    return createResultSet(Collections.<String, Object>emptyMap(),
+    return createResultSet(Collections.emptyMap(),
         columns, CursorFactory.record(clazz, fields, fieldNames),
         new Frame(0, true, iterable));
   }
@@ -199,7 +188,7 @@ public class CalciteMetaImpl extends MetaImpl {
   createEmptyResultSet(final Class<E> clazz) {
     final List<ColumnMetaData> columns = fieldMetaData(clazz).columns;
     final CursorFactory cursorFactory = CursorFactory.deduce(columns, clazz);
-    return createResultSet(Collections.<String, Object>emptyMap(), columns,
+    return createResultSet(Collections.emptyMap(), columns,
         cursorFactory, Frame.EMPTY);
   }
 
@@ -211,8 +200,8 @@ public class CalciteMetaImpl extends MetaImpl {
       final AvaticaStatement statement = connection.createStatement();
       final CalcitePrepare.CalciteSignature<Object> signature =
           new CalcitePrepare.CalciteSignature<Object>("",
-              ImmutableList.<AvaticaParameter>of(), internalParameters, null,
-              columns, cursorFactory, null, ImmutableList.<RelCollation>of(), -1,
+              ImmutableList.of(), internalParameters, null,
+              columns, cursorFactory, null, ImmutableList.of(), -1,
               null, Meta.StatementType.SELECT) {
             @Override public Enumerable<Object> enumerable(
                 DataContext dataContext) {
@@ -268,21 +257,12 @@ public class CalciteMetaImpl extends MetaImpl {
     if (typeList == null) {
       typeFilter = Functions.truePredicate1();
     } else {
-      typeFilter = new Predicate1<MetaTable>() {
-        public boolean apply(MetaTable v1) {
-          return typeList.contains(v1.tableType);
-        }
-      };
+      typeFilter = v1 -> typeList.contains(v1.tableType);
     }
     final Predicate1<MetaSchema> schemaMatcher = namedMatcher(schemaPattern);
     return createResultSet(schemas(catalog)
             .where(schemaMatcher)
-            .selectMany(
-                new Function1<MetaSchema, Enumerable<MetaTable>>() {
-                  public Enumerable<MetaTable> apply(MetaSchema schema) {
-                    return tables(schema, matcher(tableNamePattern));
-                  }
-                })
+            .selectMany(schema -> tables(schema, matcher(tableNamePattern)))
             .where(typeFilter),
         MetaTable.class,
         "TABLE_CAT",
@@ -331,18 +311,8 @@ public class CalciteMetaImpl extends MetaImpl {
         namedMatcher(columnNamePattern);
     return createResultSet(schemas(catalog)
             .where(schemaMatcher)
-            .selectMany(
-                new Function1<MetaSchema, Enumerable<MetaTable>>() {
-                  public Enumerable<MetaTable> apply(MetaSchema schema) {
-                    return tables(schema, tableNameMatcher);
-                  }
-                })
-            .selectMany(
-                new Function1<MetaTable, Enumerable<MetaColumn>>() {
-                  public Enumerable<MetaColumn> apply(MetaTable schema) {
-                    return columns(schema);
-                  }
-                })
+            .selectMany(schema -> tables(schema, tableNameMatcher))
+            .selectMany(this::columns)
             .where(columnMatcher),
         MetaColumn.class,
         "TABLE_CAT",
@@ -391,75 +361,49 @@ public class CalciteMetaImpl extends MetaImpl {
   Enumerable<MetaSchema> schemas(final String catalog) {
     return Linq4j.asEnumerable(
         getConnection().rootSchema.getSubSchemaMap().values())
-        .select(
-            new Function1<CalciteSchema, MetaSchema>() {
-              public MetaSchema apply(CalciteSchema calciteSchema) {
-                return new CalciteMetaSchema(
-                    calciteSchema,
-                    catalog,
-                    calciteSchema.getName());
-              }
-            })
-        .orderBy(
-            new Function1<MetaSchema, Comparable>() {
-              public Comparable apply(MetaSchema metaSchema) {
-                return (Comparable) FlatLists.of(
-                    Util.first(metaSchema.tableCatalog, ""),
-                    metaSchema.tableSchem);
-              }
-            });
+        .select((Function1<CalciteSchema, MetaSchema>) calciteSchema ->
+            new CalciteMetaSchema(calciteSchema, catalog,
+                calciteSchema.getName()))
+        .orderBy((Function1<MetaSchema, Comparable>) metaSchema ->
+            (Comparable) FlatLists.of(Util.first(metaSchema.tableCatalog, ""),
+                metaSchema.tableSchem));
   }
 
   Enumerable<MetaTable> tables(String catalog) {
     return schemas(catalog)
-        .selectMany(
-            new Function1<MetaSchema, Enumerable<MetaTable>>() {
-              public Enumerable<MetaTable> apply(MetaSchema schema) {
-                return tables(schema, Functions.<String>truePredicate1());
-              }
-            });
+        .selectMany(schema ->
+            tables(schema, Functions.<String>truePredicate1()));
   }
 
   Enumerable<MetaTable> tables(final MetaSchema schema_) {
     final CalciteMetaSchema schema = (CalciteMetaSchema) schema_;
     return Linq4j.asEnumerable(schema.calciteSchema.getTableNames())
-        .select(
-            new Function1<String, MetaTable>() {
-              public MetaTable apply(String name) {
-                final Table table =
-                    schema.calciteSchema.getTable(name, true).getTable();
-                return new CalciteMetaTable(table,
-                    schema.tableCatalog,
-                    schema.tableSchem,
-                    name);
-              }
-            })
+        .select((Function1<String, MetaTable>) name -> {
+          final Table table =
+              schema.calciteSchema.getTable(name, true).getTable();
+          return new CalciteMetaTable(table,
+              schema.tableCatalog,
+              schema.tableSchem,
+              name);
+        })
         .concat(
             Linq4j.asEnumerable(
                 schema.calciteSchema.getTablesBasedOnNullaryFunctions()
                     .entrySet())
-                .select(
-                    new Function1<Map.Entry<String, Table>, MetaTable>() {
-                      public MetaTable apply(Map.Entry<String, Table> pair) {
-                        final Table table = pair.getValue();
-                        return new CalciteMetaTable(table,
-                            schema.tableCatalog,
-                            schema.tableSchem,
-                            pair.getKey());
-                      }
-                    }));
+                .select(pair -> {
+                  final Table table = pair.getValue();
+                  return new CalciteMetaTable(table,
+                      schema.tableCatalog,
+                      schema.tableSchem,
+                      pair.getKey());
+                }));
   }
 
   Enumerable<MetaTable> tables(
       final MetaSchema schema,
       final Predicate1<String> matcher) {
     return tables(schema)
-        .where(
-            new Predicate1<MetaTable>() {
-              public boolean apply(MetaTable v1) {
-                return matcher.apply(v1.getName());
-              }
-            });
+        .where(v1 -> matcher.apply(v1.getName()));
   }
 
   private ImmutableList<MetaTypeInfo> getAllDefaultType() {
@@ -499,35 +443,32 @@ public class CalciteMetaImpl extends MetaImpl {
     final RelDataType rowType =
         table.calciteTable.getRowType(getConnection().typeFactory);
     return Linq4j.asEnumerable(rowType.getFieldList())
-        .select(
-            new Function1<RelDataTypeField, MetaColumn>() {
-              public MetaColumn apply(RelDataTypeField field) {
-                final int precision =
-                    field.getType().getSqlTypeName().allowsPrec()
-                        && !(field.getType()
-                        instanceof RelDataTypeFactoryImpl.JavaType)
-                        ? field.getType().getPrecision()
-                        : -1;
-                return new MetaColumn(
-                    table.tableCat,
-                    table.tableSchem,
-                    table.tableName,
-                    field.getName(),
-                    field.getType().getSqlTypeName().getJdbcOrdinal(),
-                    field.getType().getFullTypeString(),
-                    precision,
-                    field.getType().getSqlTypeName().allowsScale()
-                        ? field.getType().getScale()
-                        : null,
-                    10,
-                    field.getType().isNullable()
-                        ? DatabaseMetaData.columnNullable
-                        : DatabaseMetaData.columnNoNulls,
-                    precision,
-                    field.getIndex() + 1,
-                    field.getType().isNullable() ? "YES" : "NO");
-              }
-            });
+        .select(field -> {
+          final int precision =
+              field.getType().getSqlTypeName().allowsPrec()
+                  && !(field.getType()
+                  instanceof RelDataTypeFactoryImpl.JavaType)
+                  ? field.getType().getPrecision()
+                  : -1;
+          return new MetaColumn(
+              table.tableCat,
+              table.tableSchem,
+              table.tableName,
+              field.getName(),
+              field.getType().getSqlTypeName().getJdbcOrdinal(),
+              field.getType().getFullTypeString(),
+              precision,
+              field.getType().getSqlTypeName().allowsScale()
+                  ? field.getType().getScale()
+                  : null,
+              10,
+              field.getType().isNullable()
+                  ? DatabaseMetaData.columnNullable
+                  : DatabaseMetaData.columnNoNulls,
+              precision,
+              field.getIndex() + 1,
+              field.getType().isNullable() ? "YES" : "NO");
+        });
   }
 
   public MetaResultSet getSchemas(ConnectionHandle ch, String catalog, Pat schemaPattern) {
@@ -745,7 +686,7 @@ public class CalciteMetaImpl extends MetaImpl {
           public void execute() throws SQLException {
             if (signature.statementType.canUpdate()) {
               final Iterable<Object> iterable =
-                  _createIterable(h, signature, ImmutableList.<TypedValue>of(),
+                  _createIterable(h, signature, ImmutableList.of(),
                       null);
               final Iterator<Object> iterator = iterable.iterator();
               updateCount = ((Number) iterator.next()).longValue();
@@ -763,7 +704,7 @@ public class CalciteMetaImpl extends MetaImpl {
   @VisibleForTesting
   public static DataContext createDataContext(CalciteConnection connection) {
     return ((CalciteConnectionImpl) connection)
-        .createDataContext(ImmutableMap.<String, Object>of(),
+        .createDataContext(ImmutableMap.of(),
             CalciteSchema.from(connection.getRootSchema()));
   }
 
@@ -796,7 +737,7 @@ public class CalciteMetaImpl extends MetaImpl {
         String tableSchem, String tableName) {
       super(tableCat, tableSchem, tableName,
           calciteTable.getJdbcTableType().jdbcName);
-      this.calciteTable = Preconditions.checkNotNull(calciteTable);
+      this.calciteTable = Objects.requireNonNull(calciteTable);
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/CalcitePrepare.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/CalcitePrepare.java b/core/src/main/java/org/apache/calcite/jdbc/CalcitePrepare.java
index e0be075..f33d066 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/CalcitePrepare.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/CalcitePrepare.java
@@ -63,18 +63,9 @@ import java.util.Map;
  * API for a service that prepares statements for execution.
  */
 public interface CalcitePrepare {
-  Function0<CalcitePrepare> DEFAULT_FACTORY =
-      new Function0<CalcitePrepare>() {
-        public CalcitePrepare apply() {
-          return new CalcitePrepareImpl();
-        }
-      };
+  Function0<CalcitePrepare> DEFAULT_FACTORY = CalcitePrepareImpl::new;
   ThreadLocal<Deque<Context>> THREAD_CONTEXT_STACK =
-      new ThreadLocal<Deque<Context>>() {
-        @Override protected Deque<Context> initialValue() {
-          return new ArrayDeque<>();
-        }
-      };
+      ThreadLocal.withInitial(ArrayDeque::new);
 
   ParseResult parse(Context context, String sql);
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/CalciteResultSet.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/CalciteResultSet.java b/core/src/main/java/org/apache/calcite/jdbc/CalciteResultSet.java
index a8e2ecf..62e2249 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/CalciteResultSet.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/CalciteResultSet.java
@@ -25,7 +25,6 @@ import org.apache.calcite.avatica.Meta;
 import org.apache.calcite.avatica.util.Cursor;
 import org.apache.calcite.linq4j.Enumerator;
 import org.apache.calcite.linq4j.Linq4j;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.runtime.ArrayEnumeratorCursor;
 import org.apache.calcite.runtime.ObjectEnumeratorCursor;
 
@@ -57,9 +56,7 @@ public class CalciteResultSet extends AvaticaResultSet {
     final boolean autoTemp = connection.config().autoTemp();
     Handler.ResultSink resultSink = null;
     if (autoTemp) {
-      resultSink = new Handler.ResultSink() {
-        public void toBeCompleted() {
-        }
+      resultSink = () -> {
       };
     }
     connection.getDriver().handler.onStatementExecute(statement, resultSink);
@@ -83,7 +80,7 @@ public class CalciteResultSet extends AvaticaResultSet {
         new CalcitePrepare.CalciteSignature<>(signature.sql,
             signature.parameters, signature.internalParameters,
             signature.rowType, columnMetaDataList, Meta.CursorFactory.ARRAY,
-            signature.rootSchema, ImmutableList.<RelCollation>of(), -1, null,
+            signature.rootSchema, ImmutableList.of(), -1, null,
             statement.getStatementType());
     ResultSetMetaData subResultSetMetaData =
         new AvaticaResultSetMetaData(statement, null, newSignature);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/CalciteSchema.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/CalciteSchema.java b/core/src/main/java/org/apache/calcite/jdbc/CalciteSchema.java
index badf781..2cba4be 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/CalciteSchema.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/CalciteSchema.java
@@ -47,6 +47,7 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.NavigableMap;
 import java.util.NavigableSet;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -82,17 +83,17 @@ public abstract class CalciteSchema {
     if (tableMap == null) {
       this.tableMap = new NameMap<>();
     } else {
-      this.tableMap = Preconditions.checkNotNull(tableMap);
+      this.tableMap = Objects.requireNonNull(tableMap);
     }
     if (latticeMap == null) {
       this.latticeMap = new NameMap<>();
     } else {
-      this.latticeMap = Preconditions.checkNotNull(latticeMap);
+      this.latticeMap = Objects.requireNonNull(latticeMap);
     }
     if (subSchemaMap == null) {
       this.subSchemaMap = new NameMap<>();
     } else {
-      this.subSchemaMap = Preconditions.checkNotNull(subSchemaMap);
+      this.subSchemaMap = Objects.requireNonNull(subSchemaMap);
     }
     if (functionMap == null) {
       this.functionMap = new NameMultimap<>();
@@ -101,14 +102,14 @@ public abstract class CalciteSchema {
     } else {
       // If you specify functionMap, you must also specify functionNames and
       // nullaryFunctionMap.
-      this.functionMap = Preconditions.checkNotNull(functionMap);
-      this.functionNames = Preconditions.checkNotNull(functionNames);
-      this.nullaryFunctionMap = Preconditions.checkNotNull(nullaryFunctionMap);
+      this.functionMap = Objects.requireNonNull(functionMap);
+      this.functionNames = Objects.requireNonNull(functionNames);
+      this.nullaryFunctionMap = Objects.requireNonNull(nullaryFunctionMap);
     }
     if (typeMap == null) {
       this.typeMap = new NameMap<>();
     } else {
-      this.typeMap = Preconditions.checkNotNull(typeMap);
+      this.typeMap = Objects.requireNonNull(typeMap);
     }
     this.path = path;
   }
@@ -172,7 +173,7 @@ public abstract class CalciteSchema {
 
   /** Creates a TableEntryImpl with no SQLs. */
   protected TableEntryImpl tableEntry(String name, Table table) {
-    return new TableEntryImpl(this, name, table, ImmutableList.<String>of());
+    return new TableEntryImpl(this, name, table, ImmutableList.of());
   }
 
   /** Creates a TableEntryImpl with no SQLs. */
@@ -182,7 +183,7 @@ public abstract class CalciteSchema {
 
   /** Defines a table within this schema. */
   public TableEntry add(String tableName, Table table) {
-    return add(tableName, table, ImmutableList.<String>of());
+    return add(tableName, table, ImmutableList.of());
   }
 
   /** Defines a table within this schema. */
@@ -552,8 +553,8 @@ public abstract class CalciteSchema {
     public final String name;
 
     public Entry(CalciteSchema schema, String name) {
-      this.schema = Preconditions.checkNotNull(schema);
-      this.name = Preconditions.checkNotNull(name);
+      this.schema = Objects.requireNonNull(schema);
+      this.name = Objects.requireNonNull(name);
     }
 
     /** Returns this object's path. For example ["hr", "emps"]. */
@@ -569,7 +570,7 @@ public abstract class CalciteSchema {
     public TableEntry(CalciteSchema schema, String name,
         ImmutableList<String> sqls) {
       super(schema, name);
-      this.sqls = Preconditions.checkNotNull(sqls);
+      this.sqls = Objects.requireNonNull(sqls);
     }
 
     public abstract Table getTable();
@@ -730,7 +731,7 @@ public abstract class CalciteSchema {
         ImmutableList<String> sqls) {
       super(schema, name, sqls);
       assert table != null;
-      this.table = Preconditions.checkNotNull(table);
+      this.table = Objects.requireNonNull(table);
     }
 
     public Table getTable() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/JavaRecordType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/JavaRecordType.java b/core/src/main/java/org/apache/calcite/jdbc/JavaRecordType.java
index 831d696..7ef3439 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/JavaRecordType.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/JavaRecordType.java
@@ -19,8 +19,6 @@ package org.apache.calcite.jdbc;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rel.type.RelRecordType;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
 import java.util.Objects;
 
@@ -36,7 +34,7 @@ public class JavaRecordType extends RelRecordType {
 
   public JavaRecordType(List<RelDataTypeField> fields, Class clazz) {
     super(fields);
-    this.clazz = Preconditions.checkNotNull(clazz);
+    this.clazz = Objects.requireNonNull(clazz);
   }
 
   @Override public boolean equals(Object obj) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/JavaTypeFactoryImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/JavaTypeFactoryImpl.java b/core/src/main/java/org/apache/calcite/jdbc/JavaTypeFactoryImpl.java
index 8999f44..59805fe 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/JavaTypeFactoryImpl.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/JavaTypeFactoryImpl.java
@@ -37,8 +37,6 @@ import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
 import java.lang.reflect.Field;
@@ -50,6 +48,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Implementation of {@link JavaTypeFactory}.
@@ -245,11 +244,7 @@ public class JavaTypeFactoryImpl
     if (type instanceof RelRecordType) {
       return typeFactory.createStructType(
           Lists.transform(type.getFieldList(),
-              new Function<RelDataTypeField, RelDataType>() {
-                public RelDataType apply(RelDataTypeField a0) {
-                  return toSql(typeFactory, a0.getType());
-                }
-              }),
+              field -> toSql(typeFactory, field.getType())),
           type.getFieldNames());
     }
     if (type instanceof JavaType) {
@@ -367,9 +362,9 @@ public class JavaTypeFactoryImpl
         Type type,
         boolean nullable,
         int modifiers) {
-      this.syntheticType = Preconditions.checkNotNull(syntheticType);
-      this.name = Preconditions.checkNotNull(name);
-      this.type = Preconditions.checkNotNull(type);
+      this.syntheticType = Objects.requireNonNull(syntheticType);
+      this.name = Objects.requireNonNull(name);
+      this.type = Objects.requireNonNull(type);
       this.nullable = nullable;
       this.modifiers = modifiers;
       assert !(nullable && Primitive.is(type))

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/jdbc/MetadataSchema.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/jdbc/MetadataSchema.java b/core/src/main/java/org/apache/calcite/jdbc/MetadataSchema.java
index 5fb2e89..c11ccea 100644
--- a/core/src/main/java/org/apache/calcite/jdbc/MetadataSchema.java
+++ b/core/src/main/java/org/apache/calcite/jdbc/MetadataSchema.java
@@ -16,9 +16,7 @@
  */
 package org.apache.calcite.jdbc;
 
-import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Enumerator;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.schema.Schema;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.AbstractSchema;
@@ -34,7 +32,7 @@ import static org.apache.calcite.jdbc.CalciteMetaImpl.MetaTable;
 /** Schema that contains metadata tables such as "TABLES" and "COLUMNS". */
 class MetadataSchema extends AbstractSchema {
   private static final Map<String, Table> TABLE_MAP =
-      ImmutableMap.<String, Table>of(
+      ImmutableMap.of(
           "COLUMNS",
           new CalciteMetaImpl.MetadataTable<MetaColumn>(MetaColumn.class) {
             public Enumerator<MetaColumn> enumerator(
@@ -45,12 +43,8 @@ class MetadataSchema extends AbstractSchema {
               } catch (SQLException e) {
                 throw new RuntimeException(e);
               }
-              return meta.tables(catalog).selectMany(
-                  new Function1<MetaTable, Enumerable<MetaColumn>>() {
-                    public Enumerable<MetaColumn> apply(MetaTable table) {
-                      return meta.columns(table);
-                    }
-                  }).enumerator();
+              return meta.tables(catalog)
+                  .selectMany(meta::columns).enumerator();
             }
           },
           "TABLES",

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/CachingLatticeStatisticProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/CachingLatticeStatisticProvider.java b/core/src/main/java/org/apache/calcite/materialize/CachingLatticeStatisticProvider.java
index 21c6fed..fb102d7 100644
--- a/core/src/main/java/org/apache/calcite/materialize/CachingLatticeStatisticProvider.java
+++ b/core/src/main/java/org/apache/calcite/materialize/CachingLatticeStatisticProvider.java
@@ -27,7 +27,6 @@ import com.google.common.util.concurrent.UncheckedExecutionException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
-import javax.annotation.Nonnull;
 
 /**
  * Implementation of {@link LatticeStatisticProvider} that caches single-column
@@ -41,13 +40,8 @@ class CachingLatticeStatisticProvider implements LatticeStatisticProvider {
   CachingLatticeStatisticProvider(final Lattice lattice,
       final LatticeStatisticProvider provider) {
     this.lattice = lattice;
-    cache = CacheBuilder.<Lattice.Column>newBuilder()
-        .build(
-            new CacheLoader<Lattice.Column, Double>() {
-              public Double load(@Nonnull Lattice.Column key) throws Exception {
-                return provider.cardinality(ImmutableList.of(key));
-              }
-            });
+    cache = CacheBuilder.<Lattice.Column>newBuilder().build(
+        CacheLoader.from(key -> provider.cardinality(ImmutableList.of(key))));
   }
 
   public double cardinality(List<Lattice.Column> columns) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/Lattice.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/Lattice.java b/core/src/main/java/org/apache/calcite/materialize/Lattice.java
index 3828416..0e09f63 100644
--- a/core/src/main/java/org/apache/calcite/materialize/Lattice.java
+++ b/core/src/main/java/org/apache/calcite/materialize/Lattice.java
@@ -52,16 +52,15 @@ import org.apache.calcite.util.graph.DirectedGraph;
 import org.apache.calcite.util.graph.TopologicalOrderIterator;
 import org.apache.calcite.util.mapping.IntPair;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableListMultimap;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Ordering;
-import com.google.common.collect.Sets;
 
 import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -72,20 +71,6 @@ import java.util.Set;
  * recognized and recommended.
  */
 public class Lattice {
-  private static final Function<Column, String> GET_ALIAS =
-      new Function<Column, String>() {
-        public String apply(Column input) {
-          return input.alias;
-        }
-      };
-
-  private static final Function<Column, Integer> GET_ORDINAL =
-      new Function<Column, Integer>() {
-        public Integer apply(Column input) {
-          return input.ordinal;
-        }
-      };
-
   public final CalciteSchema rootSchema;
   public final ImmutableList<Node> nodes;
   public final ImmutableList<Column> columns;
@@ -98,33 +83,19 @@ public class Lattice {
   public final ImmutableList<String> uniqueColumnNames;
   public final LatticeStatisticProvider statisticProvider;
 
-  private final Function<Integer, Column> toColumnFunction =
-      new Function<Integer, Column>() {
-        public Column apply(Integer input) {
-          return columns.get(input);
-        }
-      };
-  private final Function<AggregateCall, Measure> toMeasureFunction =
-      new Function<AggregateCall, Measure>() {
-        public Measure apply(AggregateCall input) {
-          return new Measure(input.getAggregation(),
-              Lists.transform(input.getArgList(), toColumnFunction));
-        }
-      };
-
   private Lattice(CalciteSchema rootSchema, ImmutableList<Node> nodes,
       boolean auto, boolean algorithm, long algorithmMaxMillis,
       LatticeStatisticProvider.Factory statisticProviderFactory,
       Double rowCountEstimate, ImmutableList<Column> columns,
       ImmutableList<Measure> defaultMeasures, ImmutableList<Tile> tiles) {
     this.rootSchema = rootSchema;
-    this.nodes = Preconditions.checkNotNull(nodes);
-    this.columns = Preconditions.checkNotNull(columns);
+    this.nodes = Objects.requireNonNull(nodes);
+    this.columns = Objects.requireNonNull(columns);
     this.auto = auto;
     this.algorithm = algorithm;
     this.algorithmMaxMillis = algorithmMaxMillis;
-    this.defaultMeasures = Preconditions.checkNotNull(defaultMeasures);
-    this.tiles = Preconditions.checkNotNull(tiles);
+    this.defaultMeasures = Objects.requireNonNull(defaultMeasures);
+    this.tiles = Objects.requireNonNull(tiles);
 
     // Validate that nodes form a tree; each node except the first references
     // a predecessor.
@@ -137,13 +108,14 @@ public class Lattice {
       }
     }
 
-    List<String> nameList = Lists.newArrayList();
+    List<String> nameList = new ArrayList<>();
     for (Column column : columns) {
       nameList.add(column.alias);
     }
     uniqueColumnNames =
         ImmutableList.copyOf(
-            SqlValidatorUtil.uniquify(Lists.transform(columns, GET_ALIAS), true));
+            SqlValidatorUtil.uniquify(
+                Lists.transform(columns, input -> input.alias), true));
     if (rowCountEstimate == null) {
       // We could improve this when we fix
       // [CALCITE-429] Add statistics SPI for lattice optimization algorithm
@@ -152,7 +124,7 @@ public class Lattice {
     Preconditions.checkArgument(rowCountEstimate > 0d);
     this.rowCountEstimate = rowCountEstimate;
     this.statisticProvider =
-        Preconditions.checkNotNull(statisticProviderFactory.apply(this));
+        Objects.requireNonNull(statisticProviderFactory.apply(this));
   }
 
   /** Creates a Lattice. */
@@ -274,7 +246,7 @@ public class Lattice {
     final StringBuilder buf = new StringBuilder("SELECT ");
     final StringBuilder groupBuf = new StringBuilder("\nGROUP BY ");
     int k = 0;
-    final Set<String> columnNames = Sets.newHashSet();
+    final Set<String> columnNames = new HashSet<>();
     if (groupSet != null) {
       for (int i : groupSet) {
         if (k++ > 0) {
@@ -359,7 +331,7 @@ public class Lattice {
    * attributes given in {@code groupSet}. */
   public String countSql(ImmutableBitSet groupSet) {
     return "select count(*) as c from ("
-        + sql(groupSet, ImmutableList.<Measure>of())
+        + sql(groupSet, ImmutableList.of())
         + ")";
   }
 
@@ -373,7 +345,7 @@ public class Lattice {
   }
 
   public StarTable createStarTable() {
-    final List<Table> tables = Lists.newArrayList();
+    final List<Table> tables = new ArrayList<>();
     for (Node node : nodes) {
       tables.add(node.scan.getTable().unwrap(Table.class));
     }
@@ -385,7 +357,9 @@ public class Lattice {
   }
 
   public List<Measure> toMeasures(List<AggregateCall> aggCallList) {
-    return Lists.transform(aggCallList, toMeasureFunction);
+    return Lists.transform(aggCallList,
+        call -> new Measure(call.getAggregation(),
+        Lists.transform(call.getArgList(), columns::get)));
   }
 
   public Iterable<? extends Tile> computeTiles() {
@@ -454,7 +428,7 @@ public class Lattice {
 
     public Node(TableScan scan, Node parent, List<IntPair> link,
         int startCol, int endCol, String alias) {
-      this.scan = Preconditions.checkNotNull(scan);
+      this.scan = Objects.requireNonNull(scan);
       this.parent = parent;
       this.link = link == null ? null : ImmutableList.copyOf(link);
       assert (parent == null) == (link == null);
@@ -469,13 +443,9 @@ public class Lattice {
   /** Edge in the temporary graph. */
   private static class Edge extends DefaultEdge {
     public static final DirectedGraph.EdgeFactory<RelNode, Edge> FACTORY =
-        new DirectedGraph.EdgeFactory<RelNode, Edge>() {
-          public Edge createEdge(RelNode source, RelNode target) {
-            return new Edge(source, target);
-          }
-        };
+        Edge::new;
 
-    final List<IntPair> pairs = Lists.newArrayList();
+    final List<IntPair> pairs = new ArrayList<>();
 
     Edge(RelNode source, RelNode target) {
       super(source, target);
@@ -496,7 +466,7 @@ public class Lattice {
     public final ImmutableList<Column> args;
 
     public Measure(SqlAggFunction agg, Iterable<Column> args) {
-      this.agg = Preconditions.checkNotNull(agg);
+      this.agg = Objects.requireNonNull(agg);
       this.args = ImmutableList.copyOf(args);
     }
 
@@ -534,7 +504,7 @@ public class Lattice {
 
     /** Returns a list of argument ordinals. */
     public List<Integer> argOrdinals() {
-      return Lists.transform(args, GET_ORDINAL);
+      return Lists.transform(args, input -> input.ordinal);
     }
 
     private static int compare(List<Column> list0, List<Column> list1) {
@@ -562,9 +532,9 @@ public class Lattice {
 
     private Column(int ordinal, String table, String column, String alias) {
       this.ordinal = ordinal;
-      this.table = Preconditions.checkNotNull(table);
-      this.column = Preconditions.checkNotNull(column);
-      this.alias = Preconditions.checkNotNull(alias);
+      this.table = Objects.requireNonNull(table);
+      this.column = Objects.requireNonNull(column);
+      this.alias = Objects.requireNonNull(alias);
     }
 
     /** Converts a list of columns to a bit set of their ordinals. */
@@ -601,7 +571,7 @@ public class Lattice {
 
   /** Lattice builder. */
   public static class Builder {
-    private final List<Node> nodes = Lists.newArrayList();
+    private final List<Node> nodes = new ArrayList<>();
     private final ImmutableList<Column> columns;
     private final ImmutableListMultimap<String, Column> columnsByAlias;
     private final ImmutableList.Builder<Measure> defaultMeasureListBuilder =
@@ -616,19 +586,19 @@ public class Lattice {
     private String statisticProvider;
 
     public Builder(CalciteSchema schema, String sql) {
-      this.rootSchema = Preconditions.checkNotNull(schema.root());
+      this.rootSchema = Objects.requireNonNull(schema.root());
       Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
       CalcitePrepare.ConvertResult parsed =
           Schemas.convert(MaterializedViewTable.MATERIALIZATION_CONNECTION,
               schema, schema.path(null), sql);
 
       // Walk the join tree.
-      List<RelNode> relNodes = Lists.newArrayList();
-      List<int[][]> tempLinks = Lists.newArrayList();
+      List<RelNode> relNodes = new ArrayList<>();
+      List<int[][]> tempLinks = new ArrayList<>();
       populate(relNodes, tempLinks, parsed.root.rel);
 
       // Get aliases.
-      List<String> aliases = Lists.newArrayList();
+      List<String> aliases = new ArrayList<>();
       populateAliases(((SqlSelect) parsed.sqlNode).getFrom(), aliases, null);
 
       // Build a graph.
@@ -650,7 +620,7 @@ public class Lattice {
       // Convert the graph into a tree of nodes, each connected to a parent and
       // with a join condition to that parent.
       Node previous = null;
-      final Map<RelNode, Node> map = Maps.newIdentityHashMap();
+      final Map<RelNode, Node> map = new IdentityHashMap<>();
       int previousColumn = 0;
       for (RelNode relNode : TopologicalOrderIterator.of(graph)) {
         final List<Edge> edges = graph.getInwardEdges(relNode);
@@ -857,8 +827,8 @@ public class Lattice {
 
     public Tile(ImmutableList<Measure> measures,
         ImmutableList<Column> dimensions) {
-      this.measures = Preconditions.checkNotNull(measures);
-      this.dimensions = Preconditions.checkNotNull(dimensions);
+      this.measures = Objects.requireNonNull(measures);
+      this.dimensions = Objects.requireNonNull(dimensions);
       assert Ordering.natural().isStrictlyOrdered(dimensions);
       assert Ordering.natural().isStrictlyOrdered(measures);
       bitSet = Column.toBitSet(dimensions);
@@ -875,8 +845,8 @@ public class Lattice {
 
   /** Tile builder. */
   public static class TileBuilder {
-    private final List<Measure> measureBuilder = Lists.newArrayList();
-    private final List<Column> dimensionListBuilder = Lists.newArrayList();
+    private final List<Measure> measureBuilder = new ArrayList<>();
+    private final List<Column> dimensionListBuilder = new ArrayList<>();
 
     public Tile build() {
       return new Tile(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/LatticeStatisticProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/LatticeStatisticProvider.java b/core/src/main/java/org/apache/calcite/materialize/LatticeStatisticProvider.java
index d16e903..d191f8b 100644
--- a/core/src/main/java/org/apache/calcite/materialize/LatticeStatisticProvider.java
+++ b/core/src/main/java/org/apache/calcite/materialize/LatticeStatisticProvider.java
@@ -16,9 +16,8 @@
  */
 package org.apache.calcite.materialize;
 
-import com.google.common.base.Function;
-
 import java.util.List;
+import java.util.function.Function;
 
 /**
  * Estimates row counts for a lattice and its attributes.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/MaterializationActor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/MaterializationActor.java b/core/src/main/java/org/apache/calcite/materialize/MaterializationActor.java
index 4564478..f01b9af 100644
--- a/core/src/main/java/org/apache/calcite/materialize/MaterializationActor.java
+++ b/core/src/main/java/org/apache/calcite/materialize/MaterializationActor.java
@@ -21,9 +21,9 @@ import org.apache.calcite.rel.type.RelDataType;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
 
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -35,11 +35,11 @@ class MaterializationActor {
   // Not an actor yet -- TODO make members private and add request/response
   // queues
 
-  final Map<MaterializationKey, Materialization> keyMap = Maps.newHashMap();
+  final Map<MaterializationKey, Materialization> keyMap = new HashMap<>();
 
-  final Map<QueryKey, MaterializationKey> keyBySql = Maps.newHashMap();
+  final Map<QueryKey, MaterializationKey> keyBySql = new HashMap<>();
 
-  final Map<TileKey, MaterializationKey> keyByTile = Maps.newHashMap();
+  final Map<TileKey, MaterializationKey> keyByTile = new HashMap<>();
 
   /** Tiles grouped by dimensionality. We use a
    *  {@link TileKey} with no measures to represent a
@@ -75,7 +75,7 @@ class MaterializationActor {
         RelDataType rowType,
         List<String> viewSchemaPath) {
       this.key = key;
-      this.rootSchema = Preconditions.checkNotNull(rootSchema);
+      this.rootSchema = Objects.requireNonNull(rootSchema);
       Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
       this.materializedTable = materializedTable; // may be null
       this.sql = sql;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java b/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java
index 39a077f..e013d08 100644
--- a/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java
+++ b/core/src/main/java/org/apache/calcite/materialize/MaterializationService.java
@@ -18,7 +18,6 @@ package org.apache.calcite.materialize;
 
 import org.apache.calcite.DataContext;
 import org.apache.calcite.adapter.clone.CloneSchema;
-import org.apache.calcite.avatica.ColumnMetaData;
 import org.apache.calcite.config.CalciteConnectionProperty;
 import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.jdbc.CalciteMetaImpl;
@@ -38,11 +37,9 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
 
 import java.lang.reflect.Type;
 import java.util.ArrayList;
@@ -52,6 +49,7 @@ import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.PriorityQueue;
+import java.util.Set;
 
 /**
  * Manages the collection of materialized tables known to the system,
@@ -63,27 +61,20 @@ public class MaterializationService {
 
   /** For testing. */
   private static final ThreadLocal<MaterializationService> THREAD_INSTANCE =
-      new ThreadLocal<MaterializationService>() {
-        @Override protected MaterializationService initialValue() {
-          return new MaterializationService();
-        }
-      };
+      ThreadLocal.withInitial(MaterializationService::new);
 
   private static final Comparator<Pair<CalciteSchema.TableEntry, TileKey>> C =
-      new Comparator<Pair<CalciteSchema.TableEntry, TileKey>>() {
-        public int compare(Pair<CalciteSchema.TableEntry, TileKey> o0,
-            Pair<CalciteSchema.TableEntry, TileKey> o1) {
-          // We prefer rolling up from the table with the fewest rows.
-          final Table t0 = o0.left.getTable();
-          final Table t1 = o1.left.getTable();
-          int c = Double.compare(t0.getStatistic().getRowCount(),
-              t1.getStatistic().getRowCount());
-          if (c != 0) {
-            return c;
-          }
-          // Tie-break based on table name.
-          return o0.left.name.compareTo(o1.left.name);
+      (o0, o1) -> {
+        // We prefer rolling up from the table with the fewest rows.
+        final Table t0 = o0.left.getTable();
+        final Table t1 = o1.left.getTable();
+        int c = Double.compare(t0.getStatistic().getRowCount(),
+            t1.getStatistic().getRowCount());
+        if (c != 0) {
+          return c;
         }
+        // Tie-break based on table name.
+        return o0.left.name.compareTo(o1.left.name);
       };
 
   private final MaterializationActor actor = new MaterializationActor();
@@ -207,7 +198,7 @@ public class MaterializationService {
     // Step 2. Look for a match of the tile with the same dimensionality and an
     // acceptable list of measures.
     final TileKey tileKey0 =
-        new TileKey(lattice, groupSet, ImmutableList.<Lattice.Measure>of());
+        new TileKey(lattice, groupSet, ImmutableList.of());
     for (TileKey tileKey1 : actor.tilesByDimensionality.get(tileKey0)) {
       assert tileKey1.dimensions.equals(groupSet);
       if (allSatisfiable(measureList, tileKey1)) {
@@ -267,8 +258,8 @@ public class MaterializationService {
     // whether they were current, create a wider tile that contains their
     // measures plus the currently requested measures. Then we can obsolete all
     // other tiles.
-    final List<TileKey> obsolete = Lists.newArrayList();
-    final LinkedHashSet<Lattice.Measure> measureSet = Sets.newLinkedHashSet();
+    final List<TileKey> obsolete = new ArrayList<>();
+    final Set<Lattice.Measure> measureSet = new LinkedHashSet<>();
     for (TileKey tileKey1 : actor.tilesByDimensionality.get(tileKey0)) {
       measureSet.addAll(tileKey1.measures);
       obsolete.add(tileKey1);
@@ -380,12 +371,7 @@ public class MaterializationService {
       return CloneSchema.createCloneTable(connection.getTypeFactory(),
           RelDataTypeImpl.proto(calciteSignature.rowType),
           calciteSignature.getCollationList(),
-          Lists.transform(calciteSignature.columns,
-              new Function<ColumnMetaData, ColumnMetaData.Rep>() {
-                public ColumnMetaData.Rep apply(ColumnMetaData column) {
-                  return column.type.rep;
-                }
-              }),
+          Lists.transform(calciteSignature.columns, column -> column.type.rep),
           new AbstractQueryable<Object>() {
             public Enumerator<Object> enumerator() {
               final DataContext dataContext =

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/ProfilerLatticeStatisticProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/ProfilerLatticeStatisticProvider.java b/core/src/main/java/org/apache/calcite/materialize/ProfilerLatticeStatisticProvider.java
index 39e0b29..3653b46 100644
--- a/core/src/main/java/org/apache/calcite/materialize/ProfilerLatticeStatisticProvider.java
+++ b/core/src/main/java/org/apache/calcite/materialize/ProfilerLatticeStatisticProvider.java
@@ -17,7 +17,6 @@
 package org.apache.calcite.materialize;
 
 import org.apache.calcite.linq4j.Enumerable;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.profile.Profiler;
 import org.apache.calcite.profile.ProfilerImpl;
 import org.apache.calcite.rel.metadata.NullSentinel;
@@ -25,73 +24,58 @@ import org.apache.calcite.schema.ScannableTable;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
 import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;
 
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Objects;
+import java.util.function.Supplier;
 
 /**
  * Implementation of {@link LatticeStatisticProvider} that uses a
  * {@link org.apache.calcite.profile.Profiler}.
  */
 class ProfilerLatticeStatisticProvider implements LatticeStatisticProvider {
-  static final Factory FACTORY =
-      new Factory() {
-        public LatticeStatisticProvider apply(Lattice lattice) {
-          return new ProfilerLatticeStatisticProvider(lattice);
-        }
-      };
+  static final Factory FACTORY = ProfilerLatticeStatisticProvider::new;
 
-  /** Converts an array of values to a list of {@link Comparable} values,
-   * converting null values to sentinels. */
-  private static final Function1<Object[], List<Comparable>> TO_LIST =
-      new Function1<Object[], List<Comparable>>() {
-        public List<Comparable> apply(Object[] values) {
-          for (int i = 0; i < values.length; i++) {
-            if (values[i] == null) {
-              values[i] = NullSentinel.INSTANCE;
-            }
-          }
-          //noinspection unchecked
-          return (List) Arrays.asList(values);
-        }
-      };
-
-  private final Lattice lattice;
-  private final Supplier<Profiler.Profile> profile =
-      Suppliers.memoize(new Supplier<Profiler.Profile>() {
-        public Profiler.Profile get() {
-          final ProfilerImpl profiler =
-              ProfilerImpl.builder()
-                  .withPassSize(200)
-                  .withMinimumSurprise(0.3D)
-                  .build();
-          final List<Profiler.Column> columns = new ArrayList<>();
-          for (Lattice.Column column : lattice.columns) {
-            columns.add(new Profiler.Column(column.ordinal, column.alias));
-          }
-          final String sql =
-              lattice.sql(ImmutableBitSet.range(lattice.columns.size()),
-                  false, ImmutableList.<Lattice.Measure>of());
-          final Table table =
-              new MaterializationService.DefaultTableFactory()
-                  .createTable(lattice.rootSchema, sql,
-                      ImmutableList.<String>of());
-          final ImmutableList<ImmutableBitSet> initialGroups =
-              ImmutableList.of();
-          final Enumerable<List<Comparable>> rows =
-              ((ScannableTable) table).scan(null).select(TO_LIST);
-          return profiler.profile(rows, columns, initialGroups);
-        }
-      });
+  private final Supplier<Profiler.Profile> profile;
 
   /** Creates a ProfilerLatticeStatisticProvider. */
   private ProfilerLatticeStatisticProvider(Lattice lattice) {
-    this.lattice = Preconditions.checkNotNull(lattice);
+    Objects.requireNonNull(lattice);
+    this.profile = Suppliers.memoize(() -> {
+      final ProfilerImpl profiler =
+          ProfilerImpl.builder()
+              .withPassSize(200)
+              .withMinimumSurprise(0.3D)
+              .build();
+      final List<Profiler.Column> columns = new ArrayList<>();
+      for (Lattice.Column column : lattice.columns) {
+        columns.add(new Profiler.Column(column.ordinal, column.alias));
+      }
+      final String sql =
+          lattice.sql(ImmutableBitSet.range(lattice.columns.size()),
+              false, ImmutableList.of());
+      final Table table =
+          new MaterializationService.DefaultTableFactory()
+              .createTable(lattice.rootSchema, sql, ImmutableList.of());
+      final ImmutableList<ImmutableBitSet> initialGroups =
+          ImmutableList.of();
+      final Enumerable<List<Comparable>> rows =
+          ((ScannableTable) table).scan(null)
+              .select(values -> {
+                for (int i = 0; i < values.length; i++) {
+                  if (values[i] == null) {
+                    values[i] = NullSentinel.INSTANCE;
+                  }
+                }
+                //noinspection unchecked
+                return (List<Comparable>) (List) Arrays.asList(values);
+              });
+      return profiler.profile(rows, columns, initialGroups);
+    })::get;
   }
 
   public double cardinality(List<Lattice.Column> columns) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/SqlLatticeStatisticProvider.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/SqlLatticeStatisticProvider.java b/core/src/main/java/org/apache/calcite/materialize/SqlLatticeStatisticProvider.java
index 8e5b19d..28d804c 100644
--- a/core/src/main/java/org/apache/calcite/materialize/SqlLatticeStatisticProvider.java
+++ b/core/src/main/java/org/apache/calcite/materialize/SqlLatticeStatisticProvider.java
@@ -20,38 +20,30 @@ import org.apache.calcite.schema.ScannableTable;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Implementation of {@link LatticeStatisticProvider} that gets statistics by
  * executing "SELECT COUNT(DISTINCT ...) ..." SQL queries.
  */
 class SqlLatticeStatisticProvider implements LatticeStatisticProvider {
-  static final Factory FACTORY =
-      new LatticeStatisticProvider.Factory() {
-        public LatticeStatisticProvider apply(Lattice lattice) {
-          return new SqlLatticeStatisticProvider(lattice);
-        }
-      };
+  static final Factory FACTORY = SqlLatticeStatisticProvider::new;
 
-  static final Factory CACHED_FACTORY =
-      new LatticeStatisticProvider.Factory() {
-        public LatticeStatisticProvider apply(Lattice lattice) {
-          LatticeStatisticProvider provider = FACTORY.apply(lattice);
-          return new CachingLatticeStatisticProvider(lattice, provider);
-        }
-      };
+  static final Factory CACHED_FACTORY = lattice -> {
+    LatticeStatisticProvider provider = FACTORY.apply(lattice);
+    return new CachingLatticeStatisticProvider(lattice, provider);
+  };
 
   private final Lattice lattice;
 
   /** Creates a SqlLatticeStatisticProvider. */
   private SqlLatticeStatisticProvider(Lattice lattice) {
-    this.lattice = Preconditions.checkNotNull(lattice);
+    this.lattice = Objects.requireNonNull(lattice);
   }
 
   public double cardinality(List<Lattice.Column> columns) {
@@ -66,7 +58,7 @@ class SqlLatticeStatisticProvider implements LatticeStatisticProvider {
     final String sql = lattice.countSql(ImmutableBitSet.of(column.ordinal));
     final Table table =
         new MaterializationService.DefaultTableFactory()
-            .createTable(lattice.rootSchema, sql, ImmutableList.<String>of());
+            .createTable(lattice.rootSchema, sql, ImmutableList.of());
     final Object[] values =
         Iterables.getOnlyElement(((ScannableTable) table).scan(null));
     return ((Number) values[0]).doubleValue();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/materialize/TileSuggester.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/materialize/TileSuggester.java b/core/src/main/java/org/apache/calcite/materialize/TileSuggester.java
index bc98d94..64cf736 100644
--- a/core/src/main/java/org/apache/calcite/materialize/TileSuggester.java
+++ b/core/src/main/java/org/apache/calcite/materialize/TileSuggester.java
@@ -18,10 +18,8 @@ package org.apache.calcite.materialize;
 
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
 
 import org.pentaho.aggdes.algorithm.Algorithm;
 import org.pentaho.aggdes.algorithm.Progress;
@@ -46,13 +44,6 @@ import java.util.List;
  * for a given lattice.
  */
 public class TileSuggester {
-  private static final Function<Attribute, Lattice.Column> TO_COLUMN =
-      new Function<Attribute, Lattice.Column>() {
-        public Lattice.Column apply(Attribute input) {
-          return ((AttributeImpl) input).column;
-        }
-      };
-
   private final Lattice lattice;
 
   public TileSuggester(Lattice lattice) {
@@ -206,7 +197,8 @@ public class TileSuggester {
     }
 
     public double getRowCount(List<Attribute> attributes) {
-      return lattice.getRowCount(Lists.transform(attributes, TO_COLUMN));
+      return lattice.getRowCount(
+          Util.transform(attributes, input -> ((AttributeImpl) input).column));
     }
 
     public double getSpace(List<Attribute> attributes) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java b/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
index 81a297b..06306d5 100644
--- a/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
+++ b/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
@@ -21,7 +21,6 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexExecutor;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.util.CancelFlag;
 
 import com.google.common.collect.ImmutableList;
@@ -38,7 +37,6 @@ import java.util.regex.Pattern;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
-
 /**
  * Abstract base for implementations of the {@link RelOptPlanner} interface.
  */
@@ -417,12 +415,7 @@ public abstract class AbstractRelOptPlanner implements RelOptPlanner {
   /** Returns sub-classes of relational expression. */
   public Iterable<Class<? extends RelNode>> subClasses(
       final Class<? extends RelNode> clazz) {
-    return Iterables.filter(classes,
-        new PredicateImpl<Class<? extends RelNode>>() {
-          public boolean test(Class<? extends RelNode> input) {
-            return clazz.isAssignableFrom(input);
-          }
-        });
+    return Iterables.filter(classes, clazz::isAssignableFrom);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/Contexts.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/Contexts.java b/core/src/main/java/org/apache/calcite/plan/Contexts.java
index 2aad6b1..adc13da 100644
--- a/core/src/main/java/org/apache/calcite/plan/Contexts.java
+++ b/core/src/main/java/org/apache/calcite/plan/Contexts.java
@@ -18,12 +18,11 @@ package org.apache.calcite.plan;
 
 import org.apache.calcite.config.CalciteConnectionConfig;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Utilities for {@link Context}.
@@ -82,7 +81,7 @@ public class Contexts {
 
   private static Context chain(Iterable<? extends Context> contexts) {
     // Flatten any chain contexts in the list, and remove duplicates
-    final List<Context> list = Lists.newArrayList();
+    final List<Context> list = new ArrayList<>();
     for (Context context : contexts) {
       build(list, context);
     }
@@ -116,7 +115,7 @@ public class Contexts {
     final Object target;
 
     WrapContext(Object target) {
-      this.target = Preconditions.checkNotNull(target);
+      this.target = Objects.requireNonNull(target);
     }
 
     public <T> T unwrap(Class<T> clazz) {
@@ -139,7 +138,7 @@ public class Contexts {
     final ImmutableList<Context> contexts;
 
     ChainContext(ImmutableList<Context> contexts) {
-      this.contexts = Preconditions.checkNotNull(contexts);
+      this.contexts = Objects.requireNonNull(contexts);
       for (Context context : contexts) {
         assert !(context instanceof ChainContext) : "must be flat";
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/ConventionTraitDef.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/ConventionTraitDef.java b/core/src/main/java/org/apache/calcite/plan/ConventionTraitDef.java
index a0b7e37..ff9de80 100644
--- a/core/src/main/java/org/apache/calcite/plan/ConventionTraitDef.java
+++ b/core/src/main/java/org/apache/calcite/plan/ConventionTraitDef.java
@@ -32,7 +32,6 @@ import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Multimap;
 
 import java.util.List;
-import javax.annotation.Nonnull;
 
 /**
  * Definition of the the convention trait.
@@ -59,12 +58,8 @@ public class ConventionTraitDef extends RelTraitDef<Convention> {
    * the planner goes away, so does the cache entry.
    */
   private final LoadingCache<RelOptPlanner, ConversionData> conversionCache =
-      CacheBuilder.newBuilder().weakKeys().build(
-          new CacheLoader<RelOptPlanner, ConversionData>() {
-            public ConversionData load(@Nonnull RelOptPlanner key) {
-              return new ConversionData();
-            }
-          });
+      CacheBuilder.newBuilder().weakKeys()
+          .build(CacheLoader.from(ConversionData::new));
 
   //~ Constructors -----------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelCompositeTrait.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelCompositeTrait.java b/core/src/main/java/org/apache/calcite/plan/RelCompositeTrait.java
index a7d1b00..b2a4ffc 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelCompositeTrait.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelCompositeTrait.java
@@ -16,12 +16,12 @@
  */
 package org.apache.calcite.plan;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Ordering;
 
 import java.util.Arrays;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * A trait that consists of a list of traits, all of the same type.
@@ -40,7 +40,7 @@ class RelCompositeTrait<T extends RelMultipleTrait> implements RelTrait {
   // Must remain private. Does not copy the array.
   private RelCompositeTrait(RelTraitDef traitDef, T[] traits) {
     this.traitDef = traitDef;
-    this.traits = Preconditions.checkNotNull(traits);
+    this.traits = Objects.requireNonNull(traits);
     //noinspection unchecked
     assert Ordering.natural()
         .isStrictlyOrdered(Arrays.asList((Comparable[]) traits))
@@ -59,7 +59,7 @@ class RelCompositeTrait<T extends RelMultipleTrait> implements RelTrait {
       compositeTrait = new EmptyCompositeTrait<T>(def);
     } else {
       final RelMultipleTrait[] traits =
-          traitList.toArray(new RelMultipleTrait[traitList.size()]);
+          traitList.toArray(new RelMultipleTrait[0]);
       for (int i = 0; i < traits.length; i++) {
         traits[i] = (T) def.canonize(traits[i]);
       }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/plan/RelOptCluster.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/plan/RelOptCluster.java b/core/src/main/java/org/apache/calcite/plan/RelOptCluster.java
index bce405c..c853eb8 100644
--- a/core/src/main/java/org/apache/calcite/plan/RelOptCluster.java
+++ b/core/src/main/java/org/apache/calcite/plan/RelOptCluster.java
@@ -27,10 +27,9 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexNode;
 
-import com.google.common.base.Preconditions;
-
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Objects;
 import java.util.concurrent.atomic.AtomicInteger;
 
 /**
@@ -76,8 +75,8 @@ public class RelOptCluster {
       Map<String, RelNode> mapCorrelToRel) {
     this.nextCorrel = nextCorrel;
     this.mapCorrelToRel = mapCorrelToRel;
-    this.planner = Preconditions.checkNotNull(planner);
-    this.typeFactory = Preconditions.checkNotNull(typeFactory);
+    this.planner = Objects.requireNonNull(planner);
+    this.typeFactory = Objects.requireNonNull(typeFactory);
     this.rexBuilder = rexBuilder;
     this.originalExpression = rexBuilder.makeLiteral("?");
 


[13/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql2rel/ReflectiveConvertletTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/ReflectiveConvertletTable.java b/core/src/main/java/org/apache/calcite/sql2rel/ReflectiveConvertletTable.java
index 4d87df1..314970a 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/ReflectiveConvertletTable.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/ReflectiveConvertletTable.java
@@ -78,19 +78,14 @@ public class ReflectiveConvertletTable implements SqlRexConvertletTable {
     if (!SqlNode.class.isAssignableFrom(parameterType)) {
       return;
     }
-    map.put(parameterType,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(
-              SqlRexContext cx,
-              SqlCall call) {
-            try {
-              return (RexNode) method.invoke(ReflectiveConvertletTable.this,
-                  cx, call);
-            } catch (IllegalAccessException | InvocationTargetException e) {
-              throw new RuntimeException("while converting " + call, e);
-            }
-          }
-        });
+    map.put(parameterType, (SqlRexConvertlet) (cx, call) -> {
+      try {
+        return (RexNode) method.invoke(ReflectiveConvertletTable.this,
+            cx, call);
+      } catch (IllegalAccessException | InvocationTargetException e) {
+        throw new RuntimeException("while converting " + call, e);
+      }
+    });
   }
 
   /**
@@ -124,17 +119,14 @@ public class ReflectiveConvertletTable implements SqlRexConvertletTable {
     if (!SqlCall.class.isAssignableFrom(parameterType)) {
       return;
     }
-    map.put(opClass,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            try {
-              return (RexNode) method.invoke(ReflectiveConvertletTable.this,
-                  cx, call.getOperator(), call);
-            } catch (IllegalAccessException | InvocationTargetException e) {
-              throw new RuntimeException("while converting " + call, e);
-            }
-          }
-        });
+    map.put(opClass, (SqlRexConvertlet) (cx, call) -> {
+      try {
+        return (RexNode) method.invoke(ReflectiveConvertletTable.this,
+            cx, call.getOperator(), call);
+      } catch (IllegalAccessException | InvocationTargetException e) {
+        throw new RuntimeException("while converting " + call, e);
+      }
+    });
   }
 
   public SqlRexConvertlet get(SqlCall call) {
@@ -191,17 +183,12 @@ public class ReflectiveConvertletTable implements SqlRexConvertletTable {
    */
   protected void addAlias(final SqlOperator alias, final SqlOperator target) {
     map.put(
-        alias,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(
-              SqlRexContext cx,
-              SqlCall call) {
-            Preconditions.checkArgument(call.getOperator() == alias,
-                "call to wrong operator");
-            final SqlCall newCall =
-                target.createCall(SqlParserPos.ZERO, call.getOperandList());
-            return cx.convertExpression(newCall);
-          }
+        alias, (SqlRexConvertlet) (cx, call) -> {
+          Preconditions.checkArgument(call.getOperator() == alias,
+              "call to wrong operator");
+          final SqlCall newCall =
+              target.createCall(SqlParserPos.ZERO, call.getOperandList());
+          return cx.convertExpression(newCall);
         });
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java b/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java
index 7d9bf1e..9deb7e0 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java
@@ -87,18 +87,14 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mappings;
 import org.apache.calcite.util.trace.CalciteTrace;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.ImmutableSortedMap;
 import com.google.common.collect.ImmutableSortedSet;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
-import com.google.common.collect.Multimaps;
+import com.google.common.collect.MultimapBuilder;
 import com.google.common.collect.Sets;
 import com.google.common.collect.SortedSetMultimap;
 
@@ -119,7 +115,6 @@ import java.util.Objects;
 import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
-import java.util.TreeSet;
 import javax.annotation.Nonnull;
 
 /**
@@ -165,7 +160,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
    * positions. This is from the view point of the parent rel of a new rel. */
   private final Map<RelNode, Frame> map = new HashMap<>();
 
-  private final HashSet<LogicalCorrelate> generatedCorRels = Sets.newHashSet();
+  private final HashSet<LogicalCorrelate> generatedCorRels = new HashSet<>();
 
   //~ Constructors -----------------------------------------------------------
 
@@ -282,26 +277,24 @@ public class RelDecorrelator implements ReflectiveVisitor {
   }
 
   private Function2<RelNode, RelNode, Void> createCopyHook() {
-    return new Function2<RelNode, RelNode, Void>() {
-      public Void apply(RelNode oldNode, RelNode newNode) {
-        if (cm.mapRefRelToCorRef.containsKey(oldNode)) {
-          cm.mapRefRelToCorRef.putAll(newNode,
-              cm.mapRefRelToCorRef.get(oldNode));
+    return (oldNode, newNode) -> {
+      if (cm.mapRefRelToCorRef.containsKey(oldNode)) {
+        cm.mapRefRelToCorRef.putAll(newNode,
+            cm.mapRefRelToCorRef.get(oldNode));
+      }
+      if (oldNode instanceof LogicalCorrelate
+          && newNode instanceof LogicalCorrelate) {
+        LogicalCorrelate oldCor = (LogicalCorrelate) oldNode;
+        CorrelationId c = oldCor.getCorrelationId();
+        if (cm.mapCorToCorRel.get(c) == oldNode) {
+          cm.mapCorToCorRel.put(c, newNode);
         }
-        if (oldNode instanceof LogicalCorrelate
-            && newNode instanceof LogicalCorrelate) {
-          LogicalCorrelate oldCor = (LogicalCorrelate) oldNode;
-          CorrelationId c = oldCor.getCorrelationId();
-          if (cm.mapCorToCorRel.get(c) == oldNode) {
-            cm.mapCorToCorRel.put(c, newNode);
-          }
 
-          if (generatedCorRels.contains(oldNode)) {
-            generatedCorRels.add((LogicalCorrelate) newNode);
-          }
+        if (generatedCorRels.contains(oldNode)) {
+          generatedCorRels.add((LogicalCorrelate) newNode);
         }
-        return null;
       }
+      return null;
     };
   }
 
@@ -342,7 +335,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       boolean projectPulledAboveLeftCorrelator) {
     RemoveCorrelationRexShuttle shuttle =
         new RemoveCorrelationRexShuttle(relBuilder.getRexBuilder(),
-            projectPulledAboveLeftCorrelator, null, ImmutableSet.<Integer>of());
+            projectPulledAboveLeftCorrelator, null, ImmutableSet.of());
     return exp.accept(shuttle);
   }
 
@@ -353,7 +346,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
     RemoveCorrelationRexShuttle shuttle =
         new RemoveCorrelationRexShuttle(relBuilder.getRexBuilder(),
             projectPulledAboveLeftCorrelator, nullIndicator,
-            ImmutableSet.<Integer>of());
+            ImmutableSet.of());
     return exp.accept(shuttle);
   }
 
@@ -373,7 +366,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     if (rel.getInputs().size() > 0) {
       List<RelNode> oldInputs = rel.getInputs();
-      List<RelNode> newInputs = Lists.newArrayList();
+      List<RelNode> newInputs = new ArrayList<>();
       for (int i = 0; i < oldInputs.size(); ++i) {
         final Frame frame = getInvoke(oldInputs.get(i), rel);
         if (frame == null || !frame.corDefOutputs.isEmpty()) {
@@ -393,7 +386,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
     // the output position should not change since there are no corVars
     // coming from below.
     return register(rel, newRel, identityMap(rel.getRowType().getFieldCount()),
-        ImmutableSortedMap.<CorDef, Integer>of());
+        ImmutableSortedMap.of());
   }
 
   /**
@@ -485,7 +478,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     // Project projects the original expressions,
     // plus any correlated variables the input wants to pass along.
-    final List<Pair<RexNode, String>> projects = Lists.newArrayList();
+    final List<Pair<RexNode, String>> projects = new ArrayList<>();
 
     List<RelDataTypeField> newInputOutput =
         newInput.getRowType().getFieldList();
@@ -554,7 +547,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
     // oldInput ----> newProject
     //                   |
     //                newInput
-    Map<Integer, Integer> combinedMap = Maps.newHashMap();
+    Map<Integer, Integer> combinedMap = new HashMap<>();
 
     for (Integer oldInputPos : frame.oldToNewOutputs.keySet()) {
       combinedMap.put(oldInputPos,
@@ -566,7 +559,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     // now it's time to rewrite the Aggregate
     final ImmutableBitSet newGroupSet = ImmutableBitSet.range(newGroupKeyCount);
-    List<AggregateCall> newAggCalls = Lists.newArrayList();
+    List<AggregateCall> newAggCalls = new ArrayList<>();
     List<AggregateCall> oldAggCalls = rel.getAggCallList();
 
     int oldInputOutputFieldCount = rel.getGroupSet().cardinality();
@@ -577,7 +570,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       ++i;
       List<Integer> oldAggArgs = oldAggCall.getArgList();
 
-      List<Integer> aggArgs = Lists.newArrayList();
+      List<Integer> aggArgs = new ArrayList<>();
 
       // Adjust the Aggregate argument positions.
       // Note Aggregate does not change input ordering, so the input
@@ -662,7 +655,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     // Project projects the original expressions,
     // plus any correlated variables the input wants to pass along.
-    final List<Pair<RexNode, String>> projects = Lists.newArrayList();
+    final List<Pair<RexNode, String>> projects = new ArrayList<>();
 
     // If this Project has correlated reference, create value generator
     // and produce the correlated variables in the new output.
@@ -779,7 +772,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
           r =
               LogicalJoin.create(r, distinct,
                   cluster.getRexBuilder().makeLiteral(true),
-                  ImmutableSet.<CorrelationId>of(), JoinRelType.INNER);
+                  ImmutableSet.of(), JoinRelType.INNER);
         }
       }
     }
@@ -818,7 +811,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
   private Frame getFrame(RelNode r, boolean safe) {
     final Frame frame = map.get(r);
     if (frame == null && safe) {
-      return new Frame(r, r, ImmutableSortedMap.<CorDef, Integer>of(),
+      return new Frame(r, r, ImmutableSortedMap.of(),
           identityMap(r.getRowType().getFieldCount()));
     }
     return frame;
@@ -926,7 +919,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     RelNode join =
         LogicalJoin.create(frame.r, valueGen, relBuilder.literal(true),
-            ImmutableSet.<CorrelationId>of(), JoinRelType.INNER);
+            ImmutableSet.of(), JoinRelType.INNER);
 
     // Join or Filter does not change the old input ordering. All
     // input fields from newLeftInput (i.e. the original input to the old
@@ -1145,7 +1138,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
             false);
     RelNode newJoin =
         LogicalJoin.create(leftFrame.r, rightFrame.r, condition,
-            ImmutableSet.<CorrelationId>of(), rel.getJoinType().toJoinType());
+            ImmutableSet.of(), rel.getJoinType().toJoinType());
 
     return register(rel, newJoin, mapOldToNewOutputs, corDefOutputs);
   }
@@ -1177,11 +1170,11 @@ public class RelDecorrelator implements ReflectiveVisitor {
     final RelNode newJoin =
         LogicalJoin.create(leftFrame.r, rightFrame.r,
             decorrelateExpr(currentRel, map, cm, rel.getCondition()),
-            ImmutableSet.<CorrelationId>of(), rel.getJoinType());
+            ImmutableSet.of(), rel.getJoinType());
 
     // Create the mapping between the output of the old correlation rel
     // and the new join rel
-    Map<Integer, Integer> mapOldToNewOutputs = Maps.newHashMap();
+    Map<Integer, Integer> mapOldToNewOutputs = new HashMap<>();
 
     int oldLeftFieldCount = oldLeft.getRowType().getFieldCount();
     int newLeftFieldCount = leftFrame.r.getRowType().getFieldCount();
@@ -1281,7 +1274,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
                 true));
 
     // now create the new project
-    List<Pair<RexNode, String>> newProjExprs = Lists.newArrayList();
+    List<Pair<RexNode, String>> newProjExprs = new ArrayList<>();
 
     // project everything from the LHS and then those from the original
     // projRel
@@ -1331,7 +1324,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
     final JoinRelType joinType = correlate.getJoinType().toJoinType();
 
     // now create the new project
-    final List<Pair<RexNode, String>> newProjects = Lists.newArrayList();
+    final List<Pair<RexNode, String>> newProjects = new ArrayList<>();
 
     // Project everything from the LHS and then those from the original
     // project
@@ -1441,7 +1434,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       List<Pair<RexNode, String>> additionalExprs) {
     final List<RelDataTypeField> fieldList =
         input.getRowType().getFieldList();
-    List<Pair<RexNode, String>> projects = Lists.newArrayList();
+    List<Pair<RexNode, String>> projects = new ArrayList<>();
     for (Ord<RelDataTypeField> field : Ord.zip(fieldList)) {
       projects.add(
           Pair.of(
@@ -1502,9 +1495,9 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     private DecorrelateRexShuttle(RelNode currentRel,
         Map<RelNode, Frame> map, CorelMap cm) {
-      this.currentRel = Preconditions.checkNotNull(currentRel);
-      this.map = Preconditions.checkNotNull(map);
-      this.cm = Preconditions.checkNotNull(cm);
+      this.currentRel = Objects.requireNonNull(currentRel);
+      this.map = Objects.requireNonNull(map);
+      this.cm = Objects.requireNonNull(cm);
     }
 
     @Override public RexNode visitFieldAccess(RexFieldAccess fieldAccess) {
@@ -1886,8 +1879,8 @@ public class RelDecorrelator implements ReflectiveVisitor {
         // filterInput) and correlatedJoinKeys. correlatedJoinKeys
         // can be expressions, while rightJoinKeys need to be input
         // refs. These comparisons are AND'ed together.
-        List<RexNode> tmpRightJoinKeys = Lists.newArrayList();
-        List<RexNode> correlatedJoinKeys = Lists.newArrayList();
+        List<RexNode> tmpRightJoinKeys = new ArrayList<>();
+        List<RexNode> correlatedJoinKeys = new ArrayList<>();
         RelOptUtil.splitCorrelatedFilterCondition(
             filter,
             tmpRightJoinKeys,
@@ -1985,7 +1978,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       // make the new join rel
       LogicalJoin join =
           LogicalJoin.create(left, right, joinCond,
-              ImmutableSet.<CorrelationId>of(), joinType);
+              ImmutableSet.of(), joinType);
 
       RelNode newProject =
           projectJoinOutputWithNullability(join, project, nullIndicatorPos);
@@ -2004,7 +1997,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
           operand(LogicalCorrelate.class,
               operand(RelNode.class, any()),
               operand(LogicalProject.class,
-                  operand(LogicalAggregate.class, null, Aggregate.IS_SIMPLE,
+                  operandJ(LogicalAggregate.class, null, Aggregate::isSimple,
                       operand(LogicalProject.class,
                           operand(RelNode.class, any()))))),
           relBuilderFactory, null);
@@ -2057,7 +2050,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       final List<RexNode> aggInputProjects = aggInputProject.getProjects();
 
       final List<AggregateCall> aggCalls = aggregate.getAggCallList();
-      final Set<Integer> isCountStar = Sets.newHashSet();
+      final Set<Integer> isCountStar = new HashSet<>();
 
       // mark if agg produces count(*) which needs to reference the
       // nullIndicator after the transformation.
@@ -2095,8 +2088,8 @@ public class RelDecorrelator implements ReflectiveVisitor {
         // filterInput) and correlatedJoinKeys. correlatedJoinKeys
         // can only be RexFieldAccess, while rightJoinKeys can be
         // expressions. These comparisons are AND'ed together.
-        List<RexNode> rightJoinKeys = Lists.newArrayList();
-        List<RexNode> tmpCorrelatedJoinKeys = Lists.newArrayList();
+        List<RexNode> rightJoinKeys = new ArrayList<>();
+        List<RexNode> tmpCorrelatedJoinKeys = new ArrayList<>();
         RelOptUtil.splitCorrelatedFilterCondition(
             filter,
             rightJoinKeys,
@@ -2106,8 +2099,8 @@ public class RelDecorrelator implements ReflectiveVisitor {
         // make sure the correlated reference forms a unique key check
         // that the columns referenced in these comparisons form an
         // unique key of the leftInput
-        List<RexFieldAccess> correlatedJoinKeys = Lists.newArrayList();
-        List<RexInputRef> correlatedInputRefJoinKeys = Lists.newArrayList();
+        List<RexFieldAccess> correlatedJoinKeys = new ArrayList<>();
+        List<RexInputRef> correlatedInputRefJoinKeys = new ArrayList<>();
         for (RexNode joinKey : tmpCorrelatedJoinKeys) {
           assert joinKey instanceof RexFieldAccess;
           correlatedJoinKeys.add((RexFieldAccess) joinKey);
@@ -2261,12 +2254,12 @@ public class RelDecorrelator implements ReflectiveVisitor {
       right =
           createProjectWithAdditionalExprs(right,
               ImmutableList.of(
-                  Pair.<RexNode, String>of(rexBuilder.makeLiteral(true),
+                  Pair.of(rexBuilder.makeLiteral(true),
                       "nullIndicator")));
 
       LogicalJoin join =
           LogicalJoin.create(left, right, joinCond,
-              ImmutableSet.<CorrelationId>of(), joinType);
+              ImmutableSet.of(), joinType);
 
       // To the consumer of joinOutputProjRel, nullIndicator is located
       // at the end
@@ -2281,7 +2274,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
                   true));
 
       // first project all group-by keys plus the transformed agg input
-      List<RexNode> joinOutputProjects = Lists.newArrayList();
+      List<RexNode> joinOutputProjects = new ArrayList<>();
 
       // LOJ Join preserves LHS types
       for (int i = 0; i < leftInputFieldCount; i++) {
@@ -2310,7 +2303,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
       final int groupCount = leftInputFieldCount;
 
-      List<AggregateCall> newAggCalls = Lists.newArrayList();
+      List<AggregateCall> newAggCalls = new ArrayList<>();
       k = -1;
       for (AggregateCall aggCall : aggCalls) {
         ++k;
@@ -2321,7 +2314,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
           // the null indicator is located at the end
           argList = Collections.singletonList(nullIndicatorPos);
         } else {
-          argList = Lists.newArrayList();
+          argList = new ArrayList<>();
 
           for (int aggArg : aggCall.getArgList()) {
             argList.add(aggArg + groupCount);
@@ -2340,7 +2333,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       LogicalAggregate newAggregate =
           LogicalAggregate.create(joinOutputProject, groupSet, null,
               newAggCalls);
-      List<RexNode> newAggOutputProjectList = Lists.newArrayList();
+      List<RexNode> newAggOutputProjectList = new ArrayList<>();
       for (int i : groupSet) {
         newAggOutputProjectList.add(
             rexBuilder.makeInputRef(newAggregate, i));
@@ -2402,7 +2395,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
         aggregate = call.rel(2);
 
         // Create identity projection
-        final List<Pair<RexNode, String>> projects = Lists.newArrayList();
+        final List<Pair<RexNode, String>> projects = new ArrayList<>();
         final List<RelDataTypeField> fields =
             aggregate.getRowType().getFieldList();
         for (int i = 0; i < fields.size(); i++) {
@@ -2460,7 +2453,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
       }
 
       List<AggregateCall> aggCalls = aggregate.getAggCallList();
-      Set<Integer> isCount = Sets.newHashSet();
+      Set<Integer> isCount = new HashSet<>();
 
       // remember the count() positions
       int i = -1;
@@ -2670,14 +2663,9 @@ public class RelDecorrelator implements ReflectiveVisitor {
         new TreeMap<>();
 
     final SortedSetMultimap<RelNode, CorRef> mapRefRelToCorRef =
-        Multimaps.newSortedSetMultimap(
-            new HashMap<RelNode, Collection<CorRef>>(),
-            new Supplier<TreeSet<CorRef>>() {
-              public TreeSet<CorRef> get() {
-                Bug.upgrade("use MultimapBuilder when we're on Guava-16");
-                return Sets.newTreeSet();
-              }
-            });
+        MultimapBuilder.SortedSetMultimapBuilder.hashKeys()
+            .treeSetValues()
+            .build();
 
     final Map<RexFieldAccess, CorRef> mapFieldAccessToCorVar = new HashMap<>();
 
@@ -2788,7 +2776,7 @@ public class RelDecorrelator implements ReflectiveVisitor {
 
     Frame(RelNode oldRel, RelNode r, SortedMap<CorDef, Integer> corDefOutputs,
         Map<Integer, Integer> oldToNewOutputs) {
-      this.r = Preconditions.checkNotNull(r);
+      this.r = Objects.requireNonNull(r);
       this.corDefOutputs = ImmutableSortedMap.copyOf(corDefOutputs);
       this.oldToNewOutputs = ImmutableSortedMap.copyOf(oldToNewOutputs);
       assert allLessThan(this.corDefOutputs.values(),

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql2rel/RelFieldTrimmer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/RelFieldTrimmer.java b/core/src/main/java/org/apache/calcite/sql2rel/RelFieldTrimmer.java
index db6588f..733ee02 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/RelFieldTrimmer.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/RelFieldTrimmer.java
@@ -65,7 +65,6 @@ import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.MappingType;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
@@ -613,7 +612,7 @@ public class RelFieldTrimmer implements ReflectiveVisitor {
       // on-demand fields.
       Set<RelDataTypeField> inputExtraFields =
           RelDataTypeImpl.extra(inputRowType) == null
-              ? Collections.<RelDataTypeField>emptySet()
+              ? Collections.emptySet()
               : combinedInputExtraFields;
       inputExtraFieldCounts.add(inputExtraFields.size());
       TrimResult trimResult =
@@ -848,11 +847,7 @@ public class RelFieldTrimmer implements ReflectiveVisitor {
     final ImmutableList<ImmutableBitSet> newGroupSets =
         ImmutableList.copyOf(
             Iterables.transform(aggregate.getGroupSets(),
-                new Function<ImmutableBitSet, ImmutableBitSet>() {
-                  public ImmutableBitSet apply(ImmutableBitSet input) {
-                    return Mappings.apply(inputMapping, input);
-                  }
-                }));
+                input1 -> Mappings.apply(inputMapping, input1)));
 
     // Populate mapping of where to find the fields. System, group key and
     // indicator fields first.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql2rel/RelStructuredTypeFlattener.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/RelStructuredTypeFlattener.java b/core/src/main/java/org/apache/calcite/sql2rel/RelStructuredTypeFlattener.java
index ae830a5..ff41b16 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/RelStructuredTypeFlattener.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/RelStructuredTypeFlattener.java
@@ -74,13 +74,13 @@ import org.apache.calcite.util.ReflectiveVisitor;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import com.google.common.collect.SortedSetMultimap;
 
+import java.util.ArrayList;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.SortedMap;
@@ -131,7 +131,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
   private final RexBuilder rexBuilder;
   private final boolean restructure;
 
-  private final Map<RelNode, RelNode> oldToNewRelMap = Maps.newHashMap();
+  private final Map<RelNode, RelNode> oldToNewRelMap = new HashMap<>();
   private RelNode currentRel;
   private int iRestructureInput;
   private RelDataType flattenedRootType;
@@ -215,7 +215,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
   }
 
   private List<RexNode> restructureFields(RelDataType structuredType) {
-    final List<RexNode> structuringExps = Lists.newArrayList();
+    final List<RexNode> structuringExps = new ArrayList<>();
     for (RelDataTypeField field : structuredType.getFieldList()) {
       // TODO:  row
       if (field.getType().getSqlTypeName() == SqlTypeName.STRUCTURED) {
@@ -324,11 +324,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
   private Mappings.TargetMapping getNewForOldInputMapping(RelNode oldRel) {
     final RelNode newRel = getNewForOldRel(oldRel);
     return Mappings.target(
-        new Function<Integer, Integer>() {
-          public Integer apply(Integer oldInput) {
-            return getNewForOldInput(oldInput);
-          }
-        },
+        this::getNewForOldInput,
         oldRel.getRowType().getFieldCount(),
         newRel.getRowType().getFieldCount());
   }
@@ -481,7 +477,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
   }
 
   public void rewriteRel(LogicalProject rel) {
-    final List<Pair<RexNode, String>> flattenedExpList = Lists.newArrayList();
+    final List<Pair<RexNode, String>> flattenedExpList = new ArrayList<>();
     flattenProjections(new RewriteRexShuttle(),
         rel.getProjects(),
         rel.getRowType().getFieldNames(),
@@ -511,7 +507,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
     }
 
     // Convert the projections.
-    final List<Pair<RexNode, String>> flattenedExpList = Lists.newArrayList();
+    final List<Pair<RexNode, String>> flattenedExpList = new ArrayList<>();
     List<String> fieldNames = rel.getRowType().getFieldNames();
     flattenProjections(new RewriteRexShuttle(),
         program.getProjectList(),
@@ -593,7 +589,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
         for (int j = 0; j < n; ++j) {
           RelDataTypeField field = fieldList.get(j);
           flattenedExps.add(
-              Pair.<RexNode, String>of(
+              Pair.of(
                   new RexInputRef(newOffset + j, field.getType()),
                   fieldName));
         }
@@ -605,7 +601,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
           // For object constructors, prepend a FALSE null
           // indicator.
           flattenedExps.add(
-              Pair.<RexNode, String>of(rexBuilder.makeLiteral(false),
+              Pair.of(rexBuilder.makeLiteral(false),
                   fieldName));
         } else if (exp.isA(SqlKind.CAST)) {
           if (RexLiteral.isNullLiteral(
@@ -620,7 +616,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
         }
         flattenProjections(new RewriteRexShuttle(),
             call.getOperands(),
-            Collections.<String>nCopies(call.getOperands().size(), null),
+            Collections.nCopies(call.getOperands().size(), null),
             fieldName,
             flattenedExps);
       } else if (exp instanceof RexCall) {
@@ -677,7 +673,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
   public void rewriteRel(TableScan rel) {
     RelNode newRel = rel.getTable().toRel(toRelContext);
     if (!SqlTypeUtil.isFlat(rel.getRowType())) {
-      final List<Pair<RexNode, String>> flattenedExpList = Lists.newArrayList();
+      final List<Pair<RexNode, String>> flattenedExpList = new ArrayList<>();
       flattenInputs(rel.getRowType().getFieldList(),
           rexBuilder.makeRangeReference(newRel),
           flattenedExpList);
@@ -861,7 +857,7 @@ public class RelStructuredTypeFlattener implements ReflectiveVisitor {
         RexBuilder rexBuilder,
         SqlOperator op,
         List<RexNode> exprs) {
-      final List<Pair<RexNode, String>> flattenedExps = Lists.newArrayList();
+      final List<Pair<RexNode, String>> flattenedExps = new ArrayList<>();
       flattenProjections(this, exprs, null, "", flattenedExps);
       int n = flattenedExps.size() / 2;
       boolean negate = false;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java b/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
index 3767e30..0d61247 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
@@ -170,16 +170,12 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableList.Builder;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
 import org.slf4j.Logger;
 
@@ -197,8 +193,10 @@ import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.TreeSet;
+import java.util.function.Supplier;
 
 import static org.apache.calcite.sql.SqlUtil.stripAs;
 
@@ -317,7 +315,7 @@ public class SqlToRelConverter {
     this.subQueryConverter = new NoOpSubQueryConverter();
     this.rexBuilder = cluster.getRexBuilder();
     this.typeFactory = rexBuilder.getTypeFactory();
-    this.cluster = Preconditions.checkNotNull(cluster);
+    this.cluster = Objects.requireNonNull(cluster);
     this.exprConverter = new SqlNodeToRexConverterImpl(convertletTable);
     this.explainParamCount = 0;
     this.config = new ConfigBuilder().withConfig(config).build();
@@ -717,9 +715,9 @@ public class SqlToRelConverter {
         return;
       }
 
-      final Map<Integer, Integer> squished = Maps.newHashMap();
+      final Map<Integer, Integer> squished = new HashMap<>();
       final List<RelDataTypeField> fields = rel.getRowType().getFieldList();
-      final List<Pair<RexNode, String>> newProjects = Lists.newArrayList();
+      final List<Pair<RexNode, String>> newProjects = new ArrayList<>();
       for (int i = 0; i < fields.size(); i++) {
         if (origins.get(i) == i) {
           squished.put(i, newProjects.size());
@@ -735,7 +733,7 @@ public class SqlToRelConverter {
 
       // Create the expressions to reverse the mapping.
       // Project($0, $1, $0, $2).
-      final List<Pair<RexNode, String>> undoProjects = Lists.newArrayList();
+      final List<Pair<RexNode, String>> undoProjects = new ArrayList<>();
       for (int i = 0; i < fields.size(); i++) {
         final int origin = origins.get(i);
         RelDataTypeField field = fields.get(i);
@@ -761,7 +759,7 @@ public class SqlToRelConverter {
     final ImmutableBitSet groupSet =
         ImmutableBitSet.range(rel.getRowType().getFieldCount());
     rel = createAggregate(bb, groupSet, ImmutableList.of(groupSet),
-        ImmutableList.<AggregateCall>of());
+        ImmutableList.of());
 
     bb.setRoot(
         rel,
@@ -1037,7 +1035,7 @@ public class SqlToRelConverter {
       final List<RexNode> leftKeys;
       switch (leftKeyNode.getKind()) {
       case ROW:
-        leftKeys = Lists.newArrayList();
+        leftKeys = new ArrayList<>();
         for (SqlNode sqlExpr : ((SqlBasicCall) leftKeyNode).getOperandList()) {
           leftKeys.add(bb.convertExpression(sqlExpr));
         }
@@ -1107,12 +1105,12 @@ public class SqlToRelConverter {
             LogicalAggregate.create(seek, ImmutableBitSet.of(), null,
                 ImmutableList.of(
                     AggregateCall.create(SqlStdOperatorTable.COUNT, false,
-                        false, ImmutableList.<Integer>of(), -1, longType, null),
+                        false, ImmutableList.of(), -1, longType, null),
                     AggregateCall.create(SqlStdOperatorTable.COUNT, false,
                         false, args, -1, longType, null)));
         LogicalJoin join =
             LogicalJoin.create(bb.root, aggregate, rexBuilder.makeLiteral(true),
-                ImmutableSet.<CorrelationId>of(), JoinRelType.INNER);
+                ImmutableSet.of(), JoinRelType.INNER);
         bb.setRoot(join, false);
       }
       final RexNode rex =
@@ -1426,14 +1424,9 @@ public class SqlToRelConverter {
                 rexBuilder,
                 Iterables.transform(
                     Pair.zip(leftKeys, call.getOperandList()),
-                    new Function<Pair<RexNode, SqlNode>, RexNode>() {
-                      public RexNode apply(Pair<RexNode, SqlNode> pair) {
-                        return rexBuilder.makeCall(comparisonOp,
-                            pair.left,
-                            ensureSqlType(pair.left.getType(),
-                                bb.convertExpression(pair.right)));
-                      }
-                    }),
+                    pair -> rexBuilder.makeCall(comparisonOp, pair.left,
+                        ensureSqlType(pair.left.getType(),
+                            bb.convertExpression(pair.right)))),
                 false);
       }
       comparisons.add(rexComparison);
@@ -2169,7 +2162,7 @@ public class SqlToRelConverter {
         new SqlBasicVisitor<RexNode>() {
           @Override public RexNode visit(SqlCall call) {
             List<SqlNode> operands = call.getOperandList();
-            List<RexNode> newOperands = Lists.newArrayList();
+            List<RexNode> newOperands = new ArrayList<>();
             for (SqlNode node : operands) {
               newOperands.add(node.accept(this));
             }
@@ -2201,7 +2194,7 @@ public class SqlToRelConverter {
 
     // convert subset
     final SqlNodeList subsets = matchRecognize.getSubsetList();
-    final Map<String, TreeSet<String>> subsetMap = Maps.newHashMap();
+    final Map<String, TreeSet<String>> subsetMap = new HashMap<>();
     for (SqlNode node : subsets) {
       List<SqlNode> operands = ((SqlCall) node).getOperandList();
       SqlIdentifier left = (SqlIdentifier) operands.get(0);
@@ -2411,7 +2404,7 @@ public class SqlToRelConverter {
 
     final Join originalJoin =
         (Join) RelFactories.DEFAULT_JOIN_FACTORY.createJoin(leftRel, rightRel,
-            joinCond, ImmutableSet.<CorrelationId>of(), joinType, false);
+            joinCond, ImmutableSet.of(), joinType, false);
 
     return RelOptUtil.pushDownJoinConditions(originalJoin, relBuilder);
   }
@@ -2423,7 +2416,7 @@ public class SqlToRelConverter {
       return null;
     }
     final ImmutableBitSet.Builder requiredColumns = ImmutableBitSet.builder();
-    final List<CorrelationId> correlNames = Lists.newArrayList();
+    final List<CorrelationId> correlNames = new ArrayList<>();
 
     // All correlations must refer the same namespace since correlation
     // produces exactly one correlation source.
@@ -2628,7 +2621,7 @@ public class SqlToRelConverter {
       SqlValidatorNamespace rightNamespace,
       List<String> nameList) {
     final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
-    final List<RexNode> list = Lists.newArrayList();
+    final List<RexNode> list = new ArrayList<>();
     for (String name : nameList) {
       List<RexNode> operands = new ArrayList<>();
       int offset = 0;
@@ -2739,7 +2732,7 @@ public class SqlToRelConverter {
     }
 
     final RexNode havingExpr;
-    final List<Pair<RexNode, String>> projects = Lists.newArrayList();
+    final List<Pair<RexNode, String>> projects = new ArrayList<>();
 
     try {
       Preconditions.checkArgument(bb.agg == null, "already in agg mode");
@@ -3222,12 +3215,10 @@ public class SqlToRelConverter {
             NullInitializerExpressionFactory.INSTANCE);
 
     // Lazily create a blackboard that contains all non-generated columns.
-    final Supplier<Blackboard> bb = new Supplier<Blackboard>() {
-      public Blackboard get() {
-        RexNode sourceRef = rexBuilder.makeRangeReference(scan);
-        return createInsertBlackboard(table, sourceRef,
-            table.getRowType().getFieldNames());
-      }
+    final Supplier<Blackboard> bb = () -> {
+      RexNode sourceRef = rexBuilder.makeRangeReference(scan);
+      return createInsertBlackboard(table, sourceRef,
+          table.getRowType().getFieldNames());
     };
 
     int virtualCount = 0;
@@ -3293,10 +3284,10 @@ public class SqlToRelConverter {
     final List<RelDataTypeField> targetFields = targetRowType.getFieldList();
     final List<RexNode> sourceExps =
         new ArrayList<>(
-            Collections.<RexNode>nCopies(targetFields.size(), null));
+            Collections.nCopies(targetFields.size(), null));
     final List<String> fieldNames =
         new ArrayList<>(
-            Collections.<String>nCopies(targetFields.size(), null));
+            Collections.nCopies(targetFields.size(), null));
 
     final InitializerExpressionFactory initializerFactory =
         getInitializerFactory(validator.getNamespace(call).getTable());
@@ -3313,12 +3304,8 @@ public class SqlToRelConverter {
     }
 
     // Lazily create a blackboard that contains all non-generated columns.
-    final Supplier<Blackboard> bb = new Supplier<Blackboard>() {
-      public Blackboard get() {
-        return createInsertBlackboard(targetTable, sourceRef,
-            targetColumnNames);
-      }
-    };
+    final Supplier<Blackboard> bb = () ->
+        createInsertBlackboard(targetTable, sourceRef, targetColumnNames);
 
     // Walk the expression list and get default values for any columns
     // that were not supplied in the statement. Get field names too.
@@ -3795,7 +3782,7 @@ public class SqlToRelConverter {
               ret,
               relNode,
               rexBuilder.makeLiteral(true),
-              ImmutableSet.<CorrelationId>of(),
+              ImmutableSet.of(),
               JoinRelType.INNER,
               false);
     }
@@ -4093,12 +4080,12 @@ public class SqlToRelConverter {
       final RexNode joinCond;
       final int origLeftInputCount = root.getRowType().getFieldCount();
       if (leftKeys != null) {
-        List<RexNode> newLeftInputExprs = Lists.newArrayList();
+        List<RexNode> newLeftInputExprs = new ArrayList<>();
         for (int i = 0; i < origLeftInputCount; i++) {
           newLeftInputExprs.add(rexBuilder.makeInputRef(root, i));
         }
 
-        final List<Integer> leftJoinKeys = Lists.newArrayList();
+        final List<Integer> leftJoinKeys = new ArrayList<>();
         for (RexNode leftKey : leftKeys) {
           int index = newLeftInputExprs.indexOf(leftKey);
           if (index < 0 || joinType == JoinRelType.LEFT) {
@@ -4307,7 +4294,7 @@ public class SqlToRelConverter {
           }
           final RexNode c =
               rexBuilder.makeCorrel(builder.uniquify().build(), correlId);
-          return Pair.<RexNode, Map<String, Integer>>of(c, fields.build());
+          return Pair.of(c, fields.build());
         }
       }
     }
@@ -4504,8 +4491,8 @@ public class SqlToRelConverter {
       case CURSOR:
       case IN:
       case NOT_IN:
-        subQuery = Preconditions.checkNotNull(getSubQuery(expr));
-        rex = Preconditions.checkNotNull(subQuery.expr);
+        subQuery = Objects.requireNonNull(getSubQuery(expr));
+        rex = Objects.requireNonNull(subQuery.expr);
         return StandardConvertletTable.castToValidatedType(expr, rex,
             validator, rexBuilder);
 
@@ -4552,7 +4539,7 @@ public class SqlToRelConverter {
 
       // Apply standard conversions.
       rex = expr.accept(this);
-      return Preconditions.checkNotNull(rex);
+      return Objects.requireNonNull(rex);
     }
 
     /**
@@ -4776,7 +4763,7 @@ public class SqlToRelConverter {
     private final Blackboard bb;
     public final AggregatingSelectScope aggregatingSelectScope;
 
-    private final Map<String, String> nameMap = Maps.newHashMap();
+    private final Map<String, String> nameMap = new HashMap<>();
 
     /**
      * The group-by expressions, in {@link SqlNode} format.
@@ -5246,7 +5233,7 @@ public class SqlToRelConverter {
                 rexBuilder.getTypeFactory(),
                 SqlStdOperatorTable.HISTOGRAM_AGG,
                 exprs,
-                ImmutableList.<RelCollation>of());
+                ImmutableList.of());
 
         RexNode over =
             rexBuilder.makeOver(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java b/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
index caf5d5d..5714806 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/StandardConvertletTable.java
@@ -19,7 +19,6 @@ package org.apache.calcite.sql2rel;
 import org.apache.calcite.avatica.util.DateTimeUtils;
 import org.apache.calcite.avatica.util.TimeUnit;
 import org.apache.calcite.plan.RelOptUtil;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeFamily;
@@ -96,63 +95,36 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
 
     // Register aliases (operators which have a different name but
     // identical behavior to other operators).
-    addAlias(
-        SqlStdOperatorTable.CHARACTER_LENGTH,
+    addAlias(SqlStdOperatorTable.CHARACTER_LENGTH,
         SqlStdOperatorTable.CHAR_LENGTH);
-    addAlias(
-        SqlStdOperatorTable.IS_UNKNOWN,
+    addAlias(SqlStdOperatorTable.IS_UNKNOWN,
         SqlStdOperatorTable.IS_NULL);
-    addAlias(
-        SqlStdOperatorTable.IS_NOT_UNKNOWN,
+    addAlias(SqlStdOperatorTable.IS_NOT_UNKNOWN,
         SqlStdOperatorTable.IS_NOT_NULL);
     addAlias(SqlStdOperatorTable.PERCENT_REMAINDER, SqlStdOperatorTable.MOD);
 
     // Register convertlets for specific objects.
-    registerOp(
-        SqlStdOperatorTable.CAST,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            return convertCast(cx, call);
-          }
-        });
-    registerOp(
-        SqlStdOperatorTable.IS_DISTINCT_FROM,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            return convertIsDistinctFrom(cx, call, false);
-          }
-        });
-    registerOp(
-        SqlStdOperatorTable.IS_NOT_DISTINCT_FROM,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            return convertIsDistinctFrom(cx, call, true);
-          }
-        });
+    registerOp(SqlStdOperatorTable.CAST, this::convertCast);
+    registerOp(SqlStdOperatorTable.IS_DISTINCT_FROM,
+        (cx, call) -> convertIsDistinctFrom(cx, call, false));
+    registerOp(SqlStdOperatorTable.IS_NOT_DISTINCT_FROM,
+        (cx, call) -> convertIsDistinctFrom(cx, call, true));
 
-    registerOp(
-        SqlStdOperatorTable.PLUS,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            return convertPlus(cx, call);
-          }
-        });
+    registerOp(SqlStdOperatorTable.PLUS, this::convertPlus);
 
     registerOp(SqlStdOperatorTable.MINUS,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            final RexCall e =
-                (RexCall) StandardConvertletTable.this.convertCall(cx, call,
-                    call.getOperator());
-            switch (e.getOperands().get(0).getType().getSqlTypeName()) {
-            case DATE:
-            case TIME:
-            case TIMESTAMP:
-              return convertDatetimeMinus(cx, SqlStdOperatorTable.MINUS_DATE,
-                  call);
-            default:
-              return e;
-            }
+        (cx, call) -> {
+          final RexCall e =
+              (RexCall) StandardConvertletTable.this.convertCall(cx, call,
+                  call.getOperator());
+          switch (e.getOperands().get(0).getType().getSqlTypeName()) {
+          case DATE:
+          case TIME:
+          case TIMESTAMP:
+            return convertDatetimeMinus(cx, SqlStdOperatorTable.MINUS_DATE,
+                call);
+          default:
+            return e;
           }
         });
 
@@ -165,121 +137,76 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
     registerOp(OracleSqlOperatorTable.LEAST, new GreatestConvertlet());
 
     registerOp(OracleSqlOperatorTable.NVL,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            final RexBuilder rexBuilder = cx.getRexBuilder();
-            final RexNode operand0 =
-                cx.convertExpression(call.getOperandList().get(0));
-            final RexNode operand1 =
-                cx.convertExpression(call.getOperandList().get(1));
-            final RelDataType type =
-                cx.getValidator().getValidatedNodeType(call);
-            return rexBuilder.makeCall(type, SqlStdOperatorTable.CASE,
-                ImmutableList.of(
-                    rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL,
-                        operand0),
-                    rexBuilder.makeCast(type, operand0),
-                    rexBuilder.makeCast(type, operand1)));
-          }
+        (cx, call) -> {
+          final RexBuilder rexBuilder = cx.getRexBuilder();
+          final RexNode operand0 =
+              cx.convertExpression(call.getOperandList().get(0));
+          final RexNode operand1 =
+              cx.convertExpression(call.getOperandList().get(1));
+          final RelDataType type =
+              cx.getValidator().getValidatedNodeType(call);
+          return rexBuilder.makeCall(type, SqlStdOperatorTable.CASE,
+              ImmutableList.of(
+                  rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL,
+                      operand0),
+                  rexBuilder.makeCast(type, operand0),
+                  rexBuilder.makeCast(type, operand1)));
         });
 
     registerOp(OracleSqlOperatorTable.DECODE,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            final RexBuilder rexBuilder = cx.getRexBuilder();
-            final List<RexNode> operands = convertExpressionList(cx,
-                call.getOperandList(), SqlOperandTypeChecker.Consistency.NONE);
-            final RelDataType type =
-                cx.getValidator().getValidatedNodeType(call);
-            final List<RexNode> exprs = new ArrayList<>();
-            for (int i = 1; i < operands.size() - 1; i += 2) {
-              exprs.add(
-                  RelOptUtil.isDistinctFrom(rexBuilder, operands.get(0),
-                      operands.get(i), true));
-              exprs.add(operands.get(i + 1));
-            }
-            if (operands.size() % 2 == 0) {
-              exprs.add(Util.last(operands));
-            } else {
-              exprs.add(rexBuilder.makeNullLiteral(type));
-            }
-            return rexBuilder.makeCall(type, SqlStdOperatorTable.CASE, exprs);
+        (cx, call) -> {
+          final RexBuilder rexBuilder = cx.getRexBuilder();
+          final List<RexNode> operands = convertExpressionList(cx,
+              call.getOperandList(), SqlOperandTypeChecker.Consistency.NONE);
+          final RelDataType type =
+              cx.getValidator().getValidatedNodeType(call);
+          final List<RexNode> exprs = new ArrayList<>();
+          for (int i = 1; i < operands.size() - 1; i += 2) {
+            exprs.add(
+                RelOptUtil.isDistinctFrom(rexBuilder, operands.get(0),
+                    operands.get(i), true));
+            exprs.add(operands.get(i + 1));
+          }
+          if (operands.size() % 2 == 0) {
+            exprs.add(Util.last(operands));
+          } else {
+            exprs.add(rexBuilder.makeNullLiteral(type));
           }
+          return rexBuilder.makeCall(type, SqlStdOperatorTable.CASE, exprs);
         });
 
     // Expand "x NOT LIKE y" into "NOT (x LIKE y)"
-    registerOp(
-        SqlStdOperatorTable.NOT_LIKE,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            final SqlCall expanded =
-                SqlStdOperatorTable.NOT.createCall(
-                    SqlParserPos.ZERO,
-                    SqlStdOperatorTable.LIKE.createCall(
-                        SqlParserPos.ZERO,
-                        call.getOperandList()));
-            return cx.convertExpression(expanded);
-          }
-        });
+    registerOp(SqlStdOperatorTable.NOT_LIKE,
+        (cx, call) -> cx.convertExpression(
+            SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO,
+                SqlStdOperatorTable.LIKE.createCall(SqlParserPos.ZERO,
+                    call.getOperandList()))));
 
     // Expand "x NOT SIMILAR y" into "NOT (x SIMILAR y)"
-    registerOp(
-        SqlStdOperatorTable.NOT_SIMILAR_TO,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            final SqlCall expanded =
-                SqlStdOperatorTable.NOT.createCall(
-                    SqlParserPos.ZERO,
-                    SqlStdOperatorTable.SIMILAR_TO.createCall(
-                        SqlParserPos.ZERO,
-                        call.getOperandList()));
-            return cx.convertExpression(expanded);
-          }
-        });
+    registerOp(SqlStdOperatorTable.NOT_SIMILAR_TO,
+        (cx, call) -> cx.convertExpression(
+            SqlStdOperatorTable.NOT.createCall(SqlParserPos.ZERO,
+                SqlStdOperatorTable.SIMILAR_TO.createCall(SqlParserPos.ZERO,
+                    call.getOperandList()))));
 
     // Unary "+" has no effect, so expand "+ x" into "x".
-    registerOp(
-        SqlStdOperatorTable.UNARY_PLUS,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            SqlNode expanded = call.operand(0);
-            return cx.convertExpression(expanded);
-          }
-        });
+    registerOp(SqlStdOperatorTable.UNARY_PLUS,
+        (cx, call) -> cx.convertExpression(call.operand(0)));
 
     // "DOT"
-    registerOp(
-        SqlStdOperatorTable.DOT,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            return cx.getRexBuilder().makeCall(SqlStdOperatorTable.DOT,
-                cx.convertExpression(call.operand(0)),
-                cx.getRexBuilder().makeLiteral(call.operand(1).toString()));
-          }
-        });
+    registerOp(SqlStdOperatorTable.DOT,
+        (cx, call) -> cx.getRexBuilder().makeCall(SqlStdOperatorTable.DOT,
+            cx.convertExpression(call.operand(0)),
+            cx.getRexBuilder().makeLiteral(call.operand(1).toString())));
     // "AS" has no effect, so expand "x AS id" into "x".
-    registerOp(
-        SqlStdOperatorTable.AS,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            SqlNode expanded = call.operand(0);
-            return cx.convertExpression(expanded);
-          }
-        });
+    registerOp(SqlStdOperatorTable.AS,
+        (cx, call) -> cx.convertExpression(call.operand(0)));
     // "SQRT(x)" is equivalent to "POWER(x, .5)"
-    registerOp(
-        SqlStdOperatorTable.SQRT,
-        new SqlRexConvertlet() {
-          public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-            SqlNode expanded =
-                SqlStdOperatorTable.POWER.createCall(
-                    SqlParserPos.ZERO,
-                    call.operand(0),
-                    SqlLiteral.createExactNumeric(
-                        "0.5", SqlParserPos.ZERO));
-            return cx.convertExpression(expanded);
-          }
-        });
+    registerOp(SqlStdOperatorTable.SQRT,
+        (cx, call) -> cx.convertExpression(
+            SqlStdOperatorTable.POWER.createCall(SqlParserPos.ZERO,
+                call.operand(0),
+                SqlLiteral.createExactNumeric("0.5", SqlParserPos.ZERO))));
 
     // REVIEW jvs 24-Apr-2006: This only seems to be working from within a
     // windowed agg.  I have added an optimizer rule
@@ -297,26 +224,19 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
     // different types, say BIGINT.
     //
     // Similarly STDDEV_POP and STDDEV_SAMP, VAR_POP and VAR_SAMP.
-    registerOp(
-        SqlStdOperatorTable.AVG,
+    registerOp(SqlStdOperatorTable.AVG,
         new AvgVarianceConvertlet(SqlKind.AVG));
-    registerOp(
-        SqlStdOperatorTable.STDDEV_POP,
+    registerOp(SqlStdOperatorTable.STDDEV_POP,
         new AvgVarianceConvertlet(SqlKind.STDDEV_POP));
-    registerOp(
-        SqlStdOperatorTable.STDDEV_SAMP,
+    registerOp(SqlStdOperatorTable.STDDEV_SAMP,
         new AvgVarianceConvertlet(SqlKind.STDDEV_SAMP));
-    registerOp(
-        SqlStdOperatorTable.STDDEV,
+    registerOp(SqlStdOperatorTable.STDDEV,
         new AvgVarianceConvertlet(SqlKind.STDDEV_SAMP));
-    registerOp(
-        SqlStdOperatorTable.VAR_POP,
+    registerOp(SqlStdOperatorTable.VAR_POP,
         new AvgVarianceConvertlet(SqlKind.VAR_POP));
-    registerOp(
-        SqlStdOperatorTable.VAR_SAMP,
+    registerOp(SqlStdOperatorTable.VAR_SAMP,
         new AvgVarianceConvertlet(SqlKind.VAR_SAMP));
-    registerOp(
-        SqlStdOperatorTable.VARIANCE,
+    registerOp(SqlStdOperatorTable.VARIANCE,
         new AvgVarianceConvertlet(SqlKind.VAR_SAMP));
 
     final SqlRexConvertlet floorCeilConvertlet = new FloorCeilConvertlet();
@@ -330,46 +250,34 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
     // Convert "element(<expr>)" to "$element_slice(<expr>)", if the
     // expression is a multiset of scalars.
     if (false) {
-      registerOp(
-          SqlStdOperatorTable.ELEMENT,
-          new SqlRexConvertlet() {
-            public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-              assert call.operandCount() == 1;
-              final SqlNode operand = call.operand(0);
-              final RelDataType type =
-                  cx.getValidator().getValidatedNodeType(operand);
-              if (!type.getComponentType().isStruct()) {
-                return cx.convertExpression(
-                    SqlStdOperatorTable.ELEMENT_SLICE.createCall(
-                        SqlParserPos.ZERO,
-                        operand));
-              }
-
-              // fallback on default behavior
-              return StandardConvertletTable.this.convertCall(
-                  cx,
-                  call);
+      registerOp(SqlStdOperatorTable.ELEMENT,
+          (cx, call) -> {
+            assert call.operandCount() == 1;
+            final SqlNode operand = call.operand(0);
+            final RelDataType type =
+                cx.getValidator().getValidatedNodeType(operand);
+            if (!type.getComponentType().isStruct()) {
+              return cx.convertExpression(
+                  SqlStdOperatorTable.ELEMENT_SLICE.createCall(
+                      SqlParserPos.ZERO, operand));
             }
+
+            // fallback on default behavior
+            return StandardConvertletTable.this.convertCall(cx, call);
           });
     }
 
     // Convert "$element_slice(<expr>)" to "element(<expr>).field#0"
     if (false) {
-      registerOp(
-          SqlStdOperatorTable.ELEMENT_SLICE,
-          new SqlRexConvertlet() {
-            public RexNode convertCall(SqlRexContext cx, SqlCall call) {
-              assert call.operandCount() == 1;
-              final SqlNode operand = call.operand(0);
-              final RexNode expr =
-                  cx.convertExpression(
-                      SqlStdOperatorTable.ELEMENT.createCall(
-                          SqlParserPos.ZERO,
-                          operand));
-              return cx.getRexBuilder().makeFieldAccess(
-                  expr,
-                  0);
-            }
+      registerOp(SqlStdOperatorTable.ELEMENT_SLICE,
+          (cx, call) -> {
+            assert call.operandCount() == 1;
+            final SqlNode operand = call.operand(0);
+            final RexNode expr =
+                cx.convertExpression(
+                    SqlStdOperatorTable.ELEMENT.createCall(SqlParserPos.ZERO,
+                        operand));
+            return cx.getRexBuilder().makeFieldAccess(expr, 0);
           });
     }
   }
@@ -739,7 +647,7 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
     RelDataType returnType =
         cx.getValidator().getValidatedNodeType(call);
     return cx.getRexBuilder().makeCall(returnType, fun,
-        ImmutableList.<RexNode>of(cx.getRexBuilder().makeLiteral(key)));
+        ImmutableList.of(cx.getRexBuilder().makeLiteral(key)));
   }
 
   public RexNode convertAggregateFunction(
@@ -759,7 +667,8 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
     final int groupCount = cx.getGroupCount();
     if (returnType == null) {
       RexCallBinding binding =
-          new RexCallBinding(cx.getTypeFactory(), fun, exprs, ImmutableList.<RelCollation>of()) {
+          new RexCallBinding(cx.getTypeFactory(), fun, exprs,
+              ImmutableList.of()) {
             @Override public int getGroupCount() {
               return groupCount;
             }
@@ -854,7 +763,7 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
 
   private static List<RexNode> convertExpressionList(SqlRexContext cx,
       List<SqlNode> nodes, SqlOperandTypeChecker.Consistency consistency) {
-    final List<RexNode> exprs = Lists.newArrayList();
+    final List<RexNode> exprs = new ArrayList<>();
     for (SqlNode node : nodes) {
       exprs.add(cx.convertExpression(node));
     }
@@ -880,7 +789,7 @@ public class StandardConvertletTable extends ReflectiveConvertletTable {
         // All arguments are of same family. No need for explicit casts.
         return null;
       }
-      final List<RelDataType> nonCharacterTypes = Lists.newArrayList();
+      final List<RelDataType> nonCharacterTypes = new ArrayList<>();
       for (RelDataType type : types) {
         if (type.getFamily() != SqlTypeFamily.CHARACTER) {
           nonCharacterTypes.add(type);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/tools/Frameworks.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/tools/Frameworks.java b/core/src/main/java/org/apache/calcite/tools/Frameworks.java
index 364e592..ee0549b 100644
--- a/core/src/main/java/org/apache/calcite/tools/Frameworks.java
+++ b/core/src/main/java/org/apache/calcite/tools/Frameworks.java
@@ -37,12 +37,12 @@ import org.apache.calcite.sql2rel.SqlToRelConverter;
 import org.apache.calcite.sql2rel.StandardConvertletTable;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.util.List;
+import java.util.Objects;
 import java.util.Properties;
 
 /**
@@ -200,24 +200,23 @@ public class Frameworks {
     }
 
     public ConfigBuilder context(Context c) {
-      this.context = Preconditions.checkNotNull(c);
+      this.context = Objects.requireNonNull(c);
       return this;
     }
 
     public ConfigBuilder executor(RexExecutor executor) {
-      Preconditions.checkNotNull(executor);
-      this.executor = executor;
+      this.executor = Objects.requireNonNull(executor);
       return this;
     }
 
     public ConfigBuilder convertletTable(
         SqlRexConvertletTable convertletTable) {
-      this.convertletTable = Preconditions.checkNotNull(convertletTable);
+      this.convertletTable = Objects.requireNonNull(convertletTable);
       return this;
     }
 
     public ConfigBuilder operatorTable(SqlOperatorTable operatorTable) {
-      this.operatorTable = Preconditions.checkNotNull(operatorTable);
+      this.operatorTable = Objects.requireNonNull(operatorTable);
       return this;
     }
 
@@ -236,14 +235,14 @@ public class Frameworks {
     }
 
     public ConfigBuilder parserConfig(SqlParser.Config parserConfig) {
-      this.parserConfig = Preconditions.checkNotNull(parserConfig);
+      this.parserConfig = Objects.requireNonNull(parserConfig);
       return this;
     }
 
     public ConfigBuilder sqlToRelConverterConfig(
         SqlToRelConverter.Config sqlToRelConverterConfig) {
       this.sqlToRelConverterConfig =
-          Preconditions.checkNotNull(sqlToRelConverterConfig);
+          Objects.requireNonNull(sqlToRelConverterConfig);
       return this;
     }
 
@@ -262,7 +261,7 @@ public class Frameworks {
     }
 
     public ConfigBuilder ruleSets(List<RuleSet> ruleSets) {
-      return programs(Programs.listOf(Preconditions.checkNotNull(ruleSets)));
+      return programs(Programs.listOf(Objects.requireNonNull(ruleSets)));
     }
 
     public ConfigBuilder programs(List<Program> programs) {
@@ -276,7 +275,7 @@ public class Frameworks {
     }
 
     public ConfigBuilder typeSystem(RelDataTypeSystem typeSystem) {
-      this.typeSystem = Preconditions.checkNotNull(typeSystem);
+      this.typeSystem = Objects.requireNonNull(typeSystem);
       return this;
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/tools/Programs.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/tools/Programs.java b/core/src/main/java/org/apache/calcite/tools/Programs.java
index a37313c..b6337e2 100644
--- a/core/src/main/java/org/apache/calcite/tools/Programs.java
+++ b/core/src/main/java/org/apache/calcite/tools/Programs.java
@@ -64,11 +64,11 @@ import org.apache.calcite.sql2rel.RelDecorrelator;
 import org.apache.calcite.sql2rel.RelFieldTrimmer;
 import org.apache.calcite.sql2rel.SqlToRelConverter;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
@@ -76,13 +76,6 @@ import java.util.List;
  * Utilities for creating {@link Program}s.
  */
 public class Programs {
-  private static final Function<RuleSet, Program> RULE_SET_TO_PROGRAM =
-      new Function<RuleSet, Program>() {
-        public Program apply(RuleSet ruleSet) {
-          return of(ruleSet);
-        }
-      };
-
   public static final ImmutableList<RelOptRule> CALC_RULES =
       ImmutableList.of(
           NoneToBindableConverterRule.INSTANCE,
@@ -156,12 +149,12 @@ public class Programs {
 
   /** Creates a list of programs based on an array of rule sets. */
   public static List<Program> listOf(RuleSet... ruleSets) {
-    return Lists.transform(Arrays.asList(ruleSets), RULE_SET_TO_PROGRAM);
+    return Lists.transform(Arrays.asList(ruleSets), Programs::of);
   }
 
   /** Creates a list of programs based on a list of rule sets. */
   public static List<Program> listOf(List<RuleSet> ruleSets) {
-    return Lists.transform(ruleSets, RULE_SET_TO_PROGRAM);
+    return Lists.transform(ruleSets, Programs::of);
   }
 
   /** Creates a program from a list of rules. */
@@ -192,26 +185,21 @@ public class Programs {
   /** Creates a program that executes a {@link HepProgram}. */
   public static Program of(final HepProgram hepProgram, final boolean noDag,
       final RelMetadataProvider metadataProvider) {
-    return new Program() {
-      public RelNode run(RelOptPlanner planner, RelNode rel,
-          RelTraitSet requiredOutputTraits,
-          List<RelOptMaterialization> materializations,
-          List<RelOptLattice> lattices) {
-        final HepPlanner hepPlanner = new HepPlanner(hepProgram,
-            null, noDag, null, RelOptCostImpl.FACTORY);
-
-        List<RelMetadataProvider> list = Lists.newArrayList();
-        if (metadataProvider != null) {
-          list.add(metadataProvider);
-        }
-        hepPlanner.registerMetadataProviders(list);
-        RelMetadataProvider plannerChain =
-            ChainedRelMetadataProvider.of(list);
-        rel.getCluster().setMetadataProvider(plannerChain);
-
-        hepPlanner.setRoot(rel);
-        return hepPlanner.findBestExp();
+    return (planner, rel, requiredOutputTraits, materializations, lattices) -> {
+      final HepPlanner hepPlanner = new HepPlanner(hepProgram,
+          null, noDag, null, RelOptCostImpl.FACTORY);
+
+      List<RelMetadataProvider> list = new ArrayList<>();
+      if (metadataProvider != null) {
+        list.add(metadataProvider);
       }
+      hepPlanner.registerMetadataProviders(list);
+      RelMetadataProvider plannerChain =
+          ChainedRelMetadataProvider.of(list);
+      rel.getCluster().setMetadataProvider(plannerChain);
+
+      hepPlanner.setRoot(rel);
+      return hepPlanner.findBestExp();
     };
   }
 
@@ -223,45 +211,40 @@ public class Programs {
   public static Program heuristicJoinOrder(
       final Iterable<? extends RelOptRule> rules,
       final boolean bushy, final int minJoinCount) {
-    return new Program() {
-      public RelNode run(RelOptPlanner planner, RelNode rel,
-          RelTraitSet requiredOutputTraits,
-          List<RelOptMaterialization> materializations,
-          List<RelOptLattice> lattices) {
-        final int joinCount = RelOptUtil.countJoins(rel);
-        final Program program;
-        if (joinCount < minJoinCount) {
-          program = ofRules(rules);
-        } else {
-          // Create a program that gathers together joins as a MultiJoin.
-          final HepProgram hep = new HepProgramBuilder()
-              .addRuleInstance(FilterJoinRule.FILTER_ON_JOIN)
-              .addMatchOrder(HepMatchOrder.BOTTOM_UP)
-              .addRuleInstance(JoinToMultiJoinRule.INSTANCE)
-              .build();
-          final Program program1 =
-              of(hep, false, DefaultRelMetadataProvider.INSTANCE);
-
-          // Create a program that contains a rule to expand a MultiJoin
-          // into heuristically ordered joins.
-          // We use the rule set passed in, but remove JoinCommuteRule and
-          // JoinPushThroughJoinRule, because they cause exhaustive search.
-          final List<RelOptRule> list = Lists.newArrayList(rules);
-          list.removeAll(
-              ImmutableList.of(JoinCommuteRule.INSTANCE,
-                  JoinAssociateRule.INSTANCE,
-                  JoinPushThroughJoinRule.LEFT,
-                  JoinPushThroughJoinRule.RIGHT));
-          list.add(bushy
-              ? MultiJoinOptimizeBushyRule.INSTANCE
-              : LoptOptimizeJoinRule.INSTANCE);
-          final Program program2 = ofRules(list);
-
-          program = sequence(program1, program2);
-        }
-        return program.run(
-            planner, rel, requiredOutputTraits, materializations, lattices);
+    return (planner, rel, requiredOutputTraits, materializations, lattices) -> {
+      final int joinCount = RelOptUtil.countJoins(rel);
+      final Program program;
+      if (joinCount < minJoinCount) {
+        program = ofRules(rules);
+      } else {
+        // Create a program that gathers together joins as a MultiJoin.
+        final HepProgram hep = new HepProgramBuilder()
+            .addRuleInstance(FilterJoinRule.FILTER_ON_JOIN)
+            .addMatchOrder(HepMatchOrder.BOTTOM_UP)
+            .addRuleInstance(JoinToMultiJoinRule.INSTANCE)
+            .build();
+        final Program program1 =
+            of(hep, false, DefaultRelMetadataProvider.INSTANCE);
+
+        // Create a program that contains a rule to expand a MultiJoin
+        // into heuristically ordered joins.
+        // We use the rule set passed in, but remove JoinCommuteRule and
+        // JoinPushThroughJoinRule, because they cause exhaustive search.
+        final List<RelOptRule> list = Lists.newArrayList(rules);
+        list.removeAll(
+            ImmutableList.of(JoinCommuteRule.INSTANCE,
+                JoinAssociateRule.INSTANCE,
+                JoinPushThroughJoinRule.LEFT,
+                JoinPushThroughJoinRule.RIGHT));
+        list.add(bushy
+            ? MultiJoinOptimizeBushyRule.INSTANCE
+            : LoptOptimizeJoinRule.INSTANCE);
+        final Program program2 = ofRules(list);
+
+        program = sequence(program1, program2);
       }
+      return program.run(
+          planner, rel, requiredOutputTraits, materializations, lattices);
     };
   }
 
@@ -282,14 +265,8 @@ public class Programs {
   }
 
   public static Program getProgram() {
-    return new Program() {
-      public RelNode run(RelOptPlanner planner, RelNode rel,
-          RelTraitSet requiredOutputTraits,
-          List<RelOptMaterialization> materializations,
-          List<RelOptLattice> lattices) {
-        return null;
-      }
-    };
+    return (planner, rel, requiredOutputTraits, materializations, lattices)
+        -> null;
   }
 
   /** Returns the standard program used by Prepare. */
@@ -299,34 +276,28 @@ public class Programs {
 
   /** Returns the standard program with user metadata provider. */
   public static Program standard(RelMetadataProvider metadataProvider) {
-
     final Program program1 =
-        new Program() {
-          public RelNode run(RelOptPlanner planner, RelNode rel,
-              RelTraitSet requiredOutputTraits,
-              List<RelOptMaterialization> materializations,
-              List<RelOptLattice> lattices) {
-            planner.setRoot(rel);
-
-            for (RelOptMaterialization materialization : materializations) {
-              planner.addMaterialization(materialization);
-            }
-            for (RelOptLattice lattice : lattices) {
-              planner.addLattice(lattice);
-            }
-
-            final RelNode rootRel2 =
-                rel.getTraitSet().equals(requiredOutputTraits)
-                ? rel
-                : planner.changeTraits(rel, requiredOutputTraits);
-            assert rootRel2 != null;
-
-            planner.setRoot(rootRel2);
-            final RelOptPlanner planner2 = planner.chooseDelegate();
-            final RelNode rootRel3 = planner2.findBestExp();
-            assert rootRel3 != null : "could not implement exp";
-            return rootRel3;
+        (planner, rel, requiredOutputTraits, materializations, lattices) -> {
+          planner.setRoot(rel);
+
+          for (RelOptMaterialization materialization : materializations) {
+            planner.addMaterialization(materialization);
           }
+          for (RelOptLattice lattice : lattices) {
+            planner.addLattice(lattice);
+          }
+
+          final RelNode rootRel2 =
+              rel.getTraitSet().equals(requiredOutputTraits)
+                  ? rel
+                  : planner.changeTraits(rel, requiredOutputTraits);
+          assert rootRel2 != null;
+
+          planner.setRoot(rootRel2);
+          final RelOptPlanner planner2 = planner.chooseDelegate();
+          final RelNode rootRel3 = planner2.findBestExp();
+          assert rootRel3 != null : "could not implement exp";
+          return rootRel3;
         };
 
     return sequence(subQuery(metadataProvider),
@@ -334,8 +305,8 @@ public class Programs {
         new TrimFieldsProgram(),
         program1,
 
-        // Second planner pass to do physical "tweaks". This the first time that
-        // EnumerableCalcRel is introduced.
+        // Second planner pass to do physical "tweaks". This the first time
+        // that EnumerableCalcRel is introduced.
         calc(metadataProvider));
   }
 


[22/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoinRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoinRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoinRule.java
index d4748ef..f04df74 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoinRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableMergeJoinRule.java
@@ -30,8 +30,7 @@ import org.apache.calcite.rel.core.JoinInfo;
 import org.apache.calcite.rel.core.JoinRelType;
 import org.apache.calcite.rel.logical.LogicalJoin;
 
-import com.google.common.collect.Lists;
-
+import java.util.ArrayList;
 import java.util.List;
 
 /** Planner rule that converts a
@@ -61,14 +60,14 @@ class EnumerableMergeJoinRule extends ConverterRule {
       // EnumerableMergeJoin CAN support cartesian join, but disable it for now.
       return null;
     }
-    final List<RelNode> newInputs = Lists.newArrayList();
-    final List<RelCollation> collations = Lists.newArrayList();
+    final List<RelNode> newInputs = new ArrayList<>();
+    final List<RelCollation> collations = new ArrayList<>();
     int offset = 0;
     for (Ord<RelNode> ord : Ord.zip(join.getInputs())) {
       RelTraitSet traits = ord.e.getTraitSet()
           .replace(EnumerableConvention.INSTANCE);
       if (!info.pairs().isEmpty()) {
-        final List<RelFieldCollation> fieldCollations = Lists.newArrayList();
+        final List<RelFieldCollation> fieldCollations = new ArrayList<>();
         for (int key : info.keys().get(ord.i)) {
           fieldCollations.add(
               new RelFieldCollation(key, RelFieldCollation.Direction.ASCENDING,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProject.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProject.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProject.java
index a1c3984..9418a20 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProject.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProject.java
@@ -18,7 +18,6 @@ package org.apache.calcite.adapter.enumerable;
 
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Project;
@@ -26,10 +25,10 @@ import org.apache.calcite.rel.metadata.RelMdCollation;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Supplier;
-
 import java.util.List;
 
 /** Implementation of {@link org.apache.calcite.rel.core.Project} in
@@ -73,14 +72,19 @@ public class EnumerableProject extends Project implements EnumerableRel {
     final RelTraitSet traitSet =
         cluster.traitSet().replace(EnumerableConvention.INSTANCE)
             .replaceIfs(RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    return RelMdCollation.project(mq, input, projects);
-                  }
-                });
+                () -> RelMdCollation.project(mq, input, projects));
     return new EnumerableProject(cluster, traitSet, input, projects, rowType);
   }
 
+  static RelNode create(RelNode child, List<? extends RexNode> projects,
+      List<String> fieldNames) {
+    final RelOptCluster cluster = child.getCluster();
+    final RelDataType rowType =
+        RexUtil.createStructType(cluster.getTypeFactory(), projects,
+          fieldNames, SqlValidatorUtil.F_SUGGESTER);
+    return create(child, projects, rowType);
+  }
+
   public EnumerableProject copy(RelTraitSet traitSet, RelNode input,
       List<RexNode> projects, RelDataType rowType) {
     return new EnumerableProject(getCluster(), traitSet, input,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProjectRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProjectRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProjectRule.java
index 9c015a0..b35f382 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProjectRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableProjectRule.java
@@ -23,15 +23,18 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.logical.LogicalProject;
 
+import java.util.function.Predicate;
+
 /**
  * Rule to convert a {@link org.apache.calcite.rel.logical.LogicalProject} to an
  * {@link EnumerableProject}.
  */
 class EnumerableProjectRule extends ConverterRule {
   EnumerableProjectRule() {
-    super(LogicalProject.class, RelOptUtil.PROJECT_PREDICATE, Convention.NONE,
-        EnumerableConvention.INSTANCE, RelFactories.LOGICAL_BUILDER,
-        "EnumerableProjectRule");
+    super(LogicalProject.class,
+        (Predicate<LogicalProject>) RelOptUtil::containsMultisetOrWindowedAgg,
+        Convention.NONE, EnumerableConvention.INSTANCE,
+        RelFactories.LOGICAL_BUILDER, "EnumerableProjectRule");
   }
 
   public RelNode convert(RelNode rel) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRel.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRel.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRel.java
index 5f9b7d3..18f2594 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRel.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRel.java
@@ -17,15 +17,8 @@
 package org.apache.calcite.adapter.enumerable;
 
 import org.apache.calcite.linq4j.tree.BlockStatement;
-import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.RelFactories;
-import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.rex.RexUtil;
-import org.apache.calcite.sql.validate.SqlValidatorUtil;
-
-import java.util.List;
 
 /**
  * A relational expression of one of the
@@ -34,24 +27,9 @@ import java.util.List;
  */
 public interface EnumerableRel
     extends RelNode {
-  RelFactories.FilterFactory FILTER_FACTORY =
-      new RelFactories.FilterFactory() {
-        public RelNode createFilter(RelNode child, RexNode condition) {
-          return EnumerableFilter.create(child, condition);
-        }
-      };
+  RelFactories.FilterFactory FILTER_FACTORY = EnumerableFilter::create;
 
-  RelFactories.ProjectFactory PROJECT_FACTORY =
-      new RelFactories.ProjectFactory() {
-        public RelNode createProject(RelNode child,
-            List<? extends RexNode> projects, List<String> fieldNames) {
-          final RelOptCluster cluster = child.getCluster();
-          final RelDataType rowType =
-              RexUtil.createStructType(cluster.getTypeFactory(), projects,
-                  fieldNames, SqlValidatorUtil.F_SUGGESTER);
-          return EnumerableProject.create(child, projects, rowType);
-        }
-      };
+  RelFactories.ProjectFactory PROJECT_FACTORY = EnumerableProject::create;
 
   //~ Methods ----------------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelImplementor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelImplementor.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelImplementor.java
index dfae89f..b331511 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelImplementor.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelImplementor.java
@@ -42,11 +42,9 @@ import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.runtime.Bindable;
 import org.apache.calcite.util.BuiltInMethod;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
 
 import java.io.Serializable;
 import java.lang.reflect.Method;
@@ -56,7 +54,9 @@ import java.lang.reflect.Type;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
+import java.util.IdentityHashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
@@ -69,17 +69,13 @@ import java.util.Set;
 public class EnumerableRelImplementor extends JavaRelImplementor {
   public final Map<String, Object> map;
   private final Map<String, RexToLixTranslator.InputGetter> corrVars =
-      Maps.newHashMap();
+      new HashMap<>();
   private final Map<Object, ParameterExpression> stashedParameters =
-      Maps.newIdentityHashMap();
+      new IdentityHashMap<>();
   int windowCount = 0;
 
   protected final Function1<String, RexToLixTranslator.InputGetter> allCorrelateVariables =
-      new Function1<String, RexToLixTranslator.InputGetter>() {
-        public RexToLixTranslator.InputGetter apply(String name) {
-          return getCorrelVariableGetter(name);
-        }
-      };
+      this::getCorrelVariableGetter;
 
   public EnumerableRelImplementor(RexBuilder rexBuilder,
       Map<String, Object> internalParameters) {
@@ -139,16 +135,12 @@ public class EnumerableRelImplementor extends JavaRelImplementor {
     // It is convenient for passing non-literal "compile-time" constants
     final Collection<Statement> stashed =
         Collections2.transform(stashedParameters.values(),
-            new Function<ParameterExpression, Statement>() {
-              public Statement apply(ParameterExpression input) {
-                return Expressions.declare(Modifier.FINAL, input,
-                    Expressions.convert_(
-                        Expressions.call(DataContext.ROOT,
-                            BuiltInMethod.DATA_CONTEXT_GET.method,
-                            Expressions.constant(input.name)),
-                        input.type));
-              }
-            });
+            input -> Expressions.declare(Modifier.FINAL, input,
+                Expressions.convert_(
+                    Expressions.call(DataContext.ROOT,
+                        BuiltInMethod.DATA_CONTEXT_GET.method,
+                        Expressions.constant(input.name)),
+                    input.type)));
 
     final BlockStatement block = Expressions.block(
         Iterables.concat(
@@ -170,14 +162,14 @@ public class EnumerableRelImplementor extends JavaRelImplementor {
     memberDeclarations.add(
         Expressions.methodDecl(Modifier.PUBLIC, Class.class,
             BuiltInMethod.TYPED_GET_ELEMENT_TYPE.method.getName(),
-            Collections.<ParameterExpression>emptyList(),
+            ImmutableList.of(),
             Blocks.toFunctionBlock(
                 Expressions.return_(null,
                     Expressions.constant(result.physType.getJavaRowType())))));
     return Expressions.classDecl(Modifier.PUBLIC,
         "Baz",
         null,
-        Collections.<Type>singletonList(Bindable.class),
+        Collections.singletonList(Bindable.class),
         memberDeclarations);
   }
 
@@ -188,7 +180,7 @@ public class EnumerableRelImplementor extends JavaRelImplementor {
             Modifier.PUBLIC | Modifier.STATIC,
             type.getName(),
             null,
-            ImmutableList.<Type>of(Serializable.class),
+            ImmutableList.of(Serializable.class),
             new ArrayList<MemberDeclaration>());
 
     // For each field:
@@ -302,7 +294,7 @@ public class EnumerableRelImplementor extends JavaRelImplementor {
             Modifier.PUBLIC,
             int.class,
             "hashCode",
-            Collections.<ParameterExpression>emptyList(),
+            Collections.emptyList(),
             blockBuilder3.toBlock()));
 
     // compareTo method:
@@ -400,7 +392,7 @@ public class EnumerableRelImplementor extends JavaRelImplementor {
             Modifier.PUBLIC,
             String.class,
             "toString",
-            Collections.<ParameterExpression>emptyList(),
+            Collections.emptyList(),
             blockBuilder5.toBlock()));
 
     return classDeclaration;
@@ -455,12 +447,10 @@ public class EnumerableRelImplementor extends JavaRelImplementor {
   public void registerCorrelVariable(final String name,
       final ParameterExpression pe,
       final BlockBuilder corrBlock, final PhysType physType) {
-    corrVars.put(name, new RexToLixTranslator.InputGetter() {
-      public Expression field(BlockBuilder list, int index, Type storageType) {
-        Expression fieldReference =
-            physType.fieldReference(pe, index, storageType);
-        return corrBlock.append(name + "_" + index, fieldReference);
-      }
+    corrVars.put(name, (list, index, storageType) -> {
+      Expression fieldReference =
+          physType.fieldReference(pe, index, storageType);
+      return corrBlock.append(name + "_" + index, fieldReference);
     });
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScanRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScanRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScanRule.java
index 8a21b1e..a5a4190 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScanRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScanRule.java
@@ -24,7 +24,7 @@ import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.logical.LogicalTableFunctionScan;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /** Planner rule that converts a
  * {@link org.apache.calcite.rel.logical.LogicalTableFunctionScan}
@@ -42,7 +42,7 @@ public class EnumerableTableFunctionScanRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableTableFunctionScanRule(RelBuilderFactory relBuilderFactory) {
-    super(LogicalTableFunctionScan.class, Predicates.<RelNode>alwaysTrue(),
+    super(LogicalTableFunctionScan.class, (Predicate<RelNode>) r -> true,
         Convention.NONE, EnumerableConvention.INSTANCE, relBuilderFactory,
         "EnumerableTableFunctionScanRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableModifyRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableModifyRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableModifyRule.java
index 87eaefe..3e960b2 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableModifyRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableModifyRule.java
@@ -24,7 +24,7 @@ import org.apache.calcite.rel.logical.LogicalTableModify;
 import org.apache.calcite.schema.ModifiableTable;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /** Planner rule that converts a
  * {@link org.apache.calcite.rel.logical.LogicalTableModify}
@@ -37,7 +37,7 @@ public class EnumerableTableModifyRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableTableModifyRule(RelBuilderFactory relBuilderFactory) {
-    super(LogicalTableModify.class, Predicates.<RelNode>alwaysTrue(),
+    super(LogicalTableModify.class, (Predicate<RelNode>) r -> true,
         Convention.NONE, EnumerableConvention.INSTANCE, relBuilderFactory,
         "EnumerableTableModificationRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScan.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScan.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScan.java
index 3b4d8a1..78826a1 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScan.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScan.java
@@ -31,7 +31,6 @@ import org.apache.calcite.linq4j.tree.Types;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.TableScan;
@@ -45,7 +44,6 @@ import org.apache.calcite.schema.StreamableTable;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.util.BuiltInMethod;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.lang.reflect.Type;
@@ -76,15 +74,12 @@ public class EnumerableTableScan
     Class elementType = EnumerableTableScan.deduceElementType(table);
     final RelTraitSet traitSet =
         cluster.traitSetOf(EnumerableConvention.INSTANCE)
-            .replaceIfs(RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    if (table != null) {
-                      return table.getStatistic().getCollations();
-                    }
-                    return ImmutableList.of();
-                  }
-                });
+            .replaceIfs(RelCollationTraitDef.INSTANCE, () -> {
+              if (table != null) {
+                return table.getStatistic().getCollations();
+              }
+              return ImmutableList.of();
+            });
     return new EnumerableTableScan(cluster, traitSet, relOptTable, elementType);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScanRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScanRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScanRule.java
index adcfa09..3fe1a56 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScanRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableScanRule.java
@@ -26,7 +26,7 @@ import org.apache.calcite.rel.logical.LogicalTableScan;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /** Planner rule that converts a
  * {@link org.apache.calcite.rel.logical.LogicalTableFunctionScan}
@@ -45,7 +45,7 @@ public class EnumerableTableScanRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableTableScanRule(RelBuilderFactory relBuilderFactory) {
-    super(LogicalTableScan.class, Predicates.<RelNode>alwaysTrue(),
+    super(LogicalTableScan.class, (Predicate<RelNode>) r -> true,
         Convention.NONE, EnumerableConvention.INSTANCE, relBuilderFactory,
         "EnumerableTableScanRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableUncollect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableUncollect.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableUncollect.java
index 9818622..2417c16 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableUncollect.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableUncollect.java
@@ -116,7 +116,7 @@ public class EnumerableUncollect extends Uncollect implements EnumerableRel {
             Expressions.constant(Ints.toArray(fieldCounts)),
             Expressions.constant(withOrdinality),
             Expressions.constant(
-                inputTypes.toArray(new FlatProductInputType[inputTypes.size()])));
+                inputTypes.toArray(new FlatProductInputType[0])));
     builder.add(
         Expressions.return_(null,
             Expressions.call(child_,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValues.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValues.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValues.java
index b4a95c3..ebf6ffd 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValues.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValues.java
@@ -23,9 +23,7 @@ import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.Primitive;
 import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelTraitSet;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
-import org.apache.calcite.rel.RelDistribution;
 import org.apache.calcite.rel.RelDistributionTraitDef;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Values;
@@ -38,7 +36,6 @@ import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.lang.reflect.Type;
@@ -62,17 +59,9 @@ public class EnumerableValues extends Values implements EnumerableRel {
     final RelTraitSet traitSet =
         cluster.traitSetOf(EnumerableConvention.INSTANCE)
             .replaceIfs(RelCollationTraitDef.INSTANCE,
-                new Supplier<List<RelCollation>>() {
-                  public List<RelCollation> get() {
-                    return RelMdCollation.values(mq, rowType, tuples);
-                  }
-                })
+                () -> RelMdCollation.values(mq, rowType, tuples))
             .replaceIf(RelDistributionTraitDef.INSTANCE,
-                new Supplier<RelDistribution>() {
-                  public RelDistribution get() {
-                    return RelMdDistribution.values(rowType, tuples);
-                  }
-                });
+                () -> RelMdDistribution.values(rowType, tuples));
     return new EnumerableValues(cluster, rowType, tuples, traitSet);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValuesRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValuesRule.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValuesRule.java
index b401598..b48251b 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValuesRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableValuesRule.java
@@ -22,7 +22,7 @@ import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.rel.logical.LogicalValues;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /** Planner rule that converts a
  * {@link org.apache.calcite.rel.logical.LogicalValues}
@@ -35,7 +35,7 @@ public class EnumerableValuesRule extends ConverterRule {
    * @param relBuilderFactory Builder for relational expressions
    */
   public EnumerableValuesRule(RelBuilderFactory relBuilderFactory) {
-    super(LogicalValues.class, Predicates.<RelNode>alwaysTrue(),
+    super(LogicalValues.class, (Predicate<RelNode>) r -> true,
         Convention.NONE, EnumerableConvention.INSTANCE, relBuilderFactory,
         "EnumerableValuesRule");
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableWindow.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableWindow.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableWindow.java
index 9c7c737..110c724 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableWindow.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableWindow.java
@@ -53,7 +53,6 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 
 import java.lang.reflect.Modifier;
@@ -62,6 +61,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Iterator;
 import java.util.List;
+import java.util.function.Function;
 
 /** Implementation of {@link org.apache.calcite.rel.core.Window} in
  * {@link org.apache.calcite.adapter.enumerable.EnumerableConvention enumerable calling convention}. */
@@ -429,24 +429,21 @@ public class EnumerableWindow extends Window implements EnumerableRel {
               hasRows, frameRowCount, partitionRowCount,
               jDecl, inputPhysTypeFinal);
 
-      final Function<AggImpState, List<RexNode>> rexArguments =
-          new Function<AggImpState, List<RexNode>>() {
-            public List<RexNode> apply(AggImpState agg) {
-              List<Integer> argList = agg.call.getArgList();
-              List<RelDataType> inputTypes =
-                  EnumUtils.fieldRowTypes(
-                      result.physType.getRowType(),
-                      constants,
-                      argList);
-              List<RexNode> args = new ArrayList<RexNode>(
-                  inputTypes.size());
-              for (int i = 0; i < argList.size(); i++) {
-                Integer idx = argList.get(i);
-                args.add(new RexInputRef(idx, inputTypes.get(i)));
-              }
-              return args;
-            }
-          };
+      final Function<AggImpState, List<RexNode>> rexArguments = agg -> {
+        List<Integer> argList = agg.call.getArgList();
+        List<RelDataType> inputTypes =
+            EnumUtils.fieldRowTypes(
+                result.physType.getRowType(),
+                constants,
+                argList);
+        List<RexNode> args = new ArrayList<RexNode>(
+            inputTypes.size());
+        for (int i = 0; i < argList.size(); i++) {
+          Integer idx = argList.get(i);
+          args.add(new RexInputRef(idx, inputTypes.get(i)));
+        }
+        return args;
+      };
 
       implementAdd(aggs, builder7, resultContextBuilder, rexArguments, jDecl);
 
@@ -533,107 +530,101 @@ public class EnumerableWindow extends Window implements EnumerableRel {
       final Expression partitionRowCount,
       final DeclarationStatement jDecl,
       final PhysType inputPhysType) {
-    return new Function<BlockBuilder,
-        WinAggFrameResultContext>() {
-      public WinAggFrameResultContext apply(
-          final BlockBuilder block) {
-        return new WinAggFrameResultContext() {
-          public RexToLixTranslator rowTranslator(Expression rowIndex) {
-            Expression row =
-                getRow(rowIndex);
-            final RexToLixTranslator.InputGetter inputGetter =
-                new WindowRelInputGetter(row, inputPhysType,
-                    result.physType.getRowType().getFieldCount(),
-                    translatedConstants);
-
-            return RexToLixTranslator.forAggregation(typeFactory,
-                block, inputGetter);
-          }
+    return block -> new WinAggFrameResultContext() {
+      public RexToLixTranslator rowTranslator(Expression rowIndex) {
+        Expression row =
+            getRow(rowIndex);
+        final RexToLixTranslator.InputGetter inputGetter =
+            new WindowRelInputGetter(row, inputPhysType,
+                result.physType.getRowType().getFieldCount(),
+                translatedConstants);
+
+        return RexToLixTranslator.forAggregation(typeFactory,
+            block, inputGetter);
+      }
 
-          public Expression computeIndex(Expression offset,
-              WinAggImplementor.SeekType seekType) {
-            Expression index;
-            if (seekType == WinAggImplementor.SeekType.AGG_INDEX) {
-              index = jDecl.parameter;
-            } else if (seekType == WinAggImplementor.SeekType.SET) {
-              index = i_;
-            } else if (seekType == WinAggImplementor.SeekType.START) {
-              index = startX;
-            } else if (seekType == WinAggImplementor.SeekType.END) {
-              index = endX;
-            } else {
-              throw new IllegalArgumentException("SeekSet " + seekType
-                  + " is not supported");
-            }
-            if (!Expressions.constant(0).equals(offset)) {
-              index = block.append("idx", Expressions.add(index, offset));
-            }
-            return index;
-          }
+      public Expression computeIndex(Expression offset,
+          WinAggImplementor.SeekType seekType) {
+        Expression index;
+        if (seekType == WinAggImplementor.SeekType.AGG_INDEX) {
+          index = jDecl.parameter;
+        } else if (seekType == WinAggImplementor.SeekType.SET) {
+          index = i_;
+        } else if (seekType == WinAggImplementor.SeekType.START) {
+          index = startX;
+        } else if (seekType == WinAggImplementor.SeekType.END) {
+          index = endX;
+        } else {
+          throw new IllegalArgumentException("SeekSet " + seekType
+              + " is not supported");
+        }
+        if (!Expressions.constant(0).equals(offset)) {
+          index = block.append("idx", Expressions.add(index, offset));
+        }
+        return index;
+      }
 
-          private Expression checkBounds(Expression rowIndex,
-              Expression minIndex, Expression maxIndex) {
-            if (rowIndex == i_ || rowIndex == startX || rowIndex == endX) {
-              // No additional bounds check required
-              return hasRows;
-            }
+      private Expression checkBounds(Expression rowIndex,
+          Expression minIndex, Expression maxIndex) {
+        if (rowIndex == i_ || rowIndex == startX || rowIndex == endX) {
+          // No additional bounds check required
+          return hasRows;
+        }
 
-            //noinspection UnnecessaryLocalVariable
-            Expression res = block.append("rowInFrame",
-                Expressions.foldAnd(
-                    ImmutableList.of(hasRows,
-                        Expressions.greaterThanOrEqual(rowIndex, minIndex),
-                        Expressions.lessThanOrEqual(rowIndex, maxIndex))));
+        //noinspection UnnecessaryLocalVariable
+        Expression res = block.append("rowInFrame",
+            Expressions.foldAnd(
+                ImmutableList.of(hasRows,
+                    Expressions.greaterThanOrEqual(rowIndex, minIndex),
+                    Expressions.lessThanOrEqual(rowIndex, maxIndex))));
 
-            return res;
-          }
+        return res;
+      }
 
-          public Expression rowInFrame(Expression rowIndex) {
-            return checkBounds(rowIndex, startX, endX);
-          }
+      public Expression rowInFrame(Expression rowIndex) {
+        return checkBounds(rowIndex, startX, endX);
+      }
 
-          public Expression rowInPartition(Expression rowIndex) {
-            return checkBounds(rowIndex, minX, maxX);
-          }
+      public Expression rowInPartition(Expression rowIndex) {
+        return checkBounds(rowIndex, minX, maxX);
+      }
 
-          public Expression compareRows(Expression a, Expression b) {
-            return Expressions.call(comparator_,
-                BuiltInMethod.COMPARATOR_COMPARE.method,
-                getRow(a), getRow(b));
-          }
+      public Expression compareRows(Expression a, Expression b) {
+        return Expressions.call(comparator_,
+            BuiltInMethod.COMPARATOR_COMPARE.method,
+            getRow(a), getRow(b));
+      }
 
-          public Expression getRow(Expression rowIndex) {
-            return block.append(
-                "jRow",
-                RexToLixTranslator.convert(
-                    Expressions.arrayIndex(rows_, rowIndex),
-                    inputPhysType.getJavaRowType()));
-          }
+      public Expression getRow(Expression rowIndex) {
+        return block.append(
+            "jRow",
+            RexToLixTranslator.convert(
+                Expressions.arrayIndex(rows_, rowIndex),
+                inputPhysType.getJavaRowType()));
+      }
 
-          public Expression index() {
-            return i_;
-          }
+      public Expression index() {
+        return i_;
+      }
 
-          public Expression startIndex() {
-            return startX;
-          }
+      public Expression startIndex() {
+        return startX;
+      }
 
-          public Expression endIndex() {
-            return endX;
-          }
+      public Expression endIndex() {
+        return endX;
+      }
 
-          public Expression hasRows() {
-            return hasRows;
-          }
+      public Expression hasRows() {
+        return hasRows;
+      }
 
-          public Expression getFrameRowCount() {
-            return frameRowCount;
-          }
+      public Expression getFrameRowCount() {
+        return frameRowCount;
+      }
 
-          public Expression getPartitionRowCount() {
-            return partitionRowCount;
-          }
-        };
+      public Expression getPartitionRowCount() {
+        return partitionRowCount;
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/NestedBlockBuilderImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/NestedBlockBuilderImpl.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/NestedBlockBuilderImpl.java
index 1caa47e..d0fadf3 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/NestedBlockBuilderImpl.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/NestedBlockBuilderImpl.java
@@ -52,7 +52,7 @@ public class NestedBlockBuilderImpl implements NestedBlockBuilder {
    */
   public final BlockBuilder nestBlock() {
     BlockBuilder block = new BlockBuilder(true, currentBlock());
-    nestBlock(block, Collections.<RexNode, Boolean>emptyMap());
+    nestBlock(block, Collections.emptyMap());
     return block;
   }
 
@@ -63,7 +63,7 @@ public class NestedBlockBuilderImpl implements NestedBlockBuilder {
    * @see #exitBlock()
    */
   public final void nestBlock(BlockBuilder block) {
-    nestBlock(block, Collections.<RexNode, Boolean>emptyMap());
+    nestBlock(block, Collections.emptyMap());
   }
 
   /**
@@ -77,7 +77,7 @@ public class NestedBlockBuilderImpl implements NestedBlockBuilder {
       Map<RexNode, Boolean> nullables) {
     blocks.add(block);
     Map<RexNode, Boolean> prev = this.nullables.isEmpty()
-        ? Collections.<RexNode, Boolean>emptyMap()
+        ? Collections.emptyMap()
         : this.nullables.get(this.nullables.size() - 1);
     Map<RexNode, Boolean> next;
     if (nullables == null || nullables.isEmpty()) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/PhysTypeImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/PhysTypeImpl.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/PhysTypeImpl.java
index 487ddee..7464a27 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/PhysTypeImpl.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/PhysTypeImpl.java
@@ -39,14 +39,12 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.lang.reflect.Type;
 import java.util.AbstractList;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
 
@@ -173,7 +171,7 @@ public class PhysTypeImpl implements PhysType {
       JavaRowFormat targetFormat) {
     final PhysType targetPhysType =
         project(fields, true, targetFormat);
-    final List<Expression> expressions = Lists.newArrayList();
+    final List<Expression> expressions = new ArrayList<>();
     for (Ord<Integer> ord : Ord.zip(fields)) {
       final Integer field = ord.e;
       if (usedFields.contains(field)) {
@@ -210,8 +208,7 @@ public class PhysTypeImpl implements PhysType {
         project(fields, targetFormat);
     switch (format) {
     case SCALAR:
-      return Pair.of(parameter.getType(),
-          Collections.<Expression>singletonList(parameter));
+      return Pair.of(parameter.getType(), ImmutableList.of(parameter));
     default:
       return Pair.of(targetPhysType.getJavaRowType(),
           fieldReferences(parameter, fields));
@@ -262,8 +259,7 @@ public class PhysTypeImpl implements PhysType {
               Function1.class,
               fieldReference(parameter, collation.getFieldIndex()),
               parameter);
-      return Pair.<Expression, Expression>of(
-          selector,
+      return Pair.of(selector,
           Expressions.call(
               BuiltInMethod.NULLS_COMPARATOR.method,
               Expressions.constant(
@@ -332,7 +328,7 @@ public class PhysTypeImpl implements PhysType {
         Expressions.return_(null, Expressions.constant(0)));
 
     final List<MemberDeclaration> memberDeclarations =
-        Expressions.<MemberDeclaration>list(
+        Expressions.list(
             Expressions.methodDecl(
                 Modifier.PUBLIC,
                 int.class,
@@ -366,11 +362,9 @@ public class PhysTypeImpl implements PhysType {
               ImmutableList.of(parameterO0, parameterO1),
               bridgeBody.toBlock()));
     }
-    return Pair.<Expression, Expression>of(
-        selector,
-        Expressions.new_(
-            Comparator.class,
-            Collections.<Expression>emptyList(),
+    return Pair.of(selector,
+        Expressions.new_(Comparator.class,
+            ImmutableList.of(),
             memberDeclarations));
   }
 
@@ -433,7 +427,7 @@ public class PhysTypeImpl implements PhysType {
         Expressions.return_(null, Expressions.constant(0)));
 
     final List<MemberDeclaration> memberDeclarations =
-        Expressions.<MemberDeclaration>list(
+        Expressions.list(
             Expressions.methodDecl(
                 Modifier.PUBLIC,
                 int.class,
@@ -468,7 +462,7 @@ public class PhysTypeImpl implements PhysType {
     }
     return Expressions.new_(
         Comparator.class,
-        Collections.<Expression>emptyList(),
+        ImmutableList.of(),
         memberDeclarations);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
index 1ccc477..1bc9de4 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
@@ -57,9 +57,7 @@ import org.apache.calcite.util.BuiltInMethod;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Maps;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
@@ -74,6 +72,7 @@ import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Supplier;
 
 import static org.apache.calcite.linq4j.tree.ExpressionType.Add;
 import static org.apache.calcite.linq4j.tree.ExpressionType.AndAlso;
@@ -231,9 +230,9 @@ public class RexImpTable {
 
   private final Map<SqlOperator, CallImplementor> map = new HashMap<>();
   private final Map<SqlAggFunction, Supplier<? extends AggImplementor>> aggMap =
-      Maps.newHashMap();
+      new HashMap<>();
   private final Map<SqlAggFunction, Supplier<? extends WinAggImplementor>> winAggMap =
-      Maps.newHashMap();
+      new HashMap<>();
 
   RexImpTable() {
     defineMethod(ROW, BuiltInMethod.ARRAY.method, NullPolicy.ANY);
@@ -327,12 +326,7 @@ public class RexImpTable {
     defineMethod(TAN, "tan", NullPolicy.STRICT);
     defineMethod(TRUNCATE, "struncate", NullPolicy.STRICT);
 
-    map.put(PI, new CallImplementor() {
-      @Override public Expression implement(RexToLixTranslator translator,
-          RexCall call, NullAs nullAs) {
-        return Expressions.constant(Math.PI);
-      }
-    });
+    map.put(PI, (translator, call, nullAs) -> Expressions.constant(Math.PI));
 
     // datetime
     defineImplementor(DATETIME_PLUS, NullPolicy.STRICT,
@@ -413,13 +407,7 @@ public class RexImpTable {
     map.put(ARRAY_VALUE_CONSTRUCTOR, value);
     map.put(ITEM, new ItemImplementor());
 
-    map.put(DEFAULT,
-        new CallImplementor() {
-          public Expression implement(RexToLixTranslator translator,
-              RexCall call, NullAs nullAs) {
-            return Expressions.constant(null);
-          }
-        });
+    map.put(DEFAULT, (translator, call, nullAs) -> Expressions.constant(null));
 
     // Sequences
     defineImplementor(CURRENT_VALUE, NullPolicy.STRICT,
@@ -482,15 +470,13 @@ public class RexImpTable {
       throw new IllegalArgumentException(
           klass + " should implement zero arguments constructor");
     }
-    return new Supplier<T>() {
-      public T get() {
-        try {
-          return constructor.newInstance();
-        } catch (InstantiationException | IllegalAccessException
-            | InvocationTargetException e) {
-          throw new IllegalStateException(
-              "Error while creating aggregate implementor " + constructor, e);
-        }
+    return () -> {
+      try {
+        return constructor.newInstance();
+      } catch (InstantiationException | IllegalAccessException
+          | InvocationTargetException e) {
+        throw new IllegalStateException(
+            "Error while creating aggregate implementor " + constructor, e);
       }
     };
   }
@@ -528,14 +514,9 @@ public class RexImpTable {
     case ANY:
     case STRICT:
     case SEMI_STRICT:
-      return new CallImplementor() {
-        public Expression implement(
-            RexToLixTranslator translator, RexCall call, NullAs nullAs) {
-          return implementNullSemantics0(
-              translator, call, nullAs, nullPolicy, harmonize,
-              implementor);
-        }
-      };
+      return (translator, call, nullAs) -> implementNullSemantics0(
+          translator, call, nullAs, nullPolicy, harmonize,
+          implementor);
     case AND:
 /* TODO:
             if (nullAs == NullAs.FALSE) {
@@ -549,41 +530,38 @@ public class RexImpTable {
       // b0 == null ? (b1 == null || b1 ? null : Boolean.FALSE)
       //   : b0 ? b1
       //   : Boolean.FALSE;
-      return new CallImplementor() {
-        public Expression implement(
-            RexToLixTranslator translator, RexCall call, NullAs nullAs) {
-          assert call.getOperator() == AND
-              : "AND null semantics is supported only for AND operator. Actual operator is "
-              + String.valueOf(call.getOperator());
-          final RexCall call2 = call2(false, translator, call);
-          switch (nullAs) {
-          case NOT_POSSIBLE: // Just foldAnd
-          case TRUE:
-            // AND call should return false iff has FALSEs,
-            // thus if we convert nulls to true then no harm is made
-          case FALSE:
-            // AND call should return false iff has FALSEs or has NULLs,
-            // thus if we convert nulls to false, no harm is made
-            final List<Expression> expressions =
-                translator.translateList(call2.getOperands(), nullAs);
-            return Expressions.foldAnd(expressions);
-          case NULL:
-          case IS_NULL:
-          case IS_NOT_NULL:
-            final List<Expression> nullAsTrue =
-                translator.translateList(call2.getOperands(), NullAs.TRUE);
-            final List<Expression> nullAsIsNull =
-                translator.translateList(call2.getOperands(), NullAs.IS_NULL);
-            Expression hasFalse = Expressions.not(Expressions.foldAnd(nullAsTrue));
-            Expression hasNull = Expressions.foldOr(nullAsIsNull);
-            Expression result = nullAs.handle(
-                Expressions.condition(hasFalse, BOXED_FALSE_EXPR,
-                    Expressions.condition(hasNull, NULL_EXPR, BOXED_TRUE_EXPR)));
-            return result;
-          default:
-            throw new IllegalArgumentException(
-                "Unknown nullAs when implementing AND: " + nullAs);
-          }
+      return (translator, call, nullAs) -> {
+        assert call.getOperator() == AND
+            : "AND null semantics is supported only for AND operator. Actual operator is "
+            + String.valueOf(call.getOperator());
+        final RexCall call2 = call2(false, translator, call);
+        switch (nullAs) {
+        case NOT_POSSIBLE: // Just foldAnd
+        case TRUE:
+          // AND call should return false iff has FALSEs,
+          // thus if we convert nulls to true then no harm is made
+        case FALSE:
+          // AND call should return false iff has FALSEs or has NULLs,
+          // thus if we convert nulls to false, no harm is made
+          final List<Expression> expressions =
+              translator.translateList(call2.getOperands(), nullAs);
+          return Expressions.foldAnd(expressions);
+        case NULL:
+        case IS_NULL:
+        case IS_NOT_NULL:
+          final List<Expression> nullAsTrue =
+              translator.translateList(call2.getOperands(), NullAs.TRUE);
+          final List<Expression> nullAsIsNull =
+              translator.translateList(call2.getOperands(), NullAs.IS_NULL);
+          Expression hasFalse =
+              Expressions.not(Expressions.foldAnd(nullAsTrue));
+          Expression hasNull = Expressions.foldOr(nullAsIsNull);
+          return nullAs.handle(
+              Expressions.condition(hasFalse, BOXED_FALSE_EXPR,
+                  Expressions.condition(hasNull, NULL_EXPR, BOXED_TRUE_EXPR)));
+        default:
+          throw new IllegalArgumentException(
+              "Unknown nullAs when implementing AND: " + nullAs);
         }
       };
     case OR:
@@ -594,41 +572,38 @@ public class RexImpTable {
       // b0 == null ? (b1 == null || !b1 ? null : Boolean.TRUE)
       //   : !b0 ? b1
       //   : Boolean.TRUE;
-      return new CallImplementor() {
-        public Expression implement(
-            RexToLixTranslator translator, RexCall call, final NullAs nullAs) {
-          assert call.getOperator() == OR
-              : "OR null semantics is supported only for OR operator. Actual operator is "
-              + String.valueOf(call.getOperator());
-          final RexCall call2 = call2(harmonize, translator, call);
-          switch (nullAs) {
-          case NOT_POSSIBLE: // Just foldOr
-          case TRUE:
-            // This should return false iff all arguments are FALSE,
-            // thus we convert nulls to TRUE and foldOr
-          case FALSE:
-            // This should return true iff has TRUE arguments,
-            // thus we convert nulls to FALSE and foldOr
-            final List<Expression> expressions =
-                translator.translateList(call2.getOperands(), nullAs);
-            return Expressions.foldOr(expressions);
-          case NULL:
-          case IS_NULL:
-          case IS_NOT_NULL:
-            final List<Expression> nullAsFalse =
-                translator.translateList(call2.getOperands(), NullAs.FALSE);
-            final List<Expression> nullAsIsNull =
-                translator.translateList(call2.getOperands(), NullAs.IS_NULL);
-            Expression hasTrue = Expressions.foldOr(nullAsFalse);
-            Expression hasNull = Expressions.foldOr(nullAsIsNull);
-            Expression result = nullAs.handle(
-                Expressions.condition(hasTrue, BOXED_TRUE_EXPR,
-                    Expressions.condition(hasNull, NULL_EXPR, BOXED_FALSE_EXPR)));
-            return result;
-          default:
-            throw new IllegalArgumentException(
-                "Unknown nullAs when implementing OR: " + nullAs);
-          }
+      return (translator, call, nullAs) -> {
+        assert call.getOperator() == OR
+            : "OR null semantics is supported only for OR operator. Actual operator is "
+            + String.valueOf(call.getOperator());
+        final RexCall call2 = call2(harmonize, translator, call);
+        switch (nullAs) {
+        case NOT_POSSIBLE: // Just foldOr
+        case TRUE:
+          // This should return false iff all arguments are FALSE,
+          // thus we convert nulls to TRUE and foldOr
+        case FALSE:
+          // This should return true iff has TRUE arguments,
+          // thus we convert nulls to FALSE and foldOr
+          final List<Expression> expressions =
+              translator.translateList(call2.getOperands(), nullAs);
+          return Expressions.foldOr(expressions);
+        case NULL:
+        case IS_NULL:
+        case IS_NOT_NULL:
+          final List<Expression> nullAsFalse =
+              translator.translateList(call2.getOperands(), NullAs.FALSE);
+          final List<Expression> nullAsIsNull =
+              translator.translateList(call2.getOperands(), NullAs.IS_NULL);
+          Expression hasTrue = Expressions.foldOr(nullAsFalse);
+          Expression hasNull = Expressions.foldOr(nullAsIsNull);
+          Expression result = nullAs.handle(
+              Expressions.condition(hasTrue, BOXED_TRUE_EXPR,
+                  Expressions.condition(hasNull, NULL_EXPR, BOXED_FALSE_EXPR)));
+          return result;
+        default:
+          throw new IllegalArgumentException(
+              "Unknown nullAs when implementing OR: " + nullAs);
         }
       };
     case NOT:
@@ -661,13 +636,10 @@ public class RexImpTable {
         }
       };
     case NONE:
-      return new CallImplementor() {
-        public Expression implement(
-            RexToLixTranslator translator, RexCall call, NullAs nullAs) {
-          final RexCall call2 = call2(false, translator, call);
-          return implementCall(
-              translator, call2, implementor, nullAs);
-        }
+      return (translator, call, nullAs) -> {
+        final RexCall call2 = call2(false, translator, call);
+        return implementCall(
+            translator, call2, implementor, nullAs);
       };
     default:
       throw new AssertionError(nullPolicy);
@@ -1383,9 +1355,9 @@ public class RexImpTable {
 
     @Override public List<Type> getNotNullState(AggContext info) {
       if (afi.isStatic) {
-        return Collections.<Type>singletonList(afi.accumulatorType);
+        return Collections.singletonList(afi.accumulatorType);
       }
-      return Arrays.<Type>asList(afi.accumulatorType, afi.declaringClass);
+      return Arrays.asList(afi.accumulatorType, afi.declaringClass);
     }
 
     @Override protected void implementNotNullReset(AggContext info,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/RexToLixTranslator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexToLixTranslator.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexToLixTranslator.java
index f131cf8..0c460d3 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexToLixTranslator.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexToLixTranslator.java
@@ -75,7 +75,7 @@ import static org.apache.calcite.sql.fun.SqlStdOperatorTable.UPPER;
  */
 public class RexToLixTranslator {
   public static final Map<Method, SqlOperator> JAVA_TO_SQL_METHOD_MAP =
-      Util.<Method, SqlOperator>mapOf(
+      Util.mapOf(
           findMethod(String.class, "toUpperCase"), UPPER,
           findMethod(
               SqlFunctions.class, "substring", String.class, Integer.TYPE,
@@ -109,7 +109,7 @@ public class RexToLixTranslator {
   private RexToLixTranslator(RexProgram program, JavaTypeFactory typeFactory,
       Expression root, InputGetter inputGetter, BlockBuilder list) {
     this(program, typeFactory, root, inputGetter, list,
-        Collections.<RexNode, Boolean>emptyMap(),
+        Collections.emptyMap(),
         new RexBuilder(typeFactory));
   }
 
@@ -1223,7 +1223,7 @@ public class RexToLixTranslator {
       return this;
     }
     return new RexToLixTranslator(program, typeFactory, root, inputGetter,
-        block, ImmutableMap.<RexNode, Boolean>of(), builder, this, correlates);
+        block, ImmutableMap.of(), builder, this, correlates);
   }
 
   public RexToLixTranslator setCorrelates(
@@ -1232,7 +1232,7 @@ public class RexToLixTranslator {
       return this;
     }
     return new RexToLixTranslator(program, typeFactory, root, inputGetter, list,
-        Collections.<RexNode, Boolean>emptyMap(), builder, this, correlates);
+        Collections.emptyMap(), builder, this, correlates);
   }
 
   public RelDataType nullifyType(RelDataType type, boolean nullable) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggAddContextImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggAddContextImpl.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggAddContextImpl.java
index 9932cab..69b4788 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggAddContextImpl.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggAddContextImpl.java
@@ -24,9 +24,8 @@ import org.apache.calcite.linq4j.tree.BlockBuilder;
 import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
 
-import com.google.common.base.Function;
-
 import java.util.List;
+import java.util.function.Function;
 
 /**
  * Implementation of
@@ -39,6 +38,13 @@ public abstract class WinAggAddContextImpl extends WinAggResultContextImpl
     super(block, accumulator, frame);
   }
 
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public WinAggAddContextImpl(BlockBuilder block, List<Expression> accumulator,
+      com.google.common.base.Function<BlockBuilder, WinAggFrameResultContext> frame) {
+    this(block, accumulator, (Function<BlockBuilder, WinAggFrameResultContext>) frame::apply);
+  }
+
   public final RexToLixTranslator rowTranslator() {
     return rowTranslator(
         computeIndex(Expressions.constant(0),

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggResultContextImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggResultContextImpl.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggResultContextImpl.java
index df0d639..a204c3b 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggResultContextImpl.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/impl/WinAggResultContextImpl.java
@@ -23,9 +23,8 @@ import org.apache.calcite.adapter.enumerable.WinAggResultContext;
 import org.apache.calcite.linq4j.tree.BlockBuilder;
 import org.apache.calcite.linq4j.tree.Expression;
 
-import com.google.common.base.Function;
-
 import java.util.List;
+import java.util.function.Function;
 
 /**
  * Implementation of
@@ -38,6 +37,7 @@ public abstract class WinAggResultContextImpl extends AggResultContextImpl
 
   /**
    * Creates window aggregate result context.
+   *
    * @param block code block that will contain the added initialization
    * @param accumulator accumulator variables that store the intermediate
    *                    aggregate state
@@ -49,6 +49,15 @@ public abstract class WinAggResultContextImpl extends AggResultContextImpl
     this.frame = frameContextBuilder;
   }
 
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public WinAggResultContextImpl(BlockBuilder block,
+      List<Expression> accumulator,
+      com.google.common.base.Function<BlockBuilder, WinAggFrameResultContext> frameContextBuilder) {
+    this(block, accumulator,
+        (Function<BlockBuilder, WinAggFrameResultContext>) frameContextBuilder::apply);
+  }
+
   private WinAggFrameResultContext getFrame() {
     return frame.apply(currentBlock());
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcRules.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcRules.java b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcRules.java
index 87658d5..9f152b4 100644
--- a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcRules.java
+++ b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcRules.java
@@ -61,7 +61,6 @@ import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexOver;
 import org.apache.calcite.rex.RexProgram;
 import org.apache.calcite.rex.RexVisitorImpl;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.ModifiableTable;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlDialect;
@@ -72,8 +71,6 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
 
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 
 import org.slf4j.Logger;
@@ -81,7 +78,7 @@ import org.slf4j.Logger;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
-import javax.annotation.Nullable;
+import java.util.function.Predicate;
 
 /**
  * Rules and relational operators for
@@ -100,7 +97,7 @@ public class JdbcRules {
 
   public static List<RelOptRule> rules(JdbcConvention out,
       RelBuilderFactory relBuilderFactory) {
-    return ImmutableList.<RelOptRule>of(
+    return ImmutableList.of(
         new JdbcToEnumerableConverterRule(out, relBuilderFactory),
         new JdbcJoinRule(out, relBuilderFactory),
         new JdbcCalcRule(out, relBuilderFactory),
@@ -119,10 +116,11 @@ public class JdbcRules {
   abstract static class JdbcConverterRule extends ConverterRule {
     protected final JdbcConvention out;
 
+    @SuppressWarnings("unchecked")
     @Deprecated // to be removed before 2.0
     JdbcConverterRule(Class<? extends RelNode> clazz, RelTrait in,
         JdbcConvention out, String description) {
-      this(clazz, Predicates.<RelNode>alwaysTrue(), in, out,
+      this(clazz, (Predicate<RelNode>) r -> true, in, out,
           RelFactories.LOGICAL_BUILDER, description);
     }
 
@@ -132,6 +130,16 @@ public class JdbcRules {
       super(clazz, predicate, in, out, relBuilderFactory, description);
       this.out = out;
     }
+
+    @SuppressWarnings({"Guava", "unchecked"})
+    @Deprecated // to be removed before 2.0
+    <R extends RelNode> JdbcConverterRule(Class<R> clazz,
+        com.google.common.base.Predicate<? super R> predicate,
+        RelTrait in, JdbcConvention out,
+        RelBuilderFactory relBuilderFactory, String description) {
+      this(clazz, (Predicate<R>) predicate, in, out, relBuilderFactory,
+          description);
+    }
   }
 
   /** Rule that converts a join to JDBC. */
@@ -144,7 +152,7 @@ public class JdbcRules {
     /** Creates a JdbcJoinRule. */
     public JdbcJoinRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Join.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+      super(Join.class, (Predicate<RelNode>) r -> true, Convention.NONE,
           out, relBuilderFactory, "JdbcJoinRule");
     }
 
@@ -299,7 +307,7 @@ public class JdbcRules {
     /** Creates a JdbcCalcRule. */
     private JdbcCalcRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Calc.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+      super(Calc.class, (Predicate<RelNode>) r -> true, Convention.NONE,
           out, relBuilderFactory, "JdbcCalcRule");
     }
 
@@ -380,16 +388,10 @@ public class JdbcRules {
     /** Creates a JdbcProjectRule. */
     public JdbcProjectRule(final JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Project.class,
-          new PredicateImpl<Project>() {
-            public boolean test(@Nullable Project project) {
-              assert project != null;
-              return (out.dialect.supportsWindowFunctions()
+      super(Project.class, (Predicate<Project>) project ->
+              (out.dialect.supportsWindowFunctions()
                   || !RexOver.containsOver(project.getProjects(), null))
-                  && !userDefinedFunctionInProject(project);
-            }
-
-          },
+                  && !userDefinedFunctionInProject(project),
           Convention.NONE, out, relBuilderFactory, "JdbcProjectRule");
     }
 
@@ -469,17 +471,9 @@ public class JdbcRules {
     /** Creates a JdbcFilterRule. */
     public JdbcFilterRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(
-        Filter.class,
-        new PredicateImpl<Filter>() {
-          @Override public boolean test(Filter filter) {
-            return !userDefinedFunctionInFilter(filter);
-          }
-        },
-        Convention.NONE,
-        out,
-        relBuilderFactory,
-        "JdbcFilterRule");
+      super(Filter.class,
+          (Predicate<Filter>) r -> !userDefinedFunctionInFilter(r),
+          Convention.NONE, out, relBuilderFactory, "JdbcFilterRule");
     }
 
     private static boolean userDefinedFunctionInFilter(Filter filter) {
@@ -535,7 +529,7 @@ public class JdbcRules {
     /** Creates a JdbcAggregateRule. */
     public JdbcAggregateRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Aggregate.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+      super(Aggregate.class, (Predicate<RelNode>) r -> true, Convention.NONE,
           out, relBuilderFactory, "JdbcAggregateRule");
     }
 
@@ -620,7 +614,7 @@ public class JdbcRules {
     /** Creates a JdbcSortRule. */
     public JdbcSortRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Sort.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE, out,
+      super(Sort.class, (Predicate<RelNode>) r -> true, Convention.NONE, out,
           relBuilderFactory, "JdbcSortRule");
     }
 
@@ -691,7 +685,7 @@ public class JdbcRules {
     /** Creates a JdbcUnionRule. */
     public JdbcUnionRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Union.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE, out,
+      super(Union.class, (Predicate<RelNode>) r -> true, Convention.NONE, out,
           relBuilderFactory, "JdbcUnionRule");
     }
 
@@ -737,7 +731,7 @@ public class JdbcRules {
     /** Creates a JdbcIntersectRule. */
     private JdbcIntersectRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Intersect.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+      super(Intersect.class, (Predicate<RelNode>) r -> true, Convention.NONE,
           out, relBuilderFactory, "JdbcIntersectRule");
     }
 
@@ -784,7 +778,7 @@ public class JdbcRules {
     /** Creates a JdbcMinusRule. */
     private JdbcMinusRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Minus.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE, out,
+      super(Minus.class, (Predicate<RelNode>) r -> true, Convention.NONE, out,
           relBuilderFactory, "JdbcMinusRule");
     }
 
@@ -823,7 +817,7 @@ public class JdbcRules {
     /** Creates a JdbcTableModificationRule. */
     private JdbcTableModificationRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(TableModify.class, Predicates.<RelNode>alwaysTrue(),
+      super(TableModify.class, (Predicate<RelNode>) r -> true,
           Convention.NONE, out, relBuilderFactory, "JdbcTableModificationRule");
     }
 
@@ -899,7 +893,7 @@ public class JdbcRules {
     /** Creates a JdbcValuesRule. */
     private JdbcValuesRule(JdbcConvention out,
         RelBuilderFactory relBuilderFactory) {
-      super(Values.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+      super(Values.class, (Predicate<RelNode>) r -> true, Convention.NONE,
           out, relBuilderFactory, "JdbcValuesRule");
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcSchema.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcSchema.java b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcSchema.java
index 52dd865..37893d7 100644
--- a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcSchema.java
+++ b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcSchema.java
@@ -38,7 +38,6 @@ import org.apache.calcite.sql.type.SqlTypeFactoryImpl;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableMultimap;
 import com.google.common.collect.ImmutableSet;
@@ -52,6 +51,7 @@ import java.sql.Statement;
 import java.util.Collection;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import javax.sql.DataSource;
 
@@ -89,8 +89,8 @@ public class JdbcSchema implements Schema {
       JdbcConvention convention, String catalog, String schema,
       ImmutableMap<String, JdbcTable> tableMap) {
     super();
-    this.dataSource = Preconditions.checkNotNull(dataSource);
-    this.dialect = Preconditions.checkNotNull(dialect);
+    this.dataSource = Objects.requireNonNull(dataSource);
+    this.dialect = Objects.requireNonNull(dialect);
     this.convention = convention;
     this.catalog = catalog;
     this.schema = schema;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTable.java b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTable.java
index 02b6207..7a356fa 100644
--- a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTable.java
@@ -35,7 +35,6 @@ import org.apache.calcite.rel.core.TableModify.Operation;
 import org.apache.calcite.rel.logical.LogicalTableModify;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
-import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rel.type.RelProtoDataType;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.runtime.ResultSetEnumerable;
@@ -54,8 +53,6 @@ import org.apache.calcite.sql.util.SqlString;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
 import java.sql.SQLException;
@@ -63,6 +60,7 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Queryable that gets its data from a table within a JDBC connection.
@@ -90,7 +88,7 @@ public class JdbcTable extends AbstractQueryableTable
     this.jdbcCatalogName = jdbcCatalogName;
     this.jdbcSchemaName = jdbcSchemaName;
     this.jdbcTableName = tableName;
-    this.jdbcTableType = Preconditions.checkNotNull(jdbcTableType);
+    this.jdbcTableType = Objects.requireNonNull(jdbcTableType);
   }
 
   public String toString() {
@@ -121,17 +119,14 @@ public class JdbcTable extends AbstractQueryableTable
   private List<Pair<ColumnMetaData.Rep, Integer>> fieldClasses(
       final JavaTypeFactory typeFactory) {
     final RelDataType rowType = protoRowType.apply(typeFactory);
-    return Lists.transform(rowType.getFieldList(),
-        new Function<RelDataTypeField, Pair<ColumnMetaData.Rep, Integer>>() {
-          public Pair<ColumnMetaData.Rep, Integer> apply(RelDataTypeField f) {
-            final RelDataType type = f.getType();
-            final Class clazz = (Class) typeFactory.getJavaClass(type);
-            final ColumnMetaData.Rep rep =
-                Util.first(ColumnMetaData.Rep.of(clazz),
-                    ColumnMetaData.Rep.OBJECT);
-            return Pair.of(rep, type.getSqlTypeName().getJdbcOrdinal());
-          }
-        });
+    return Lists.transform(rowType.getFieldList(), f -> {
+      final RelDataType type = f.getType();
+      final Class clazz = (Class) typeFactory.getJavaClass(type);
+      final ColumnMetaData.Rep rep =
+          Util.first(ColumnMetaData.Rep.of(clazz),
+              ColumnMetaData.Rep.OBJECT);
+      return Pair.of(rep, type.getSqlTypeName().getJdbcOrdinal());
+    });
   }
 
   SqlString generateSql() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcToEnumerableConverterRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcToEnumerableConverterRule.java b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcToEnumerableConverterRule.java
index e5eec50..e685922 100644
--- a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcToEnumerableConverterRule.java
+++ b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcToEnumerableConverterRule.java
@@ -22,7 +22,7 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.convert.ConverterRule;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicates;
+import java.util.function.Predicate;
 
 /**
  * Rule to convert a relational expression from
@@ -33,7 +33,7 @@ public class JdbcToEnumerableConverterRule extends ConverterRule {
   /** Creates a JdbcToEnumerableConverterRule. */
   public JdbcToEnumerableConverterRule(JdbcConvention out,
       RelBuilderFactory relBuilderFactory) {
-    super(RelNode.class, Predicates.<RelNode>alwaysTrue(), out,
+    super(RelNode.class, (Predicate<RelNode>) r -> true, out,
         EnumerableConvention.INSTANCE, relBuilderFactory,
         "JdbcToEnumerableConverterRule:" + out);
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcUtils.java b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcUtils.java
index 113b88a..7d5b8da 100644
--- a/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcUtils.java
+++ b/core/src/main/java/org/apache/calcite/adapter/jdbc/JdbcUtils.java
@@ -127,16 +127,14 @@ final class JdbcUtils {
 
     public static Function1<ResultSet, Function0<Object[]>> factory(
         final List<Pair<ColumnMetaData.Rep, Integer>> list) {
-      return new Function1<ResultSet, Function0<Object[]>>() {
-        public Function0<Object[]> apply(ResultSet resultSet) {
-          try {
-            return new ObjectArrayRowBuilder(
-                resultSet,
-                Pair.left(list).toArray(new ColumnMetaData.Rep[list.size()]),
-                Ints.toArray(Pair.right(list)));
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
+      return resultSet -> {
+        try {
+          return new ObjectArrayRowBuilder(
+              resultSet,
+              Pair.left(list).toArray(new ColumnMetaData.Rep[list.size()]),
+              Ints.toArray(Pair.right(list)));
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
         }
       };
     }
@@ -212,17 +210,18 @@ final class JdbcUtils {
     public static final DataSourcePool INSTANCE = new DataSourcePool();
 
     private final LoadingCache<List<String>, BasicDataSource> cache =
-        CacheBuilder.newBuilder().softValues().build(
-            new CacheLoader<List<String>, BasicDataSource>() {
-              @Override public BasicDataSource load(@Nonnull List<String> key) {
-                BasicDataSource dataSource = new BasicDataSource();
-                dataSource.setUrl(key.get(0));
-                dataSource.setUsername(key.get(1));
-                dataSource.setPassword(key.get(2));
-                dataSource.setDriverClassName(key.get(3));
-                return dataSource;
-              }
-            });
+        CacheBuilder.newBuilder().softValues()
+            .build(CacheLoader.from(DataSourcePool::dataSource));
+
+    private static @Nonnull BasicDataSource dataSource(
+          @Nonnull List<String> key) {
+      BasicDataSource dataSource = new BasicDataSource();
+      dataSource.setUrl(key.get(0));
+      dataSource.setUsername(key.get(1));
+      dataSource.setPassword(key.get(2));
+      dataSource.setDriverClassName(key.get(3));
+      return dataSource;
+    }
 
     public DataSource get(String url, String driverClassName,
         String username, String password) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/config/CalciteConnectionConfigImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/config/CalciteConnectionConfigImpl.java b/core/src/main/java/org/apache/calcite/config/CalciteConnectionConfigImpl.java
index bf057cb..6c176b8 100644
--- a/core/src/main/java/org/apache/calcite/config/CalciteConnectionConfigImpl.java
+++ b/core/src/main/java/org/apache/calcite/config/CalciteConnectionConfigImpl.java
@@ -99,7 +99,7 @@ public class CalciteConnectionConfigImpl extends ConnectionConfigImpl
     tables.add(SqlStdOperatorTable.instance());
     return operatorTableClass.cast(
         ChainedSqlOperatorTable.of(
-            tables.toArray(new SqlOperatorTable[tables.size()])));
+            tables.toArray(new SqlOperatorTable[0])));
   }
 
   private static void operatorTable(String s,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/AggregateNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/AggregateNode.java b/core/src/main/java/org/apache/calcite/interpreter/AggregateNode.java
index 390849c..c547dfc 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/AggregateNode.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/AggregateNode.java
@@ -40,25 +40,24 @@ import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.function.BiFunction;
+import java.util.function.Supplier;
 
 /**
  * Interpreter node that implements an
  * {@link org.apache.calcite.rel.core.Aggregate}.
  */
 public class AggregateNode extends AbstractSingleNode<Aggregate> {
-  private final List<Grouping> groups = Lists.newArrayList();
+  private final List<Grouping> groups = new ArrayList<>();
   private final ImmutableBitSet unionGroups;
   private final int outputRowLength;
   private final ImmutableList<AccumulatorFactory> accumulatorFactories;
@@ -106,19 +105,13 @@ public class AggregateNode extends AbstractSingleNode<Aggregate> {
       boolean ignoreFilter) {
     if (call.filterArg >= 0 && !ignoreFilter) {
       final AccumulatorFactory factory = getAccumulator(call, true);
-      return new AccumulatorFactory() {
-        public Accumulator get() {
-          final Accumulator accumulator = factory.get();
-          return new FilterAccumulator(accumulator, call.filterArg);
-        }
+      return () -> {
+        final Accumulator accumulator = factory.get();
+        return new FilterAccumulator(accumulator, call.filterArg);
       };
     }
     if (call.getAggregation() == SqlStdOperatorTable.COUNT) {
-      return new AccumulatorFactory() {
-        public Accumulator get() {
-          return new CountAccumulator(call);
-        }
-      };
+      return () -> new CountAccumulator(call);
     } else if (call.getAggregation() == SqlStdOperatorTable.SUM
         || call.getAggregation() == SqlStdOperatorTable.SUM0) {
       final Class<?> clazz;
@@ -340,7 +333,7 @@ public class AggregateNode extends AbstractSingleNode<Aggregate> {
    */
   private class Grouping {
     private final ImmutableBitSet grouping;
-    private final Map<Row, AccumulatorList> accumulators = Maps.newHashMap();
+    private final Map<Row, AccumulatorList> accumulators = new HashMap<>();
 
     private Grouping(ImmutableBitSet grouping) {
       this.grouping = grouping;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/Bindables.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/Bindables.java b/core/src/main/java/org/apache/calcite/interpreter/Bindables.java
index a26325e..c7df83b 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/Bindables.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/Bindables.java
@@ -72,12 +72,12 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.ImmutableIntList;
 
 import com.google.common.base.Preconditions;
-import com.google.common.base.Predicates;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
+import java.util.function.Predicate;
 
 /**
  * Utilities pertaining to {@link BindableRel} and {@link BindableConvention}.
@@ -174,15 +174,15 @@ public class Bindables {
         RelOptTable table, ImmutableList<RexNode> filters,
         ImmutableIntList projects) {
       super(cluster, traitSet, table);
-      this.filters = Preconditions.checkNotNull(filters);
-      this.projects = Preconditions.checkNotNull(projects);
+      this.filters = Objects.requireNonNull(filters);
+      this.projects = Objects.requireNonNull(projects);
       Preconditions.checkArgument(canHandle(table));
     }
 
     /** Creates a BindableTableScan. */
     public static BindableTableScan create(RelOptCluster cluster,
         RelOptTable relOptTable) {
-      return create(cluster, relOptTable, ImmutableList.<RexNode>of(),
+      return create(cluster, relOptTable, ImmutableList.of(),
           identity(relOptTable));
     }
 
@@ -193,15 +193,12 @@ public class Bindables {
       final Table table = relOptTable.unwrap(Table.class);
       final RelTraitSet traitSet =
           cluster.traitSetOf(BindableConvention.INSTANCE)
-              .replaceIfs(RelCollationTraitDef.INSTANCE,
-                  new Supplier<List<RelCollation>>() {
-                    public List<RelCollation> get() {
-                      if (table != null) {
-                        return table.getStatistic().getCollations();
-                      }
-                      return ImmutableList.of();
-                    }
-                  });
+              .replaceIfs(RelCollationTraitDef.INSTANCE, () -> {
+                if (table != null) {
+                  return table.getStatistic().getCollations();
+                }
+                return ImmutableList.of();
+              });
       return new BindableTableScan(cluster, traitSet, relOptTable,
           ImmutableList.copyOf(filters), ImmutableIntList.copyOf(projects));
     }
@@ -268,8 +265,10 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableFilterRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalFilter.class, RelOptUtil.FILTER_PREDICATE, Convention.NONE,
-          BindableConvention.INSTANCE, relBuilderFactory, "BindableFilterRule");
+      super(LogicalFilter.class,
+          (Predicate<LogicalFilter>) RelOptUtil::containsMultisetOrWindowedAgg,
+          Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
+          "BindableFilterRule");
     }
 
     public RelNode convert(RelNode rel) {
@@ -299,11 +298,7 @@ public class Bindables {
       final RelTraitSet traitSet =
           cluster.traitSetOf(BindableConvention.INSTANCE)
               .replaceIfs(RelCollationTraitDef.INSTANCE,
-                  new Supplier<List<RelCollation>>() {
-                    public List<RelCollation> get() {
-                      return RelMdCollation.filter(mq, input);
-                    }
-                  });
+                  () -> RelMdCollation.filter(mq, input));
       return new BindableFilter(cluster, traitSet, input, condition);
     }
 
@@ -337,8 +332,9 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableProjectRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalProject.class, RelOptUtil.PROJECT_PREDICATE, Convention.NONE,
-          BindableConvention.INSTANCE, relBuilderFactory,
+      super(LogicalProject.class,
+          (Predicate<LogicalProject>) RelOptUtil::containsMultisetOrWindowedAgg,
+          Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
           "BindableProjectRule");
     }
 
@@ -394,7 +390,7 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableSortRule(RelBuilderFactory relBuilderFactory) {
-      super(Sort.class, Predicates.<RelNode>alwaysTrue(), Convention.NONE,
+      super(Sort.class, (Predicate<RelNode>) r -> true, Convention.NONE,
           BindableConvention.INSTANCE, relBuilderFactory, "BindableSortRule");
     }
 
@@ -450,7 +446,7 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableJoinRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalJoin.class, Predicates.<RelNode>alwaysTrue(),
+      super(LogicalJoin.class, (Predicate<RelNode>) r -> true,
           Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
           "BindableJoinRule");
     }
@@ -520,7 +516,7 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableUnionRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalUnion.class, Predicates.<RelNode>alwaysTrue(),
+      super(LogicalUnion.class, (Predicate<RelNode>) r -> true,
           Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
           "BindableUnionRule");
     }
@@ -595,7 +591,7 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableValuesRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalValues.class, Predicates.<RelNode>alwaysTrue(),
+      super(LogicalValues.class, (Predicate<RelNode>) r -> true,
           Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
           "BindableValuesRule");
     }
@@ -673,7 +669,7 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableAggregateRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalAggregate.class, Predicates.<RelNode>alwaysTrue(),
+      super(LogicalAggregate.class, (Predicate<RelNode>) r -> true,
           Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
           "BindableAggregateRule");
     }
@@ -738,7 +734,7 @@ public class Bindables {
      * @param relBuilderFactory Builder for relational expressions
      */
     public BindableWindowRule(RelBuilderFactory relBuilderFactory) {
-      super(LogicalWindow.class, Predicates.<RelNode>alwaysTrue(),
+      super(LogicalWindow.class, (Predicate<RelNode>) r -> true,
           Convention.NONE, BindableConvention.INSTANCE, relBuilderFactory,
           "BindableWindowRule");
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/interpreter/InterpretableRel.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/interpreter/InterpretableRel.java b/core/src/main/java/org/apache/calcite/interpreter/InterpretableRel.java
index 42276ac..2fee43d 100644
--- a/core/src/main/java/org/apache/calcite/interpreter/InterpretableRel.java
+++ b/core/src/main/java/org/apache/calcite/interpreter/InterpretableRel.java
@@ -20,8 +20,8 @@ import org.apache.calcite.DataContext;
 import org.apache.calcite.jdbc.CalcitePrepare;
 import org.apache.calcite.rel.RelNode;
 
-import com.google.common.collect.Maps;
-
+import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -37,10 +37,10 @@ public interface InterpretableRel extends RelNode {
   class InterpreterImplementor {
     public final Compiler compiler;
     public final Map<String, Object> internalParameters =
-        Maps.newLinkedHashMap();
+        new LinkedHashMap<>();
     public final CalcitePrepare.SparkHandler spark;
     public final DataContext dataContext;
-    public final Map<RelNode, List<Sink>> relSinks = Maps.newHashMap();
+    public final Map<RelNode, List<Sink>> relSinks = new HashMap<>();
 
     public InterpreterImplementor(Compiler compiler,
         CalcitePrepare.SparkHandler spark,


[27/30] calcite git commit: [CALCITE-2398] SqlSelect must call into SqlDialect for unparse (James Duong)

Posted by jh...@apache.org.
[CALCITE-2398] SqlSelect must call into SqlDialect for unparse (James Duong)

Close apache/calcite#750


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/606240d4
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/606240d4
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/606240d4

Branch: refs/heads/master
Commit: 606240d4f1e39ab36447a9b4abe20c6c519d5cab
Parents: 870e54f
Author: James Duong <jd...@dremio.com>
Authored: Tue Jul 3 16:42:18 2018 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:41:09 2018 -0700

----------------------------------------------------------------------
 .../java/org/apache/calcite/sql/SqlSelect.java  |  4 ++--
 .../rel/rel2sql/RelToSqlConverterTest.java      | 24 ++++++++++++++++++++
 2 files changed, 26 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/606240d4/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlSelect.java b/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
index ad7d6ef..2c23774 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
@@ -233,10 +233,10 @@ public class SqlSelect extends SqlCall {
       // ORDER. In this case, we don't need a wrapper frame.)
       final SqlWriter.Frame frame =
           writer.startList(SqlWriter.FrameTypeEnum.SUB_QUERY, "(", ")");
-      getOperator().unparse(writer, this, 0, 0);
+      writer.getDialect().unparseCall(writer, this, 0, 0);
       writer.endList(frame);
     } else {
-      getOperator().unparse(writer, this, leftPrec, rightPrec);
+      writer.getDialect().unparseCall(writer, this, leftPrec, rightPrec);
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/606240d4/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
index 53ba8a9..c5af61a 100644
--- a/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
+++ b/core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java
@@ -26,9 +26,12 @@ import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.rules.UnionMergeRule;
 import org.apache.calcite.runtime.FlatLists;
 import org.apache.calcite.schema.SchemaPlus;
+import org.apache.calcite.sql.SqlCall;
 import org.apache.calcite.sql.SqlDialect;
 import org.apache.calcite.sql.SqlDialect.Context;
 import org.apache.calcite.sql.SqlNode;
+import org.apache.calcite.sql.SqlSelect;
+import org.apache.calcite.sql.SqlWriter;
 import org.apache.calcite.sql.dialect.CalciteSqlDialect;
 import org.apache.calcite.sql.dialect.HiveSqlDialect;
 import org.apache.calcite.sql.dialect.JethroDataSqlDialect;
@@ -2514,6 +2517,27 @@ public class RelToSqlConverterTest {
     sql(query).ok(expected);
   }
 
+  @Test public void testUnparseSelectMustUseDialect() {
+    final String query = "select * from \"product\"";
+    final String expected = "SELECT *\n"
+        + "FROM foodmart.product";
+
+    final boolean[] callsUnparseCallOnSqlSelect = {false};
+    final SqlDialect dialect = new SqlDialect(SqlDialect.EMPTY_CONTEXT) {
+      @Override public void unparseCall(SqlWriter writer, SqlCall call,
+          int leftPrec, int rightPrec) {
+        if (call instanceof SqlSelect) {
+          callsUnparseCallOnSqlSelect[0] = true;
+        }
+        super.unparseCall(writer, call, leftPrec, rightPrec);
+      }
+    };
+    sql(query).dialect(dialect).ok(expected);
+
+    assertThat("Dialect must be able to customize unparseCall() for SqlSelect",
+        callsUnparseCallOnSqlSelect[0], is(true));
+  }
+
   /** Fluid interface to run tests. */
   private static class Sql {
     private CalciteAssert.SchemaSpec schemaSpec;


[16/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexUtil.java b/core/src/main/java/org/apache/calcite/rex/RexUtil.java
index 1e0fb15..29e63f1 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexUtil.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexUtil.java
@@ -30,7 +30,6 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeFamily;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexTableInputRef.RelTableRef;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.Schemas;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlKind;
@@ -46,15 +45,10 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -66,6 +60,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.function.Predicate;
 import javax.annotation.Nonnull;
 
 /**
@@ -73,42 +68,6 @@ import javax.annotation.Nonnull;
  */
 public class RexUtil {
 
-  private static final Function<? super RexNode, ? extends RexNode> ADD_NOT =
-      new Function<RexNode, RexNode>() {
-        public RexNode apply(RexNode input) {
-          return new RexCall(input.getType(), SqlStdOperatorTable.NOT,
-              ImmutableList.of(input));
-        }
-      };
-
-  private static final Predicate1<RexNode> IS_FLAT_PREDICATE =
-      new Predicate1<RexNode>() {
-        public boolean apply(RexNode v1) {
-          return isFlat(v1);
-        }
-      };
-
-  private static final Function<Object, String> TO_STRING =
-      new Function<Object, String>() {
-        public String apply(Object input) {
-          return input.toString();
-        }
-      };
-
-  private static final Function<RexNode, RelDataType> TYPE_FN =
-      new Function<RexNode, RelDataType>() {
-        public RelDataType apply(RexNode input) {
-          return input.getType();
-        }
-      };
-
-  private static final Function<RelDataType, RelDataTypeFamily> FAMILY_FN =
-      new Function<RelDataType, RelDataTypeFamily>() {
-        public RelDataTypeFamily apply(RelDataType input) {
-          return input.getFamily();
-        }
-      };
-
   /** Executor for a bit of constant reduction. The user can pass in another executor. */
   public static final RexExecutor EXECUTOR =
       new RexExecutorImpl(Schemas.createDataContext(null, null));
@@ -593,7 +552,7 @@ public class RexUtil {
   }
 
   public static List<RexNode> retainDeterministic(List<RexNode> list) {
-    List<RexNode> conjuctions = Lists.newArrayList();
+    List<RexNode> conjuctions = new ArrayList<>();
     for (RexNode x : list) {
       if (isDeterministic(x)) {
         conjuctions.add(x);
@@ -1083,7 +1042,7 @@ public class RexUtil {
       return ImmutableList.of();
     }
     final ImmutableList.Builder<RexNode> builder = ImmutableList.builder();
-    final Set<String> digests = Sets.newHashSet(); // to eliminate duplicates
+    final Set<String> digests = new HashSet<>(); // to eliminate duplicates
     for (RexNode node : nodes) {
       if (node != null) {
         addAnd(builder, digests, node);
@@ -1117,7 +1076,7 @@ public class RexUtil {
   @Nonnull public static RexNode composeDisjunction(RexBuilder rexBuilder,
       Iterable<? extends RexNode> nodes) {
     final RexNode e = composeDisjunction(rexBuilder, nodes, false);
-    return Preconditions.checkNotNull(e);
+    return Objects.requireNonNull(e);
   }
 
   /**
@@ -1147,7 +1106,7 @@ public class RexUtil {
       return ImmutableList.of();
     }
     final ImmutableList.Builder<RexNode> builder = ImmutableList.builder();
-    final Set<String> digests = Sets.newHashSet(); // to eliminate duplicates
+    final Set<String> digests = new HashSet<>(); // to eliminate duplicates
     for (RexNode node : nodes) {
       addOr(builder, digests, node);
     }
@@ -1279,12 +1238,7 @@ public class RexUtil {
   public static Iterable<RexNode> apply(Mappings.TargetMapping mapping,
       Iterable<? extends RexNode> nodes) {
     final RexPermuteInputsShuttle shuttle = RexPermuteInputsShuttle.of(mapping);
-    return Iterables.transform(
-        nodes, new Function<RexNode, RexNode>() {
-          public RexNode apply(RexNode input) {
-            return input.accept(shuttle);
-          }
-        });
+    return Iterables.transform(nodes, e -> e.accept(shuttle));
   }
 
   /**
@@ -1386,12 +1340,7 @@ public class RexUtil {
   private static boolean isFlat(
       List<? extends RexNode> exprs, final SqlOperator op) {
     return !isAssociative(op)
-        || !exists(exprs,
-            new Predicate1<RexNode>() {
-              public boolean apply(RexNode expr) {
-                return isCallTo(expr, op);
-              }
-            });
+        || !exists(exprs, (Predicate1<RexNode>) expr -> isCallTo(expr, op));
   }
 
   /**
@@ -1404,7 +1353,7 @@ public class RexUtil {
     }
     final RexCall call = (RexCall) expr;
     return isFlat(call.getOperands(), call.getOperator())
-        && all(call.getOperands(), IS_FLAT_PREDICATE);
+        && all(call.getOperands(), RexUtil::isFlat);
   }
 
   private static void flattenRecurse(
@@ -1658,11 +1607,11 @@ public class RexUtil {
 
   /** Transforms a list of expressions into a list of their types. */
   public static List<RelDataType> types(List<? extends RexNode> nodes) {
-    return Lists.transform(nodes, TYPE_FN);
+    return Lists.transform(nodes, RexNode::getType);
   }
 
   public static List<RelDataTypeFamily> families(List<RelDataType> types) {
-    return Lists.transform(types, FAMILY_FN);
+    return Lists.transform(types, RelDataType::getFamily);
   }
 
   /** Removes all expressions from a list that are equivalent to a given
@@ -1774,11 +1723,15 @@ public class RexUtil {
     case NOT:
       return ((RexCall) e).getOperands().get(0);
     default:
-      return new RexCall(e.getType(), SqlStdOperatorTable.NOT,
-          ImmutableList.of(e));
+      return addNot(e);
     }
   }
 
+  private static RexNode addNot(RexNode e) {
+    return new RexCall(e.getType(), SqlStdOperatorTable.NOT,
+        ImmutableList.of(e));
+  }
+
   static SqlOperator op(SqlKind kind) {
     switch (kind) {
     case IS_FALSE:
@@ -1903,25 +1856,23 @@ public class RexUtil {
       final RexCall call = (RexCall) e;
       if (call.getOperands().get(1) instanceof RexLiteral) {
         notTerms = Iterables.filter(notTerms,
-            new PredicateImpl<RexNode>() {
-              public boolean test(RexNode input) {
-                switch (input.getKind()) {
-                case EQUALS:
-                  RexCall call2 = (RexCall) input;
-                  if (call2.getOperands().get(0)
-                      .equals(call.getOperands().get(0))
-                      && call2.getOperands().get(1) instanceof RexLiteral) {
-                    return false;
-                  }
+            e2 -> {
+              switch (e2.getKind()) {
+              case EQUALS:
+                RexCall call2 = (RexCall) e2;
+                if (call2.getOperands().get(0)
+                    .equals(call.getOperands().get(0))
+                    && call2.getOperands().get(1) instanceof RexLiteral) {
+                  return false;
                 }
-                return true;
               }
+              return true;
             });
       }
     }
     return composeConjunction(rexBuilder,
         Iterables.concat(ImmutableList.of(e),
-            Iterables.transform(notTerms, notFn(rexBuilder))),
+            Iterables.transform(notTerms, e2 -> not(rexBuilder, e2))),
         false);
   }
 
@@ -1939,19 +1890,25 @@ public class RexUtil {
         && (call.operands.size() - i) % 2 == 1;
   }
 
-  /** Returns a function that applies NOT to its argument. */
-  public static Function<RexNode, RexNode> notFn(final RexBuilder rexBuilder) {
-    return new Function<RexNode, RexNode>() {
-      public RexNode apply(RexNode input) {
-        return input.isAlwaysTrue()
-            ? rexBuilder.makeLiteral(false)
-            : input.isAlwaysFalse()
-            ? rexBuilder.makeLiteral(true)
-            : input.getKind() == SqlKind.NOT
-            ? ((RexCall) input).operands.get(0)
-            : rexBuilder.makeCall(SqlStdOperatorTable.NOT, input);
-      }
-    };
+  /** Returns a function that applies NOT to its argument.
+   *
+   * @deprecated Use {@link #not} */
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed in 2.0
+  public static com.google.common.base.Function<RexNode, RexNode> notFn(
+      final RexBuilder rexBuilder) {
+    return e -> not(rexBuilder, e);
+  }
+
+  /** Applies NOT to an expression. */
+  static RexNode not(final RexBuilder rexBuilder, RexNode input) {
+    return input.isAlwaysTrue()
+        ? rexBuilder.makeLiteral(false)
+        : input.isAlwaysFalse()
+        ? rexBuilder.makeLiteral(true)
+        : input.getKind() == SqlKind.NOT
+        ? ((RexCall) input).operands.get(0)
+        : rexBuilder.makeCall(SqlStdOperatorTable.NOT, input);
   }
 
   /** Returns whether an expression contains a {@link RexCorrelVariable}. */
@@ -2250,7 +2207,7 @@ public class RexUtil {
       case AND:
         incrementAndCheck();
         operands = flattenAnd(((RexCall) rex).getOperands());
-        final List<RexNode> cnfOperands = Lists.newArrayList();
+        final List<RexNode> cnfOperands = new ArrayList<>();
         for (RexNode node : operands) {
           RexNode cnf = toCnf2(node);
           switch (cnf.getKind()) {
@@ -2273,7 +2230,7 @@ public class RexUtil {
         final RexNode tail = or(Util.skip(operands));
         final RexNode tailCnf = toCnf2(tail);
         final List<RexNode> tailCnfs = RelOptUtil.conjunctions(tailCnf);
-        final List<RexNode> list = Lists.newArrayList();
+        final List<RexNode> list = new ArrayList<>();
         for (RexNode h : headCnfs) {
           for (RexNode t : tailCnfs) {
             list.add(or(ImmutableList.of(h, t)));
@@ -2287,10 +2244,12 @@ public class RexUtil {
           return toCnf2(((RexCall) arg).getOperands().get(0));
         case OR:
           operands = ((RexCall) arg).getOperands();
-          return toCnf2(and(Lists.transform(flattenOr(operands), ADD_NOT)));
+          return toCnf2(
+              and(Lists.transform(flattenOr(operands), RexUtil::addNot)));
         case AND:
           operands = ((RexCall) arg).getOperands();
-          return toCnf2(or(Lists.transform(flattenAnd(operands), ADD_NOT)));
+          return toCnf2(
+              or(Lists.transform(flattenAnd(operands), RexUtil::addNot)));
         default:
           incrementAndCheck();
           return rex;
@@ -2328,7 +2287,7 @@ public class RexUtil {
         if (factors.isEmpty()) {
           return or(operands);
         }
-        final List<RexNode> list = Lists.newArrayList();
+        final List<RexNode> list = new ArrayList<>();
         for (RexNode operand : operands) {
           list.add(removeFactor(factors, operand));
         }
@@ -2339,7 +2298,7 @@ public class RexUtil {
     }
 
     private List<RexNode> pullList(List<RexNode> nodes) {
-      final List<RexNode> list = Lists.newArrayList();
+      final List<RexNode> list = new ArrayList<>();
       for (RexNode node : nodes) {
         RexNode pulled = pull(node);
         switch (pulled.getKind()) {
@@ -2354,7 +2313,7 @@ public class RexUtil {
     }
 
     private Map<String, RexNode> commonFactors(List<RexNode> nodes) {
-      final Map<String, RexNode> map = Maps.newHashMap();
+      final Map<String, RexNode> map = new HashMap<>();
       int i = 0;
       for (RexNode node : nodes) {
         if (i++ == 0) {
@@ -2369,7 +2328,7 @@ public class RexUtil {
     }
 
     private RexNode removeFactor(Map<String, RexNode> factors, RexNode node) {
-      List<RexNode> list = Lists.newArrayList();
+      List<RexNode> list = new ArrayList<>();
       for (RexNode operand : RelOptUtil.conjunctions(node)) {
         if (!factors.containsKey(operand.toString())) {
           list.add(operand);
@@ -2389,7 +2348,7 @@ public class RexUtil {
 
   /** Transforms a list of expressions to the list of digests. */
   public static List<String> strings(List<RexNode> list) {
-    return Lists.transform(list, TO_STRING);
+    return Lists.transform(list, Object::toString);
   }
 
   /** Helps {@link org.apache.calcite.rex.RexUtil#toDnf}. */
@@ -2411,7 +2370,7 @@ public class RexUtil {
         final RexNode tail = and(Util.skip(operands));
         final RexNode tailDnf = toDnf(tail);
         final List<RexNode> tailDnfs = RelOptUtil.disjunctions(tailDnf);
-        final List<RexNode> list = Lists.newArrayList();
+        final List<RexNode> list = new ArrayList<>();
         for (RexNode h : headDnfs) {
           for (RexNode t : tailDnfs) {
             list.add(and(ImmutableList.of(h, t)));
@@ -2428,10 +2387,12 @@ public class RexUtil {
           return toDnf(((RexCall) arg).getOperands().get(0));
         case OR:
           operands = ((RexCall) arg).getOperands();
-          return toDnf(and(Lists.transform(flattenOr(operands), ADD_NOT)));
+          return toDnf(
+              and(Lists.transform(flattenOr(operands), RexUtil::addNot)));
         case AND:
           operands = ((RexCall) arg).getOperands();
-          return toDnf(or(Lists.transform(flattenAnd(operands), ADD_NOT)));
+          return toDnf(
+              or(Lists.transform(flattenAnd(operands), RexUtil::addNot)));
         default:
           return rex;
         }
@@ -2441,7 +2402,7 @@ public class RexUtil {
     }
 
     private List<RexNode> toDnfs(List<RexNode> nodes) {
-      final List<RexNode> list = Lists.newArrayList();
+      final List<RexNode> list = new ArrayList<>();
       for (RexNode node : nodes) {
         RexNode dnf = toDnf(node);
         switch (dnf.getKind()) {
@@ -2526,51 +2487,57 @@ public class RexUtil {
   public static class SubQueryFinder extends RexVisitorImpl<Void> {
     public static final SubQueryFinder INSTANCE = new SubQueryFinder();
 
-    /** Returns whether a {@link Project} contains a sub-query. */
-    public static final Predicate<Project> PROJECT_PREDICATE =
-        new PredicateImpl<Project>() {
-          public boolean test(Project project) {
-            for (RexNode node : project.getProjects()) {
-              try {
-                node.accept(INSTANCE);
-              } catch (Util.FoundOne e) {
-                return true;
-              }
-            }
-            return false;
-          }
-        };
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed before 2.0
+    public static final com.google.common.base.Predicate<Project> PROJECT_PREDICATE =
+        SubQueryFinder::containsSubQuery;
 
-    /** Returns whether a {@link Filter} contains a sub-query. */
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed before 2.0
     public static final Predicate<Filter> FILTER_PREDICATE =
-        new PredicateImpl<Filter>() {
-          public boolean test(Filter filter) {
-            try {
-              filter.getCondition().accept(INSTANCE);
-              return false;
-            } catch (Util.FoundOne e) {
-              return true;
-            }
-          }
-        };
+        SubQueryFinder::containsSubQuery;
 
-    /** Returns whether a {@link Join} contains a sub-query. */
-    public static final Predicate<Join> JOIN_PREDICATE =
-        new PredicateImpl<Join>() {
-          public boolean test(Join join) {
-            try {
-              join.getCondition().accept(INSTANCE);
-              return false;
-            } catch (Util.FoundOne e) {
-              return true;
-            }
-          }
-        };
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed before 2.0
+    public static final com.google.common.base.Predicate<Join> JOIN_PREDICATE =
+        SubQueryFinder::containsSubQuery;
 
     private SubQueryFinder() {
       super(true);
     }
 
+    /** Returns whether a {@link Project} contains a sub-query. */
+    public static boolean containsSubQuery(Project project) {
+      for (RexNode node : project.getProjects()) {
+        try {
+          node.accept(INSTANCE);
+        } catch (Util.FoundOne e) {
+          return true;
+        }
+      }
+      return false;
+    }
+
+    /** Returns whether a {@link Filter} contains a sub-query. */
+    public static boolean containsSubQuery(Filter filter) {
+      try {
+        filter.getCondition().accept(INSTANCE);
+        return false;
+      } catch (Util.FoundOne e) {
+        return true;
+      }
+    }
+
+    /** Returns whether a {@link Join} contains a sub-query. */
+    public static boolean containsSubQuery(Join join) {
+      try {
+        join.getCondition().accept(INSTANCE);
+        return false;
+      } catch (Util.FoundOne e) {
+        return true;
+      }
+    }
+
     @Override public Void visitSubQuery(RexSubQuery subQuery) {
       throw new Util.FoundOne(subQuery);
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/BinarySearch.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/BinarySearch.java b/core/src/main/java/org/apache/calcite/runtime/BinarySearch.java
index 5311434..f78ffa0 100644
--- a/core/src/main/java/org/apache/calcite/runtime/BinarySearch.java
+++ b/core/src/main/java/org/apache/calcite/runtime/BinarySearch.java
@@ -49,7 +49,7 @@ public class BinarySearch {
    */
   public static <T> int lowerBound(T[] a, T key, Comparator<T> comparator) {
     return lowerBound(a, key, 0, a.length - 1,
-        Functions.<T>identitySelector(), comparator);
+        Functions.identitySelector(), comparator);
   }
 
   /**
@@ -68,7 +68,7 @@ public class BinarySearch {
    */
   public static <T> int upperBound(T[] a, T key, Comparator<T> comparator) {
     return upperBound(a, key, 0, a.length - 1,
-        Functions.<T>identitySelector(), comparator);
+        Functions.identitySelector(), comparator);
   }
 
   /**
@@ -136,7 +136,7 @@ public class BinarySearch {
   public static <T> int lowerBound(T[] a, T key, int imin, int imax,
       Comparator<T> comparator) {
     return lowerBound(a, key, imin, imax,
-        Functions.<T>identitySelector(), comparator);
+        Functions.identitySelector(), comparator);
   }
 
   /**
@@ -158,7 +158,7 @@ public class BinarySearch {
   public static <T> int upperBound(T[] a, T key, int imin, int imax,
       Comparator<T> comparator) {
     return upperBound(a, key, imin, imax,
-        Functions.<T>identitySelector(), comparator);
+        Functions.identitySelector(), comparator);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/Enumerables.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/Enumerables.java b/core/src/main/java/org/apache/calcite/runtime/Enumerables.java
index 5fbb268..62b7992 100644
--- a/core/src/main/java/org/apache/calcite/runtime/Enumerables.java
+++ b/core/src/main/java/org/apache/calcite/runtime/Enumerables.java
@@ -20,7 +20,7 @@ import org.apache.calcite.interpreter.Row;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.function.Function1;
 
-import com.google.common.base.Supplier;
+import java.util.function.Supplier;
 
 /**
  * Utilities for processing {@link org.apache.calcite.linq4j.Enumerable}
@@ -30,19 +30,6 @@ import com.google.common.base.Supplier;
  * Methods are subject to removal without notice.
  */
 public class Enumerables {
-  private static final Function1<?, ?> SLICE =
-      new Function1<Object[], Object>() {
-        public Object apply(Object[] a0) {
-          return a0[0];
-        }
-      };
-
-  private static final Function1<Object[], Row> ARRAY_TO_ROW =
-      new Function1<Object[], Row>() {
-        public Row apply(Object[] a0) {
-          return Row.asCopy(a0);
-        }
-      };
 
   private Enumerables() {}
 
@@ -50,24 +37,27 @@ public class Enumerables {
    * first elements. */
   public static <E> Enumerable<E> slice0(Enumerable<E[]> enumerable) {
     //noinspection unchecked
-    return enumerable.select((Function1<E[], E>) SLICE);
+    return enumerable.select(elements -> elements[0]);
   }
 
   /** Converts an {@link Enumerable} over object arrays into an
    * {@link Enumerable} over {@link Row} objects. */
   public static Enumerable<Row> toRow(final Enumerable<Object[]> enumerable) {
-    return enumerable.select(ARRAY_TO_ROW);
+    return enumerable.select((Function1<Object[], Row>) Row::asCopy);
   }
 
   /** Converts a supplier of an {@link Enumerable} over object arrays into a
    * supplier of an {@link Enumerable} over {@link Row} objects. */
   public static Supplier<Enumerable<Row>> toRow(
       final Supplier<Enumerable<Object[]>> supplier) {
-    return new Supplier<Enumerable<Row>>() {
-      public Enumerable<Row> get() {
-        return toRow(supplier.get());
-      }
-    };
+    return () -> toRow(supplier.get());
+  }
+
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static com.google.common.base.Supplier<Enumerable<Row>> toRow(
+      final com.google.common.base.Supplier<Enumerable<Object[]>> supplier) {
+    return () -> toRow(supplier.get());
   }
 
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/FlatLists.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/FlatLists.java b/core/src/main/java/org/apache/calcite/runtime/FlatLists.java
index 94cfce1..d07014a 100644
--- a/core/src/main/java/org/apache/calcite/runtime/FlatLists.java
+++ b/core/src/main/java/org/apache/calcite/runtime/FlatLists.java
@@ -372,6 +372,10 @@ public class FlatLists {
 
     @SuppressWarnings({"unchecked" })
     public <T2> T2[] toArray(T2[] a) {
+      if (a.length < 1) {
+        // Make a new array of a's runtime type, but my contents:
+        return (T2[]) Arrays.copyOf(toArray(), 1, a.getClass());
+      }
       a[0] = (T2) t0;
       return a;
     }
@@ -500,6 +504,10 @@ public class FlatLists {
 
     @SuppressWarnings({"unchecked" })
     public <T2> T2[] toArray(T2[] a) {
+      if (a.length < 2) {
+        // Make a new array of a's runtime type, but my contents:
+        return (T2[]) Arrays.copyOf(toArray(), 2, a.getClass());
+      }
       a[0] = (T2) t0;
       a[1] = (T2) t1;
       return a;
@@ -645,6 +653,10 @@ public class FlatLists {
 
     @SuppressWarnings({"unchecked" })
     public <T2> T2[] toArray(T2[] a) {
+      if (a.length < 3) {
+        // Make a new array of a's runtime type, but my contents:
+        return (T2[]) Arrays.copyOf(toArray(), 3, a.getClass());
+      }
       a[0] = (T2) t0;
       a[1] = (T2) t1;
       a[2] = (T2) t2;
@@ -809,6 +821,10 @@ public class FlatLists {
 
     @SuppressWarnings({"unchecked" })
     public <T2> T2[] toArray(T2[] a) {
+      if (a.length < 4) {
+        // Make a new array of a's runtime type, but my contents:
+        return (T2[]) Arrays.copyOf(toArray(), 4, a.getClass());
+      }
       a[0] = (T2) t0;
       a[1] = (T2) t1;
       a[2] = (T2) t2;
@@ -992,6 +1008,10 @@ public class FlatLists {
 
     @SuppressWarnings({"unchecked" })
     public <T2> T2[] toArray(T2[] a) {
+      if (a.length < 5) {
+        // Make a new array of a's runtime type, but my contents:
+        return (T2[]) Arrays.copyOf(toArray(), 5, a.getClass());
+      }
       a[0] = (T2) t0;
       a[1] = (T2) t1;
       a[2] = (T2) t2;
@@ -1195,6 +1215,10 @@ public class FlatLists {
 
     @SuppressWarnings({"unchecked" })
     public <T2> T2[] toArray(T2[] a) {
+      if (a.length < 6) {
+        // Make a new array of a's runtime type, but my contents:
+        return (T2[]) Arrays.copyOf(toArray(), 6, a.getClass());
+      }
       a[0] = (T2) t0;
       a[1] = (T2) t1;
       a[2] = (T2) t2;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/GeoFunctions.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/GeoFunctions.java b/core/src/main/java/org/apache/calcite/runtime/GeoFunctions.java
index 73884c0..3e258c9 100644
--- a/core/src/main/java/org/apache/calcite/runtime/GeoFunctions.java
+++ b/core/src/main/java/org/apache/calcite/runtime/GeoFunctions.java
@@ -38,9 +38,8 @@ import com.esri.core.geometry.SpatialReference;
 import com.esri.core.geometry.WktExportFlags;
 import com.esri.core.geometry.WktImportFlags;
 
-import com.google.common.base.Preconditions;
-
 import java.math.BigDecimal;
+import java.util.Objects;
 
 /**
  * Helper methods to implement Geo-spatial functions in generated code.
@@ -574,7 +573,7 @@ public class GeoFunctions {
     final Geometry g;
 
     SimpleGeom(Geometry g) {
-      this.g = Preconditions.checkNotNull(g);
+      this.g = Objects.requireNonNull(g);
     }
 
     @Override public String toString() {
@@ -606,7 +605,7 @@ public class GeoFunctions {
     final MapGeometry mg;
 
     MapGeom(MapGeometry mg) {
-      this.mg = Preconditions.checkNotNull(mg);
+      this.mg = Objects.requireNonNull(mg);
     }
 
     @Override public String toString() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/Hook.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/Hook.java b/core/src/main/java/org/apache/calcite/runtime/Hook.java
index 0cfbc01..10d4586 100644
--- a/core/src/main/java/org/apache/calcite/runtime/Hook.java
+++ b/core/src/main/java/org/apache/calcite/runtime/Hook.java
@@ -18,11 +18,11 @@ package org.apache.calcite.runtime;
 
 import org.apache.calcite.util.Holder;
 
-import com.google.common.base.Function;
-
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Consumer;
+import java.util.function.Function;
 
 /**
  * Collection of hooks that can be set by observers and are executed at various
@@ -88,15 +88,11 @@ public enum Hook {
    * pipeline expressions (for the MongoDB adapter), et cetera. */
   QUERY_PLAN;
 
-  private final List<Function<Object, Object>> handlers =
+  private final List<Consumer<Object>> handlers =
       new CopyOnWriteArrayList<>();
 
-  private final ThreadLocal<List<Function<Object, Object>>> threadHandlers =
-      new ThreadLocal<List<Function<Object, Object>>>() {
-        protected List<Function<Object, Object>> initialValue() {
-          return new ArrayList<>();
-        }
-      };
+  private final ThreadLocal<List<Consumer<Object>>> threadHandlers =
+      ThreadLocal.withInitial(ArrayList::new);
 
   /** Adds a handler for this Hook.
    *
@@ -112,56 +108,70 @@ public enum Hook {
    *     }</pre>
    * </blockquote>
    */
-  public <T, R> Closeable add(final Function<T, R> handler) {
+  public <T, R> Closeable add(final Consumer<T> handler) {
     //noinspection unchecked
-    handlers.add((Function<Object, Object>) handler);
-    return new Closeable() {
-      public void close() {
-        remove(handler);
-      }
-    };
+    handlers.add((Consumer<Object>) handler);
+    return () -> remove(handler);
+  }
+
+  /** @deprecated Use {@link #addThread(Consumer)}. */
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed in 2.0
+  public <T, R> Closeable add(final Function<T, R> handler) {
+    return add((Consumer<T>) handler::apply);
   }
 
   /** Removes a handler from this Hook. */
-  private boolean remove(Function handler) {
+  private boolean remove(Consumer handler) {
     return handlers.remove(handler);
   }
 
   /** Adds a handler for this thread. */
-  public <T, R> Closeable addThread(final Function<T, R> handler) {
+  public <T> Closeable addThread(final Consumer<T> handler) {
     //noinspection unchecked
-    threadHandlers.get().add((Function<Object, Object>) handler);
-    return new Closeable() {
-      public void close() {
-        removeThread(handler);
-      }
-    };
+    threadHandlers.get().add((Consumer<Object>) handler);
+    return () -> removeThread(handler);
+  }
+
+  /** @deprecated Use {@link #addThread(Consumer)}. */
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed in 2.0
+  public <T, R> Closeable addThread(
+      final com.google.common.base.Function<T, R> handler) {
+    return addThread((Consumer<T>) handler::apply);
   }
 
   /** Removes a thread handler from this Hook. */
-  private boolean removeThread(Function handler) {
+  private boolean removeThread(Consumer handler) {
     return threadHandlers.get().remove(handler);
   }
 
+  /** @deprecated Use {@link #propertyJ}. */
+  @SuppressWarnings("Guava")
+  @Deprecated // return type will change in 2.0
+  public static <V> com.google.common.base.Function<Holder<V>, Void> property(final V v) {
+    return holder -> {
+      holder.set(v);
+      return null;
+    };
+  }
+
   /** Returns a function that, when a hook is called, will "return" a given
    * value. (Because of the way hooks work, it "returns" the value by writing
    * into a {@link Holder}. */
-  public static <V> Function<Holder<V>, Void> property(final V v) {
-    return new Function<Holder<V>, Void>() {
-      public Void apply(Holder<V> holder) {
-        holder.set(v);
-        return null;
-      }
+  public static <V> Consumer<Holder<V>> propertyJ(final V v) {
+    return holder -> {
+      holder.set(v);
     };
   }
 
   /** Runs all handlers registered for this Hook, with the given argument. */
   public void run(Object arg) {
-    for (Function<Object, Object> handler : handlers) {
-      handler.apply(arg);
+    for (Consumer<Object> handler : handlers) {
+      handler.accept(arg);
     }
-    for (Function<Object, Object> handler : threadHandlers.get()) {
-      handler.apply(arg);
+    for (Consumer<Object> handler : threadHandlers.get()) {
+      handler.accept(arg);
     }
   }
 
@@ -176,10 +186,7 @@ public enum Hook {
   /** Removes a Hook after use. */
   public interface Closeable extends AutoCloseable {
     /** Closeable that does nothing. */
-    Closeable EMPTY =
-        new Closeable() {
-          public void close() {}
-        };
+    Closeable EMPTY = () -> { };
 
     // override, removing "throws"
     @Override void close();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java b/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java
index bc790d6..783d3bc 100644
--- a/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java
+++ b/core/src/main/java/org/apache/calcite/runtime/HttpUtils.java
@@ -27,9 +27,7 @@ import java.net.URLConnection;
 import java.net.URLEncoder;
 import java.nio.charset.StandardCharsets;
 import java.util.Map;
-import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLSession;
 
 /**
  * Utilities for connecting to REST services such as Splunk via HTTP.
@@ -49,12 +47,7 @@ public class HttpUtils {
       HttpsURLConnection httpsConn = (HttpsURLConnection) httpConn;
       httpsConn.setSSLSocketFactory(
           TrustAllSslSocketFactory.createSSLSocketFactory());
-      httpsConn.setHostnameVerifier(
-          new HostnameVerifier() {
-            public boolean verify(String arg0, SSLSession arg1) {
-              return true;
-            }
-          });
+      httpsConn.setHostnameVerifier((arg0, arg1) -> true);
     }
 
     return httpConn;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/PredicateImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/PredicateImpl.java b/core/src/main/java/org/apache/calcite/runtime/PredicateImpl.java
index f04737b..33adb54 100644
--- a/core/src/main/java/org/apache/calcite/runtime/PredicateImpl.java
+++ b/core/src/main/java/org/apache/calcite/runtime/PredicateImpl.java
@@ -30,6 +30,9 @@ import javax.annotation.Nullable;
  * but still works on JDK 1.7.
  *
  * @param <T> the type of the input to the predicate
+ *
+ * @deprecated Now Calcite is Java 8 and higher, we recommend that you
+ * implement {@link java.util.function.Predicate} directly.
  */
 public abstract class PredicateImpl<T> implements Predicate<T> {
   public final boolean apply(@Nullable T input) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/ResultSetEnumerable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/ResultSetEnumerable.java b/core/src/main/java/org/apache/calcite/runtime/ResultSetEnumerable.java
index 724bcf1..4724d8c 100644
--- a/core/src/main/java/org/apache/calcite/runtime/ResultSetEnumerable.java
+++ b/core/src/main/java/org/apache/calcite/runtime/ResultSetEnumerable.java
@@ -51,51 +51,45 @@ public class ResultSetEnumerable<T> extends AbstractEnumerable<T> {
       ResultSetEnumerable.class);
 
   private static final Function1<ResultSet, Function0<Object>> AUTO_ROW_BUILDER_FACTORY =
-      new Function1<ResultSet, Function0<Object>>() {
-        public Function0<Object> apply(final ResultSet resultSet) {
-          final ResultSetMetaData metaData;
-          final int columnCount;
-          try {
-            metaData = resultSet.getMetaData();
-            columnCount = metaData.getColumnCount();
-          } catch (SQLException e) {
-            throw new RuntimeException(e);
-          }
-          if (columnCount == 1) {
-            return new Function0<Object>() {
-              public Object apply() {
-                try {
-                  return resultSet.getObject(1);
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            };
-          } else {
-            //noinspection unchecked
-            return (Function0) new Function0<Object[]>() {
-              public Object[] apply() {
-                try {
-                  final List<Object> list = new ArrayList<Object>();
-                  for (int i = 0; i < columnCount; i++) {
-                    if (metaData.getColumnType(i + 1) == Types.TIMESTAMP) {
-                      long v = resultSet.getLong(i + 1);
-                      if (v == 0 && resultSet.wasNull()) {
-                        list.add(null);
-                      } else {
-                        list.add(v);
-                      }
-                    } else {
-                      list.add(resultSet.getObject(i + 1));
-                    }
+      resultSet -> {
+        final ResultSetMetaData metaData;
+        final int columnCount;
+        try {
+          metaData = resultSet.getMetaData();
+          columnCount = metaData.getColumnCount();
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
+        }
+        if (columnCount == 1) {
+          return () -> {
+            try {
+              return resultSet.getObject(1);
+            } catch (SQLException e) {
+              throw new RuntimeException(e);
+            }
+          };
+        } else {
+          //noinspection unchecked
+          return (Function0) () -> {
+            try {
+              final List<Object> list = new ArrayList<Object>();
+              for (int i = 0; i < columnCount; i++) {
+                if (metaData.getColumnType(i + 1) == Types.TIMESTAMP) {
+                  long v = resultSet.getLong(i + 1);
+                  if (v == 0 && resultSet.wasNull()) {
+                    list.add(null);
+                  } else {
+                    list.add(v);
                   }
-                  return list.toArray();
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
+                } else {
+                  list.add(resultSet.getObject(i + 1));
                 }
               }
-            };
-          }
+              return list.toArray();
+            } catch (SQLException e) {
+              throw new RuntimeException(e);
+            }
+          };
         }
       };
 
@@ -227,43 +221,37 @@ public class ResultSetEnumerable<T> extends AbstractEnumerable<T> {
 
   private static Function1<ResultSet, Function0<Object>>
       primitiveRowBuilderFactory(final Primitive[] primitives) {
-    return new Function1<ResultSet, Function0<Object>>() {
-      public Function0<Object> apply(final ResultSet resultSet) {
-        final ResultSetMetaData metaData;
-        final int columnCount;
+    return resultSet -> {
+      final ResultSetMetaData metaData;
+      final int columnCount;
+      try {
+        metaData = resultSet.getMetaData();
+        columnCount = metaData.getColumnCount();
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+      assert columnCount == primitives.length;
+      if (columnCount == 1) {
+        return () -> {
+          try {
+            return resultSet.getObject(1);
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        };
+      }
+      //noinspection unchecked
+      return (Function0) () -> {
         try {
-          metaData = resultSet.getMetaData();
-          columnCount = metaData.getColumnCount();
+          final List<Object> list = new ArrayList<Object>();
+          for (int i = 0; i < columnCount; i++) {
+            list.add(primitives[i].jdbcGet(resultSet, i + 1));
+          }
+          return list.toArray();
         } catch (SQLException e) {
           throw new RuntimeException(e);
         }
-        assert columnCount == primitives.length;
-        if (columnCount == 1) {
-          return new Function0<Object>() {
-            public Object apply() {
-              try {
-                return resultSet.getObject(1);
-              } catch (SQLException e) {
-                throw new RuntimeException(e);
-              }
-            }
-          };
-        }
-        //noinspection unchecked
-        return (Function0) new Function0<Object[]>() {
-          public Object[] apply() {
-            try {
-              final List<Object> list = new ArrayList<Object>();
-              for (int i = 0; i < columnCount; i++) {
-                list.add(primitives[i].jdbcGet(resultSet, i + 1));
-              }
-              return list.toArray();
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        };
-      }
+      };
     };
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java b/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
index 3a95f25..83cc24e 100644
--- a/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
+++ b/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
@@ -79,31 +79,20 @@ public class SqlFunctions {
   private static final TimeZone LOCAL_TZ = TimeZone.getDefault();
 
   private static final Function1<List<Object>, Enumerable<Object>> LIST_AS_ENUMERABLE =
-      new Function1<List<Object>, Enumerable<Object>>() {
-        public Enumerable<Object> apply(List<Object> list) {
-          return Linq4j.asEnumerable(list);
-        }
-      };
+      Linq4j::asEnumerable;
 
   private static final Function1<Object[], Enumerable<Object[]>> ARRAY_CARTESIAN_PRODUCT =
-      new Function1<Object[], Enumerable<Object[]>>() {
-        public Enumerable<Object[]> apply(Object[] lists) {
-          final List<Enumerator<Object>> enumerators = new ArrayList<>();
-          for (Object list : lists) {
-            enumerators.add(Linq4j.enumerator((List) list));
-          }
-          final Enumerator<List<Object>> product = Linq4j.product(enumerators);
-          return new AbstractEnumerable<Object[]>() {
-            public Enumerator<Object[]> enumerator() {
-              return Linq4j.transform(product,
-                  new Function1<List<Object>, Object[]>() {
-                    public Object[] apply(List<Object> list) {
-                      return list.toArray();
-                    }
-                  });
-            }
-          };
+      lists -> {
+        final List<Enumerator<Object>> enumerators = new ArrayList<>();
+        for (Object list : lists) {
+          enumerators.add(Linq4j.enumerator((List) list));
         }
+        final Enumerator<List<Object>> product = Linq4j.product(enumerators);
+        return new AbstractEnumerable<Object[]>() {
+          public Enumerator<Object[]> enumerator() {
+            return Linq4j.transform(product, List::toArray);
+          }
+        };
       };
 
   /** Holds, for each thread, a map from sequence name to sequence current
@@ -113,11 +102,7 @@ public class SqlFunctions {
    * that sequences can be parsed, validated and planned. A real application
    * will want persistent values for sequences, shared among threads. */
   private static final ThreadLocal<Map<String, AtomicLong>> THREAD_SEQUENCES =
-      new ThreadLocal<Map<String, AtomicLong>>() {
-        @Override protected Map<String, AtomicLong> initialValue() {
-          return new HashMap<String, AtomicLong>();
-        }
-      };
+      ThreadLocal.withInitial(HashMap::new);
 
   private SqlFunctions() {
   }
@@ -2212,20 +2197,12 @@ public class SqlFunctions {
         //noinspection unchecked
         return (Function1) LIST_AS_ENUMERABLE;
       } else {
-        return new Function1<Object, Enumerable<ComparableList<Comparable>>>() {
-          public Enumerable<ComparableList<Comparable>> apply(Object row) {
-            return p2(new Object[] { row }, fieldCounts, withOrdinality,
-                  inputTypes);
-          }
-        };
+        return row -> p2(new Object[] { row }, fieldCounts, withOrdinality,
+              inputTypes);
       }
     }
-    return new Function1<Object, Enumerable<FlatLists.ComparableList<Comparable>>>() {
-      public Enumerable<FlatLists.ComparableList<Comparable>> apply(Object lists) {
-        return p2((Object[]) lists, fieldCounts, withOrdinality,
-            inputTypes);
-      }
-    };
+    return lists -> p2((Object[]) lists, fieldCounts, withOrdinality,
+        inputTypes);
   }
 
   private static Enumerable<FlatLists.ComparableList<Comparable>> p2(
@@ -2243,12 +2220,7 @@ public class SqlFunctions {
             (List<Comparable>) inputObject;
         enumerators.add(
             Linq4j.transform(
-                Linq4j.enumerator(list),
-                new Function1<Comparable, List<Comparable>>() {
-                  public List<Comparable> apply(Comparable a0) {
-                    return FlatLists.of(a0);
-                  }
-                }));
+                Linq4j.enumerator(list), FlatLists::of));
         break;
       case LIST:
         @SuppressWarnings("unchecked") List<List<Comparable>> listList =
@@ -2262,11 +2234,7 @@ public class SqlFunctions {
             Linq4j.enumerator(map.entrySet());
 
         Enumerator<List<Comparable>> transformed = Linq4j.transform(enumerator,
-            new Function1<Entry<Comparable, Comparable>, List<Comparable>>() {
-              public List<Comparable> apply(Entry<Comparable, Comparable> e) {
-                return FlatLists.of(e.getKey(), e.getValue());
-              }
-            });
+            e -> FlatLists.of(e.getKey(), e.getValue()));
         enumerators.add(transformed);
         break;
       default:

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/FunctionParameter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/FunctionParameter.java b/core/src/main/java/org/apache/calcite/schema/FunctionParameter.java
index 3e95628..37af4bd 100644
--- a/core/src/main/java/org/apache/calcite/schema/FunctionParameter.java
+++ b/core/src/main/java/org/apache/calcite/schema/FunctionParameter.java
@@ -26,14 +26,6 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
  * {@link java.lang.reflect.Parameter} was too confusing.</p>
  */
 public interface FunctionParameter {
-  /** Function to get the name of a parameter. */
-  com.google.common.base.Function<FunctionParameter, String> NAME_FN =
-      new com.google.common.base.Function<FunctionParameter, String>() {
-        public String apply(FunctionParameter p) {
-          return p.getName();
-        }
-      };
-
   /**
    * Zero-based ordinal of this parameter within the member's parameter
    * list.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/Schemas.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/Schemas.java b/core/src/main/java/org/apache/calcite/schema/Schemas.java
index b238b3b..b303358 100644
--- a/core/src/main/java/org/apache/calcite/schema/Schemas.java
+++ b/core/src/main/java/org/apache/calcite/schema/Schemas.java
@@ -35,7 +35,6 @@ import org.apache.calcite.materialize.Lattice;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelProtoDataType;
-import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.sql.type.SqlTypeUtil;
 import org.apache.calcite.tools.RelRunner;
 import org.apache.calcite.util.BuiltInMethod;
@@ -55,34 +54,14 @@ import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
+
+import static org.apache.calcite.jdbc.CalciteSchema.LatticeEntry;
 
 /**
  * Utility functions for schemas.
  */
 public final class Schemas {
-  private static final com.google.common.base.Function<
-      CalciteSchema.LatticeEntry,
-      CalciteSchema.TableEntry> TO_TABLE_ENTRY =
-      new com.google.common.base.Function<CalciteSchema.LatticeEntry,
-          CalciteSchema.TableEntry>() {
-        public CalciteSchema.TableEntry apply(
-            CalciteSchema.LatticeEntry entry) {
-          final CalciteSchema.TableEntry starTable = entry.getStarTable();
-          assert starTable.getTable().getJdbcTableType()
-              == Schema.TableType.STAR;
-          return entry.getStarTable();
-        }
-      };
-
-  private static final com.google.common.base.Function<
-      CalciteSchema.LatticeEntry,
-      Lattice> TO_LATTICE =
-      new com.google.common.base.Function<CalciteSchema.LatticeEntry,
-          Lattice>() {
-        public Lattice apply(CalciteSchema.LatticeEntry entry) {
-          return entry.getLattice();
-        }
-      };
 
   private Schemas() {
     throw new AssertionError("no instances!");
@@ -245,7 +224,7 @@ public final class Schemas {
    * array. */
   public static Enumerable<Object[]> enumerable(final FilterableTable table,
       final DataContext root) {
-    return table.scan(root, ImmutableList.<RexNode>of());
+    return table.scan(root, ImmutableList.of());
   }
 
   /** Returns an {@link org.apache.calcite.linq4j.Enumerable} over the rows of
@@ -253,7 +232,7 @@ public final class Schemas {
    * representing each row as an object array. */
   public static Enumerable<Object[]> enumerable(
       final ProjectableFilterableTable table, final DataContext root) {
-    return table.scan(root, ImmutableList.<RexNode>of(),
+    return table.scan(root, ImmutableList.of(),
         identity(table.getRowType(root.getTypeFactory()).getFieldCount()));
   }
 
@@ -448,22 +427,14 @@ public final class Schemas {
    * {@link RelProtoDataType}
    * that asks a given table for its row type with a given type factory. */
   public static RelProtoDataType proto(final Table table) {
-    return new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory typeFactory) {
-        return table.getRowType(typeFactory);
-      }
-    };
+    return table::getRowType;
   }
 
   /** Returns an implementation of {@link RelProtoDataType}
    * that asks a given scalar function for its return type with a given type
    * factory. */
   public static RelProtoDataType proto(final ScalarFunction function) {
-    return new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory typeFactory) {
-        return function.getReturnType(typeFactory);
-      }
-    };
+    return function::getReturnType;
   }
 
   /** Returns the star tables defined in a schema.
@@ -472,7 +443,13 @@ public final class Schemas {
   public static List<CalciteSchema.TableEntry> getStarTables(
       CalciteSchema schema) {
     final List<CalciteSchema.LatticeEntry> list = getLatticeEntries(schema);
-    return Lists.transform(list, TO_TABLE_ENTRY);
+    return Lists.transform(list, entry -> {
+      final CalciteSchema.TableEntry starTable =
+          Objects.requireNonNull(entry).getStarTable();
+      assert starTable.getTable().getJdbcTableType()
+          == Schema.TableType.STAR;
+      return entry.getStarTable();
+    });
   }
 
   /** Returns the lattices defined in a schema.
@@ -480,7 +457,7 @@ public final class Schemas {
    * @param schema Schema */
   public static List<Lattice> getLattices(CalciteSchema schema) {
     final List<CalciteSchema.LatticeEntry> list = getLatticeEntries(schema);
-    return Lists.transform(list, TO_LATTICE);
+    return Lists.transform(list, CalciteSchema.LatticeEntry::getLattice);
   }
 
   /** Returns the lattices defined in a schema.
@@ -488,7 +465,7 @@ public final class Schemas {
    * @param schema Schema */
   public static List<CalciteSchema.LatticeEntry> getLatticeEntries(
       CalciteSchema schema) {
-    final List<CalciteSchema.LatticeEntry> list = Lists.newArrayList();
+    final List<LatticeEntry> list = new ArrayList<>();
     gatherLattices(schema, list);
     return list;
   }
@@ -520,7 +497,7 @@ public final class Schemas {
 
   /** Generates a table name that is unique within the given schema. */
   public static String uniqueTableName(CalciteSchema schema, String base) {
-    String t = Preconditions.checkNotNull(base);
+    String t = Objects.requireNonNull(base);
     for (int x = 0; schema.getTable(t, true) != null; x++) {
       t = base + x;
     }
@@ -558,7 +535,7 @@ public final class Schemas {
   public static Path path(SchemaPlus schema) {
     List<Pair<String, Schema>> list = new ArrayList<>();
     for (SchemaPlus s = schema; s != null; s = s.getParentSchema()) {
-      list.add(Pair.<String, Schema>of(s.getName(), s));
+      list.add(Pair.of(s.getName(), s));
     }
     return new PathImpl(ImmutableList.copyOf(Lists.reverse(list)));
   }
@@ -572,7 +549,7 @@ public final class Schemas {
     DummyDataContext(CalciteConnection connection, SchemaPlus rootSchema) {
       this.connection = connection;
       this.rootSchema = rootSchema;
-      this.map = ImmutableMap.<String, Object>of();
+      this.map = ImmutableMap.of();
     }
 
     public SchemaPlus getRootSchema() {
@@ -598,7 +575,7 @@ public final class Schemas {
     private final ImmutableList<Pair<String, Schema>> pairs;
 
     private static final PathImpl EMPTY =
-        new PathImpl(ImmutableList.<Pair<String, Schema>>of());
+        new PathImpl(ImmutableList.of());
 
     PathImpl(ImmutableList<Pair<String, Schema>> pairs) {
       this.pairs = pairs;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/Statistics.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/Statistics.java b/core/src/main/java/org/apache/calcite/schema/Statistics.java
index d3d4173..0e55140 100644
--- a/core/src/main/java/org/apache/calcite/schema/Statistics.java
+++ b/core/src/main/java/org/apache/calcite/schema/Statistics.java
@@ -45,7 +45,7 @@ public class Statistics {
         }
 
         public List<RelReferentialConstraint> getReferentialConstraints() {
-          return ImmutableList.<RelReferentialConstraint>of();
+          return ImmutableList.of();
         }
 
         public List<RelCollation> getCollations() {
@@ -59,15 +59,15 @@ public class Statistics {
 
   /** Returns a statistic with a given set of referential constraints. */
   public static Statistic of(final List<RelReferentialConstraint> referentialConstraints) {
-    return of(null, ImmutableList.<ImmutableBitSet>of(),
-        referentialConstraints, ImmutableList.<RelCollation>of());
+    return of(null, ImmutableList.of(),
+        referentialConstraints, ImmutableList.of());
   }
 
   /** Returns a statistic with a given row count and set of unique keys. */
   public static Statistic of(final double rowCount,
       final List<ImmutableBitSet> keys) {
-    return of(rowCount, keys, ImmutableList.<RelReferentialConstraint>of(),
-        ImmutableList.<RelCollation>of());
+    return of(rowCount, keys, ImmutableList.of(),
+        ImmutableList.of());
   }
 
   /** Returns a statistic with a given row count, set of unique keys,
@@ -75,7 +75,7 @@ public class Statistics {
   public static Statistic of(final double rowCount,
       final List<ImmutableBitSet> keys,
       final List<RelCollation> collations) {
-    return of(rowCount, keys, ImmutableList.<RelReferentialConstraint>of(), collations);
+    return of(rowCount, keys, ImmutableList.of(), collations);
   }
 
   /** Returns a statistic with a given row count, set of unique keys,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/Table.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/Table.java b/core/src/main/java/org/apache/calcite/schema/Table.java
index 33185db..f3540d1 100644
--- a/core/src/main/java/org/apache/calcite/schema/Table.java
+++ b/core/src/main/java/org/apache/calcite/schema/Table.java
@@ -77,9 +77,9 @@ public interface Table {
    * @param parent Parent node of {@code call} in the {@link SqlNode} tree
    * @param config Config settings. May be null
    * @return true iff the given aggregate call is valid
-   * */
-  boolean rolledUpColumnValidInsideAgg(String column, SqlCall call, SqlNode parent,
-                                       CalciteConnectionConfig config);
+   */
+  boolean rolledUpColumnValidInsideAgg(String column, SqlCall call,
+      SqlNode parent, CalciteConnectionConfig config);
 }
 
 // End Table.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/impl/AbstractSchema.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/impl/AbstractSchema.java b/core/src/main/java/org/apache/calcite/schema/impl/AbstractSchema.java
index dc8c25e..c77107b 100644
--- a/core/src/main/java/org/apache/calcite/schema/impl/AbstractSchema.java
+++ b/core/src/main/java/org/apache/calcite/schema/impl/AbstractSchema.java
@@ -50,10 +50,6 @@ import java.util.Set;
  *   <li>The name and parent schema are as specified in the constructor
  *       arguments.</li>
  * </ul>
- *
- * <p>For constructing custom maps and multi-maps, we recommend
- * {@link com.google.common.base.Suppliers} and
- * {@link com.google.common.collect.Maps}.</p>
  */
 public class AbstractSchema implements Schema {
   public AbstractSchema() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/impl/AggregateFunctionImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/impl/AggregateFunctionImpl.java b/core/src/main/java/org/apache/calcite/schema/impl/AggregateFunctionImpl.java
index 69f2269..34644e9 100644
--- a/core/src/main/java/org/apache/calcite/schema/impl/AggregateFunctionImpl.java
+++ b/core/src/main/java/org/apache/calcite/schema/impl/AggregateFunctionImpl.java
@@ -25,12 +25,12 @@ import org.apache.calcite.schema.FunctionParameter;
 import org.apache.calcite.schema.ImplementableAggFunction;
 import org.apache.calcite.util.ReflectUtil;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.List;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -70,8 +70,8 @@ public class AggregateFunctionImpl implements AggregateFunction,
     this.parameters = params;
     this.accumulatorType = accumulatorType;
     this.resultType = resultType;
-    this.initMethod = Preconditions.checkNotNull(initMethod);
-    this.addMethod = Preconditions.checkNotNull(addMethod);
+    this.initMethod = Objects.requireNonNull(initMethod);
+    this.addMethod = Objects.requireNonNull(addMethod);
     this.mergeMethod = mergeMethod;
     this.resultMethod = resultMethod;
     this.isStatic = Modifier.isStatic(initMethod.getModifiers());

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/impl/MaterializedViewTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/impl/MaterializedViewTable.java b/core/src/main/java/org/apache/calcite/schema/impl/MaterializedViewTable.java
index baebab5..5121221 100644
--- a/core/src/main/java/org/apache/calcite/schema/impl/MaterializedViewTable.java
+++ b/core/src/main/java/org/apache/calcite/schema/impl/MaterializedViewTable.java
@@ -30,12 +30,11 @@ import org.apache.calcite.schema.Schemas;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.TranslatableTable;
 
-import com.google.common.base.Preconditions;
-
 import java.lang.reflect.Type;
 import java.sql.DriverManager;
 import java.sql.SQLException;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Table that is a materialized view.
@@ -107,7 +106,7 @@ public class MaterializedViewTable extends ViewTable {
       super(schema, viewSql,
           viewSchemaPath != null ? viewSchemaPath : schema.path(null), viewPath,
           Boolean.TRUE);
-      this.key = Preconditions.checkNotNull(
+      this.key = Objects.requireNonNull(
           MaterializationService.instance().defineMaterialization(
               schema, null, viewSql, schemaPath, suggestedTableName, true,
               existing));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/impl/ModifiableViewTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/impl/ModifiableViewTable.java b/core/src/main/java/org/apache/calcite/schema/impl/ModifiableViewTable.java
index a312188..567b780 100644
--- a/core/src/main/java/org/apache/calcite/schema/impl/ModifiableViewTable.java
+++ b/core/src/main/java/org/apache/calcite/schema/impl/ModifiableViewTable.java
@@ -39,10 +39,10 @@ import org.apache.calcite.util.ImmutableIntList;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
 
 import java.lang.reflect.Type;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -186,7 +186,7 @@ public class ModifiableViewTable extends ViewTable
 
     private ModifiableViewTableInitializerExpressionFactory() {
       super();
-      final Map<Integer, RexNode> projectMap = Maps.newHashMap();
+      final Map<Integer, RexNode> projectMap = new HashMap<>();
       final List<RexNode> filters = new ArrayList<>();
       RelOptUtil.inferViewPredicates(projectMap, filters, constraint);
       assert filters.isEmpty();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/schema/impl/StarTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/schema/impl/StarTable.java b/core/src/main/java/org/apache/calcite/schema/impl/StarTable.java
index 27f3cf8..b0a62a5 100644
--- a/core/src/main/java/org/apache/calcite/schema/impl/StarTable.java
+++ b/core/src/main/java/org/apache/calcite/schema/impl/StarTable.java
@@ -34,11 +34,11 @@ import org.apache.calcite.schema.TranslatableTable;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Virtual table that is composed of two or more tables joined together.
@@ -63,7 +63,7 @@ public class StarTable extends AbstractTable implements TranslatableTable {
 
   /** Creates a StarTable. */
   private StarTable(Lattice lattice, ImmutableList<Table> tables) {
-    this.lattice = Preconditions.checkNotNull(lattice);
+    this.lattice = Objects.requireNonNull(lattice);
     this.tables = tables;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlBasicCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlBasicCall.java b/core/src/main/java/org/apache/calcite/sql/SqlBasicCall.java
index bd311f2..d9e0322 100755
--- a/core/src/main/java/org/apache/calcite/sql/SqlBasicCall.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlBasicCall.java
@@ -19,9 +19,8 @@ package org.apache.calcite.sql;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.util.UnmodifiableArrayList;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Implementation of {@link SqlCall} that keeps its operands in an array.
@@ -46,7 +45,7 @@ public class SqlBasicCall extends SqlCall {
       boolean expanded,
       SqlLiteral functionQualifier) {
     super(pos);
-    this.operator = Preconditions.checkNotNull(operator);
+    this.operator = Objects.requireNonNull(operator);
     this.operands = operands;
     this.expanded = expanded;
     this.functionQuantifier = functionQualifier;
@@ -65,7 +64,7 @@ public class SqlBasicCall extends SqlCall {
   }
 
   public void setOperator(SqlOperator operator) {
-    this.operator = Preconditions.checkNotNull(operator);
+    this.operator = Objects.requireNonNull(operator);
   }
 
   public SqlOperator getOperator() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlBinaryStringLiteral.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlBinaryStringLiteral.java b/core/src/main/java/org/apache/calcite/sql/SqlBinaryStringLiteral.java
index 71380e1..d9c4ef2 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlBinaryStringLiteral.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlBinaryStringLiteral.java
@@ -19,9 +19,7 @@ package org.apache.calcite.sql;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.BitString;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
+import org.apache.calcite.util.Util;
 
 import java.util.List;
 
@@ -32,12 +30,6 @@ import java.util.List;
  * {@link SqlTypeName#BINARY}.
  */
 public class SqlBinaryStringLiteral extends SqlAbstractStringLiteral {
-  private static final Function<SqlLiteral, BitString> F =
-      new Function<SqlLiteral, BitString>() {
-        public BitString apply(SqlLiteral literal) {
-          return ((SqlBinaryStringLiteral) literal).getBitString();
-        }
-      };
 
   //~ Constructors -----------------------------------------------------------
 
@@ -70,7 +62,9 @@ public class SqlBinaryStringLiteral extends SqlAbstractStringLiteral {
 
   protected SqlAbstractStringLiteral concat1(List<SqlLiteral> literals) {
     return new SqlBinaryStringLiteral(
-        BitString.concat(Lists.transform(literals, F)),
+        BitString.concat(
+            Util.transform(literals,
+                literal -> ((SqlBinaryStringLiteral) literal).getBitString())),
         literals.get(0).getParserPosition());
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlCall.java b/core/src/main/java/org/apache/calcite/sql/SqlCall.java
index 9e50417..aeddb6f 100755
--- a/core/src/main/java/org/apache/calcite/sql/SqlCall.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlCall.java
@@ -84,7 +84,7 @@ public abstract class SqlCall extends SqlNode {
   @Override public SqlNode clone(SqlParserPos pos) {
     final List<SqlNode> operandList = getOperandList();
     return getOperator().createCall(getFunctionQuantifier(), pos,
-        operandList.toArray(new SqlNode[operandList.size()]));
+        operandList.toArray(new SqlNode[0]));
   }
 
   public void unparse(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlCallBinding.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlCallBinding.java b/core/src/main/java/org/apache/calcite/sql/SqlCallBinding.java
index 002382c..8fe2e82 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlCallBinding.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlCallBinding.java
@@ -30,7 +30,6 @@ import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 import org.apache.calcite.util.NlsString;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.math.BigDecimal;
@@ -154,20 +153,17 @@ public class SqlCallBinding extends SqlOperatorBinding {
    * formal parameters of the function. */
   private List<SqlNode> permutedOperands(final SqlCall call) {
     final SqlFunction operator = (SqlFunction) call.getOperator();
-    return Lists.transform(operator.getParamNames(),
-        new Function<String, SqlNode>() {
-          public SqlNode apply(String paramName) {
-            for (SqlNode operand2 : call.getOperandList()) {
-              final SqlCall call2 = (SqlCall) operand2;
-              assert operand2.getKind() == SqlKind.ARGUMENT_ASSIGNMENT;
-              final SqlIdentifier id = call2.operand(1);
-              if (id.getSimple().equals(paramName)) {
-                return call2.operand(0);
-              }
-            }
-            return DEFAULT_CALL;
-          }
-        });
+    return Lists.transform(operator.getParamNames(), paramName -> {
+      for (SqlNode operand2 : call.getOperandList()) {
+        final SqlCall call2 = (SqlCall) operand2;
+        assert operand2.getKind() == SqlKind.ARGUMENT_ASSIGNMENT;
+        final SqlIdentifier id = call2.operand(1);
+        if (id.getSimple().equals(paramName)) {
+          return call2.operand(0);
+        }
+      }
+      return DEFAULT_CALL;
+    });
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlCharStringLiteral.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlCharStringLiteral.java b/core/src/main/java/org/apache/calcite/sql/SqlCharStringLiteral.java
index b74176c..c3846f1 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlCharStringLiteral.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlCharStringLiteral.java
@@ -22,9 +22,6 @@ import org.apache.calcite.util.Bug;
 import org.apache.calcite.util.NlsString;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
-
 import java.util.List;
 
 /**
@@ -34,12 +31,6 @@ import java.util.List;
  * {@link SqlTypeName#CHAR}.
  */
 public class SqlCharStringLiteral extends SqlAbstractStringLiteral {
-  private static final Function<SqlLiteral, NlsString> F =
-      new Function<SqlLiteral, NlsString>() {
-        public NlsString apply(SqlLiteral literal) {
-          return ((SqlCharStringLiteral) literal).getNlsString();
-        }
-      };
 
   //~ Constructors -----------------------------------------------------------
 
@@ -83,7 +74,9 @@ public class SqlCharStringLiteral extends SqlAbstractStringLiteral {
 
   protected SqlAbstractStringLiteral concat1(List<SqlLiteral> literals) {
     return new SqlCharStringLiteral(
-        NlsString.concat(Lists.transform(literals, F)),
+        NlsString.concat(
+            Util.transform(literals,
+                literal -> ((SqlCharStringLiteral) literal).getNlsString())),
         literals.get(0).getParserPosition());
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlDataTypeSpec.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlDataTypeSpec.java b/core/src/main/java/org/apache/calcite/sql/SqlDataTypeSpec.java
index cb921a4..a6238a3 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlDataTypeSpec.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlDataTypeSpec.java
@@ -28,8 +28,6 @@ import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-
 import java.nio.charset.Charset;
 import java.util.Objects;
 import java.util.TimeZone;
@@ -364,7 +362,7 @@ public class SqlDataTypeSpec extends SqlNode {
         charset = typeFactory.getDefaultCharset();
       } else {
         String javaCharSetName =
-            Preconditions.checkNotNull(
+            Objects.requireNonNull(
                 SqlUtil.translateCharacterSetName(charSetName), charSetName);
         charset = Charset.forName(javaCharSetName);
       }
@@ -378,7 +376,7 @@ public class SqlDataTypeSpec extends SqlNode {
     if (null != collectionsTypeName) {
       final String collectionName = collectionsTypeName.getSimple();
       final SqlTypeName collectionsSqlTypeName =
-          Preconditions.checkNotNull(SqlTypeName.get(collectionName),
+          Objects.requireNonNull(SqlTypeName.get(collectionName),
               collectionName);
 
       switch (collectionsSqlTypeName) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlDdl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlDdl.java b/core/src/main/java/org/apache/calcite/sql/SqlDdl.java
index c22abb6..671ad7d 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlDdl.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlDdl.java
@@ -18,7 +18,7 @@ package org.apache.calcite.sql;
 
 import org.apache.calcite.sql.parser.SqlParserPos;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /** Base class for CREATE, DROP and other DDL statements. */
 public abstract class SqlDdl extends SqlCall {
@@ -31,7 +31,7 @@ public abstract class SqlDdl extends SqlCall {
   /** Creates a SqlDdl. */
   public SqlDdl(SqlOperator operator, SqlParserPos pos) {
     super(pos);
-    this.operator = Preconditions.checkNotNull(operator);
+    this.operator = Objects.requireNonNull(operator);
   }
 
   public SqlOperator getOperator() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlDescribeSchema.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlDescribeSchema.java b/core/src/main/java/org/apache/calcite/sql/SqlDescribeSchema.java
index b6432c7..e9959b0 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlDescribeSchema.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlDescribeSchema.java
@@ -64,7 +64,7 @@ public class SqlDescribeSchema extends SqlCall {
   }
 
   @Override public List<SqlNode> getOperandList() {
-    return ImmutableNullableList.<SqlNode>of(schema);
+    return ImmutableNullableList.of(schema);
   }
 
   public SqlIdentifier getSchema() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlDescribeTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlDescribeTable.java b/core/src/main/java/org/apache/calcite/sql/SqlDescribeTable.java
index 025bced..76e088b 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlDescribeTable.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlDescribeTable.java
@@ -75,7 +75,7 @@ public class SqlDescribeTable extends SqlCall {
   }
 
   @Override public List<SqlNode> getOperandList() {
-    return ImmutableNullableList.<SqlNode>of(table, column);
+    return ImmutableNullableList.of(table, column);
   }
 
   public SqlIdentifier getTable() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlDialect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlDialect.java b/core/src/main/java/org/apache/calcite/sql/SqlDialect.java
index 3e679d3..1314656 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlDialect.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlDialect.java
@@ -32,7 +32,6 @@ import org.apache.calcite.sql.type.BasicSqlType;
 import org.apache.calcite.sql.type.SqlTypeUtil;
 
 import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
 import com.google.common.base.Suppliers;
 
 import org.slf4j.Logger;
@@ -44,6 +43,8 @@ import java.sql.Timestamp;
 import java.text.SimpleDateFormat;
 import java.util.List;
 import java.util.Locale;
+import java.util.Objects;
+import java.util.function.Supplier;
 import java.util.regex.Pattern;
 import javax.annotation.Nonnull;
 
@@ -135,9 +136,9 @@ public class SqlDialect {
    * @param context All the information necessary to create a dialect
    */
   public SqlDialect(Context context) {
-    this.nullCollation = Preconditions.checkNotNull(context.nullCollation());
+    this.nullCollation = Objects.requireNonNull(context.nullCollation());
     this.databaseProduct =
-        Preconditions.checkNotNull(context.databaseProduct());
+        Objects.requireNonNull(context.databaseProduct());
     String identifierQuoteString = context.identifierQuoteString();
     if (identifierQuoteString != null) {
       identifierQuoteString = identifierQuoteString.trim();
@@ -897,32 +898,24 @@ public class SqlDialect {
      */
     UNKNOWN("Unknown", "`", NullCollation.HIGH);
 
-    private final Supplier<SqlDialect> dialect =
-        Suppliers.memoize(new Supplier<SqlDialect>() {
-          public SqlDialect get() {
-            final SqlDialect dialect =
-                SqlDialectFactoryImpl.simple(DatabaseProduct.this);
-            if (dialect != null) {
-              return dialect;
-            }
-            return new SqlDialect(SqlDialect.EMPTY_CONTEXT
-                .withDatabaseProduct(DatabaseProduct.this)
-                .withDatabaseProductName(databaseProductName)
-                .withIdentifierQuoteString(quoteString)
-                .withNullCollation(nullCollation));
-          }
-        });
-
-    private String databaseProductName;
-    private String quoteString;
-    private final NullCollation nullCollation;
+    private final Supplier<SqlDialect> dialect;
 
     DatabaseProduct(String databaseProductName, String quoteString,
         NullCollation nullCollation) {
-      this.databaseProductName =
-          Preconditions.checkNotNull(databaseProductName);
-      this.quoteString = quoteString;
-      this.nullCollation = Preconditions.checkNotNull(nullCollation);
+      Objects.requireNonNull(databaseProductName);
+      Objects.requireNonNull(nullCollation);
+      dialect = Suppliers.memoize(() -> {
+        final SqlDialect dialect =
+            SqlDialectFactoryImpl.simple(DatabaseProduct.this);
+        if (dialect != null) {
+          return dialect;
+        }
+        return new SqlDialect(SqlDialect.EMPTY_CONTEXT
+            .withDatabaseProduct(DatabaseProduct.this)
+            .withDatabaseProductName(databaseProductName)
+            .withIdentifierQuoteString(quoteString)
+            .withNullCollation(nullCollation));
+      })::get;
     }
 
     /**
@@ -980,14 +973,14 @@ public class SqlDialect {
         int databaseMajorVersion, int databaseMinorVersion,
         String identifierQuoteString, NullCollation nullCollation,
         JethroDataSqlDialect.JethroInfo jethroInfo) {
-      this.databaseProduct = Preconditions.checkNotNull(databaseProduct);
+      this.databaseProduct = Objects.requireNonNull(databaseProduct);
       this.databaseProductName = databaseProductName;
       this.databaseVersion = databaseVersion;
       this.databaseMajorVersion = databaseMajorVersion;
       this.databaseMinorVersion = databaseMinorVersion;
       this.identifierQuoteString = identifierQuoteString;
-      this.nullCollation = Preconditions.checkNotNull(nullCollation);
-      this.jethroInfo = Preconditions.checkNotNull(jethroInfo);
+      this.nullCollation = Objects.requireNonNull(nullCollation);
+      this.jethroInfo = Objects.requireNonNull(jethroInfo);
     }
 
     @Nonnull public DatabaseProduct databaseProduct() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlFunction.java b/core/src/main/java/org/apache/calcite/sql/SqlFunction.java
index e485422..597b7ff 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlFunction.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.sql;
 
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.linq4j.function.Functions;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.sql.type.SqlOperandTypeChecker;
@@ -26,10 +25,10 @@ import org.apache.calcite.sql.validate.SqlValidator;
 import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.Objects;
 import javax.annotation.Nonnull;
 
 import static org.apache.calcite.util.Static.RESOURCE;
@@ -39,13 +38,6 @@ import static org.apache.calcite.util.Static.RESOURCE;
  * function-call syntax.
  */
 public class SqlFunction extends SqlOperator {
-  /** Function that generates "arg{n}" for the {@code n}th argument name. */
-  private static final Function1<Integer, String> ARG_FN =
-      new Function1<Integer, String>() {
-        public String apply(Integer a0) {
-          return "arg" + a0;
-        }
-      };
 
   //~ Instance fields --------------------------------------------------------
 
@@ -123,7 +115,7 @@ public class SqlFunction extends SqlOperator {
         operandTypeChecker);
 
     this.sqlIdentifier = sqlIdentifier;
-    this.category = Preconditions.checkNotNull(category);
+    this.category = Objects.requireNonNull(category);
     this.paramTypes =
         paramTypes == null ? null : ImmutableList.copyOf(paramTypes);
   }
@@ -161,7 +153,7 @@ public class SqlFunction extends SqlOperator {
    * <p>The default implementation returns {@code [arg0, arg1, ..., argN]}.
    */
   public List<String> getParamNames() {
-    return Functions.generate(paramTypes.size(), ARG_FN);
+    return Functions.generate(paramTypes.size(), i -> "arg" + i);
   }
 
   public void unparse(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlIdentifier.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlIdentifier.java b/core/src/main/java/org/apache/calcite/sql/SqlIdentifier.java
index 4839805..ba6fb0c 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlIdentifier.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlIdentifier.java
@@ -26,7 +26,6 @@ import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
@@ -37,19 +36,6 @@ import java.util.List;
  * A <code>SqlIdentifier</code> is an identifier, possibly compound.
  */
 public class SqlIdentifier extends SqlNode {
-  private static final Function<String, String> STAR_TO_EMPTY =
-      new Function<String, String>() {
-        public String apply(String s) {
-          return s.equals("*") ? "" : s;
-        }
-      };
-
-  private static final Function<String, String> EMPTY_TO_STAR =
-      new Function<String, String>() {
-        public String apply(String s) {
-          return s.equals("") ? "*" : s.equals("*") ? "\"*\"" : s;
-        }
-      };
 
   //~ Instance fields --------------------------------------------------------
 
@@ -131,7 +117,8 @@ public class SqlIdentifier extends SqlNode {
   /** Creates an identifier that ends in a wildcard star. */
   public static SqlIdentifier star(List<String> names, SqlParserPos pos,
       List<SqlParserPos> componentPositions) {
-    return new SqlIdentifier(Lists.transform(names, STAR_TO_EMPTY), null, pos,
+    return new SqlIdentifier(
+        Lists.transform(names, s -> s.equals("*") ? "" : s), null, pos,
         componentPositions);
   }
 
@@ -156,7 +143,8 @@ public class SqlIdentifier extends SqlNode {
 
   /** Converts empty strings in a list of names to stars. */
   public static List<String> toStar(List<String> names) {
-    return Lists.transform(names, EMPTY_TO_STAR);
+    return Lists.transform(names,
+        s -> s.equals("") ? "*" : s.equals("*") ? "\"*\"" : s);
   }
 
   /**
@@ -175,7 +163,7 @@ public class SqlIdentifier extends SqlNode {
    * Does not modify this identifier. */
   public SqlIdentifier setName(int i, String name) {
     if (!names.get(i).equals(name)) {
-      String[] nameArray = names.toArray(new String[names.size()]);
+      String[] nameArray = names.toArray(new String[0]);
       nameArray[i] = name;
       return new SqlIdentifier(ImmutableList.copyOf(nameArray), collation, pos,
           componentPositions);
@@ -274,8 +262,10 @@ public class SqlIdentifier extends SqlNode {
    */
   public SqlIdentifier plusStar() {
     final SqlIdentifier id = this.plus("*", SqlParserPos.ZERO);
-    return new SqlIdentifier(Lists.transform(id.names, STAR_TO_EMPTY), null, id.pos,
-        id.componentPositions);
+    return new SqlIdentifier(
+        id.names.stream().map(s -> s.equals("*") ? "" : s)
+            .collect(Util.toImmutableList()),
+        null, id.pos, id.componentPositions);
   }
 
   /** Creates an identifier that consists of all but the last {@code n}

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java b/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
index 2fafec7..a25d93d 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlIntervalQualifier.java
@@ -29,9 +29,8 @@ import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-
 import java.math.BigDecimal;
+import java.util.Objects;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -109,7 +108,7 @@ public class SqlIntervalQualifier extends SqlNode {
       endUnit = null;
     }
     this.timeUnitRange =
-        TimeUnitRange.of(Preconditions.checkNotNull(startUnit), endUnit);
+        TimeUnitRange.of(Objects.requireNonNull(startUnit), endUnit);
     this.startPrecision = startPrecision;
     this.fractionalSecondPrecision = fractionalSecondPrecision;
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlJdbcFunctionCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlJdbcFunctionCall.java b/core/src/main/java/org/apache/calcite/sql/SqlJdbcFunctionCall.java
index a057697..d84d931 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlJdbcFunctionCall.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlJdbcFunctionCall.java
@@ -25,10 +25,10 @@ import org.apache.calcite.sql.validate.SqlValidator;
 import org.apache.calcite.sql.validate.SqlValidatorImpl;
 import org.apache.calcite.sql.validate.SqlValidatorScope;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 
 import java.util.Map;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -601,7 +601,7 @@ public class SqlJdbcFunctionCall extends SqlFunction {
      */
     PermutingMakeCall(SqlOperator operator, int[] order) {
       super(operator);
-      this.order = Preconditions.checkNotNull(order);
+      this.order = Objects.requireNonNull(order);
     }
 
     @Override public SqlCall createCall(SqlParserPos pos,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlJoin.java b/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
index 104d315..e533ee9 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
@@ -24,6 +24,7 @@ import org.apache.calcite.util.Util;
 import com.google.common.base.Preconditions;
 
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Parse tree node representing a {@code JOIN} clause.
@@ -60,15 +61,15 @@ public class SqlJoin extends SqlCall {
       SqlNode condition) {
     super(pos);
     this.left = left;
-    this.natural = Preconditions.checkNotNull(natural);
-    this.joinType = Preconditions.checkNotNull(joinType);
+    this.natural = Objects.requireNonNull(natural);
+    this.joinType = Objects.requireNonNull(joinType);
     this.right = right;
-    this.conditionType = Preconditions.checkNotNull(conditionType);
+    this.conditionType = Objects.requireNonNull(conditionType);
     this.condition = condition;
 
     Preconditions.checkArgument(natural.getTypeName() == SqlTypeName.BOOLEAN);
-    Preconditions.checkNotNull(conditionType.symbolValue(JoinConditionType.class));
-    Preconditions.checkNotNull(joinType.symbolValue(JoinType.class));
+    Objects.requireNonNull(conditionType.symbolValue(JoinConditionType.class));
+    Objects.requireNonNull(joinType.symbolValue(JoinType.class));
   }
 
   //~ Methods ----------------------------------------------------------------


[17/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectFilterTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectFilterTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectFilterTransposeRule.java
index f468f9c..dd1c0c9 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectFilterTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectFilterTransposeRule.java
@@ -34,9 +34,9 @@ import org.apache.calcite.tools.RelBuilderFactory;
  * past a {@link org.apache.calcite.rel.core.Filter}.
  */
 public class ProjectFilterTransposeRule extends RelOptRule {
-  public static final ProjectFilterTransposeRule INSTANCE = new ProjectFilterTransposeRule(
-      LogicalProject.class, LogicalFilter.class, RelFactories.LOGICAL_BUILDER,
-      PushProjector.ExprCondition.FALSE);
+  public static final ProjectFilterTransposeRule INSTANCE =
+      new ProjectFilterTransposeRule(LogicalProject.class, LogicalFilter.class,
+          RelFactories.LOGICAL_BUILDER, expr -> false);
 
   //~ Instance fields --------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectJoinTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectJoinTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectJoinTransposeRule.java
index 2983703..34dee11 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectJoinTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectJoinTransposeRule.java
@@ -38,8 +38,7 @@ import java.util.List;
  */
 public class ProjectJoinTransposeRule extends RelOptRule {
   public static final ProjectJoinTransposeRule INSTANCE =
-      new ProjectJoinTransposeRule(
-          PushProjector.ExprCondition.TRUE,
+      new ProjectJoinTransposeRule(expr -> true,
           RelFactories.LOGICAL_BUILDER);
 
   //~ Instance fields --------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectRemoveRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectRemoveRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectRemoveRule.java
index cc773fb..515b779 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectRemoveRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectRemoveRule.java
@@ -24,11 +24,8 @@ import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexUtil;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicate;
-
 import java.util.List;
 
 /**
@@ -43,14 +40,6 @@ import java.util.List;
  * @see ProjectMergeRule
  */
 public class ProjectRemoveRule extends RelOptRule {
-  //~ Static fields/initializers ---------------------------------------------
-  private static final Predicate<Project> PREDICATE =
-      new PredicateImpl<Project>() {
-        public boolean test(Project input) {
-          return isTrivial(input);
-        }
-      };
-
   public static final ProjectRemoveRule INSTANCE =
       new ProjectRemoveRule(RelFactories.LOGICAL_BUILDER);
 
@@ -64,8 +53,8 @@ public class ProjectRemoveRule extends RelOptRule {
   public ProjectRemoveRule(RelBuilderFactory relBuilderFactory) {
     // Create a specialized operand to detect non-matches early. This keeps
     // the rule queue short.
-    super(operand(Project.class, null, PREDICATE, any()), relBuilderFactory,
-        null);
+    super(operandJ(Project.class, null, ProjectRemoveRule::isTrivial, any()),
+        relBuilderFactory, null);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectSetOpTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectSetOpTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectSetOpTransposeRule.java
index 48fb027..6190556 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectSetOpTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectSetOpTransposeRule.java
@@ -40,8 +40,8 @@ import java.util.List;
  */
 public class ProjectSetOpTransposeRule extends RelOptRule {
   public static final ProjectSetOpTransposeRule INSTANCE =
-      new ProjectSetOpTransposeRule(
-          PushProjector.ExprCondition.FALSE, RelFactories.LOGICAL_BUILDER);
+      new ProjectSetOpTransposeRule(expr -> false,
+          RelFactories.LOGICAL_BUILDER);
 
   //~ Instance fields --------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectTableScanRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectTableScanRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectTableScanRule.java
index bd4b5fe..777aa19 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectTableScanRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectTableScanRule.java
@@ -26,14 +26,12 @@ import org.apache.calcite.rel.core.Project;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.core.TableScan;
 import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.ProjectableFilterableTable;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
 
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
@@ -50,20 +48,17 @@ import java.util.List;
  * @see FilterTableScanRule
  */
 public abstract class ProjectTableScanRule extends RelOptRule {
-  public static final Predicate<TableScan> PREDICATE =
-      new PredicateImpl<TableScan>() {
-        public boolean test(TableScan scan) {
-          // We can only push projects into a ProjectableFilterableTable.
-          final RelOptTable table = scan.getTable();
-          return table.unwrap(ProjectableFilterableTable.class) != null;
-        }
-      };
+  @SuppressWarnings("Guava")
+  @Deprecated // to be removed before 2.0
+  public static final com.google.common.base.Predicate<TableScan> PREDICATE =
+      ProjectTableScanRule::test;
 
   /** Rule that matches Project on TableScan. */
   public static final ProjectTableScanRule INSTANCE =
       new ProjectTableScanRule(
           operand(Project.class,
-              operand(TableScan.class, null, PREDICATE, none())),
+              operandJ(TableScan.class, null, ProjectTableScanRule::test,
+                  none())),
           RelFactories.LOGICAL_BUILDER,
           "ProjectScanRule") {
         @Override public void onMatch(RelOptRuleCall call) {
@@ -78,7 +73,8 @@ public abstract class ProjectTableScanRule extends RelOptRule {
       new ProjectTableScanRule(
           operand(Project.class,
               operand(EnumerableInterpreter.class,
-                  operand(TableScan.class, null, PREDICATE, none()))),
+                  operandJ(TableScan.class, null, ProjectTableScanRule::test,
+                      none()))),
           RelFactories.LOGICAL_BUILDER,
           "ProjectScanRule:interpreter") {
         @Override public void onMatch(RelOptRuleCall call) {
@@ -98,6 +94,12 @@ public abstract class ProjectTableScanRule extends RelOptRule {
 
   //~ Methods ----------------------------------------------------------------
 
+  protected static boolean test(TableScan scan) {
+    // We can only push projects into a ProjectableFilterableTable.
+    final RelOptTable table = scan.getTable();
+    return table.unwrap(ProjectableFilterableTable.class) != null;
+  }
+
   protected void apply(RelOptRuleCall call, Project project, TableScan scan) {
     final RelOptTable table = scan.getTable();
     assert table.unwrap(ProjectableFilterableTable.class) != null;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ProjectToWindowRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ProjectToWindowRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ProjectToWindowRule.java
index 4b7a4dc..b85fd44 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ProjectToWindowRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ProjectToWindowRule.java
@@ -38,7 +38,6 @@ import org.apache.calcite.rex.RexOver;
 import org.apache.calcite.rex.RexProgram;
 import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.rex.RexWindow;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableIntList;
@@ -48,11 +47,9 @@ import org.apache.calcite.util.graph.DefaultEdge;
 import org.apache.calcite.util.graph.DirectedGraph;
 import org.apache.calcite.util.graph.TopologicalOrderIterator;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
 
 import java.util.ArrayDeque;
 import java.util.ArrayList;
@@ -78,20 +75,6 @@ import java.util.Set;
 public abstract class ProjectToWindowRule extends RelOptRule {
   //~ Static fields/initializers ---------------------------------------------
 
-  private static final Predicate<Calc> PREDICATE =
-      new PredicateImpl<Calc>() {
-        public boolean test(Calc calc) {
-          return RexOver.containsOver(calc.getProgram());
-        }
-      };
-
-  private static final Predicate<Project> PREDICATE2 =
-      new PredicateImpl<Project>() {
-        public boolean test(Project project) {
-          return RexOver.containsOver(project.getProjects(), null);
-        }
-      };
-
   public static final ProjectToWindowRule INSTANCE =
       new CalcToWindowRule(RelFactories.LOGICAL_BUILDER);
 
@@ -129,7 +112,8 @@ public abstract class ProjectToWindowRule extends RelOptRule {
      */
     public CalcToWindowRule(RelBuilderFactory relBuilderFactory) {
       super(
-          operand(Calc.class, null, PREDICATE, any()),
+          operandJ(Calc.class, null,
+              calc -> RexOver.containsOver(calc.getProgram()), any()),
           relBuilderFactory, "ProjectToWindowRule");
     }
 
@@ -158,7 +142,10 @@ public abstract class ProjectToWindowRule extends RelOptRule {
      */
     public ProjectToLogicalProjectAndWindowRule(
         RelBuilderFactory relBuilderFactory) {
-      super(operand(Project.class, null, PREDICATE2, any()),
+      super(
+          operandJ(Project.class, null,
+              project -> RexOver.containsOver(project.getProjects(), null),
+              any()),
           relBuilderFactory, "ProjectToWindowRule:project");
     }
 
@@ -191,11 +178,7 @@ public abstract class ProjectToWindowRule extends RelOptRule {
           if (!program.projectsOnlyIdentity()) {
             relBuilder.project(
                 Lists.transform(program.getProjectList(),
-                    new Function<RexLocalRef, RexNode>() {
-                      public RexNode apply(RexLocalRef a0) {
-                        return program.expandLocalRef(a0);
-                      }
-                    }),
+                    program::expandLocalRef),
                 calc.getRowType().getFieldNames());
           }
           return relBuilder.build();
@@ -314,7 +297,7 @@ public abstract class ProjectToWindowRule extends RelOptRule {
 
           // This RexOver cannot be added into any existing cohort
           if (!isFound) {
-            final Set<Integer> newSet = Sets.newHashSet(i);
+            final Set<Integer> newSet = new HashSet<>(ImmutableList.of(i));
             windowToIndices.add(Pair.of(over.getWindow(), newSet));
           }
         }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/PruneEmptyRules.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/PruneEmptyRules.java b/core/src/main/java/org/apache/calcite/rel/rules/PruneEmptyRules.java
index f6a89ad..1cc48b5 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/PruneEmptyRules.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/PruneEmptyRules.java
@@ -37,15 +37,14 @@ import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-
 import java.util.ArrayList;
 import java.util.List;
+import java.util.function.Predicate;
 
 import static org.apache.calcite.plan.RelOptRule.any;
 import static org.apache.calcite.plan.RelOptRule.none;
 import static org.apache.calcite.plan.RelOptRule.operand;
+import static org.apache.calcite.plan.RelOptRule.operandJ;
 import static org.apache.calcite.plan.RelOptRule.some;
 import static org.apache.calcite.plan.RelOptRule.unordered;
 
@@ -76,7 +75,7 @@ public abstract class PruneEmptyRules {
   public static final RelOptRule UNION_INSTANCE =
       new RelOptRule(
           operand(LogicalUnion.class,
-              unordered(operand(Values.class, null, Values.IS_EMPTY, none()))),
+              unordered(operandJ(Values.class, null, Values::isEmpty, none()))),
           "Union") {
         public void onMatch(RelOptRuleCall call) {
           final LogicalUnion union = call.rel(0);
@@ -124,7 +123,8 @@ public abstract class PruneEmptyRules {
   public static final RelOptRule MINUS_INSTANCE =
       new RelOptRule(
           operand(LogicalMinus.class,
-              unordered(operand(Values.class, null, Values.IS_EMPTY, none()))),
+              unordered(
+                  operandJ(Values.class, null, Values::isEmpty, none()))),
           "Minus") {
         public void onMatch(RelOptRuleCall call) {
           final LogicalMinus minus = call.rel(0);
@@ -177,7 +177,8 @@ public abstract class PruneEmptyRules {
   public static final RelOptRule INTERSECT_INSTANCE =
       new RelOptRule(
           operand(LogicalIntersect.class,
-              unordered(operand(Values.class, null, Values.IS_EMPTY, none()))),
+              unordered(
+                  operandJ(Values.class, null, Values::isEmpty, none()))),
           "Intersect") {
         public void onMatch(RelOptRuleCall call) {
           LogicalIntersect intersect = call.rel(0);
@@ -203,8 +204,9 @@ public abstract class PruneEmptyRules {
    * </ul>
    */
   public static final RelOptRule PROJECT_INSTANCE =
-      new RemoveEmptySingleRule(Project.class, Predicates.<Project>alwaysTrue(),
-          RelFactories.LOGICAL_BUILDER, "PruneEmptyProject");
+      new RemoveEmptySingleRule(Project.class,
+          (Predicate<Project>) project -> true, RelFactories.LOGICAL_BUILDER,
+          "PruneEmptyProject");
 
   /**
    * Rule that converts a {@link org.apache.calcite.rel.logical.LogicalFilter}
@@ -271,7 +273,8 @@ public abstract class PruneEmptyRules {
    * @see AggregateValuesRule
    */
   public static final RelOptRule AGGREGATE_INSTANCE =
-      new RemoveEmptySingleRule(Aggregate.class, Aggregate.IS_NOT_GRAND_TOTAL,
+      new RemoveEmptySingleRule(Aggregate.class,
+          (Predicate<Aggregate>) Aggregate::isNotGrandTotal,
           RelFactories.LOGICAL_BUILDER, "PruneEmptyAggregate");
 
   /**
@@ -288,7 +291,7 @@ public abstract class PruneEmptyRules {
       new RelOptRule(
           operand(Join.class,
               some(
-                  operand(Values.class, null, Values.IS_EMPTY, none()),
+                  operandJ(Values.class, null, Values::isEmpty, none()),
                   operand(RelNode.class, any()))),
               "PruneEmptyJoin(left)") {
         @Override public void onMatch(RelOptRuleCall call) {
@@ -317,7 +320,7 @@ public abstract class PruneEmptyRules {
           operand(Join.class,
               some(
                   operand(RelNode.class, any()),
-                  operand(Values.class, null, Values.IS_EMPTY, none()))),
+                  operandJ(Values.class, null, Values::isEmpty, none()))),
               "PruneEmptyJoin(right)") {
         @Override public void onMatch(RelOptRuleCall call) {
           Join join = call.rel(0);
@@ -333,10 +336,10 @@ public abstract class PruneEmptyRules {
   /** Planner rule that converts a single-rel (e.g. project, sort, aggregate or
    * filter) on top of the empty relational expression into empty. */
   public static class RemoveEmptySingleRule extends RelOptRule {
-    /** Creatse a simple RemoveEmptySingleRule. */
+    /** Creates a simple RemoveEmptySingleRule. */
     public <R extends SingleRel> RemoveEmptySingleRule(Class<R> clazz,
         String description) {
-      this(clazz, Predicates.<R>alwaysTrue(), RelFactories.LOGICAL_BUILDER,
+      this(clazz, (Predicate<R>) project -> true, RelFactories.LOGICAL_BUILDER,
           description);
     }
 
@@ -345,11 +348,20 @@ public abstract class PruneEmptyRules {
         Predicate<R> predicate, RelBuilderFactory relBuilderFactory,
         String description) {
       super(
-          operand(clazz, null, predicate,
-              operand(Values.class, null, Values.IS_EMPTY, none())),
+          operandJ(clazz, null, predicate,
+              operandJ(Values.class, null, Values::isEmpty, none())),
           relBuilderFactory, description);
     }
 
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed before 2.0
+    public <R extends SingleRel> RemoveEmptySingleRule(Class<R> clazz,
+        com.google.common.base.Predicate<R> predicate,
+        RelBuilderFactory relBuilderFactory, String description) {
+      this(clazz, (Predicate<R>) predicate::apply, relBuilderFactory,
+          description);
+    }
+
     public void onMatch(RelOptRuleCall call) {
       SingleRel single = call.rel(0);
       call.transformTo(call.builder().push(single).empty().build());

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/PushProjector.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/PushProjector.java b/core/src/main/java/org/apache/calcite/rel/rules/PushProjector.java
index 60a9663..22b8d63 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/PushProjector.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/PushProjector.java
@@ -32,7 +32,6 @@ import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.rex.RexVisitorImpl;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SemiJoinType;
 import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.tools.RelBuilder;
@@ -40,16 +39,15 @@ import org.apache.calcite.util.BitSets;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
+import java.util.function.Predicate;
 
 /**
  * PushProjector is a utility class used to perform operations used in push
@@ -212,7 +210,7 @@ public class PushProjector {
     this.origFilter = origFilter;
     this.childRel = childRel;
     this.preserveExprCondition = preserveExprCondition;
-    this.relBuilder = Preconditions.checkNotNull(relBuilder);
+    this.relBuilder = Objects.requireNonNull(relBuilder);
     if (origProj == null) {
       origProjExprs = ImmutableList.of();
     } else {
@@ -615,7 +613,7 @@ public class PushProjector {
    * @return the created projection
    */
   public RelNode createNewProject(RelNode projChild, int[] adjustments) {
-    final List<Pair<RexNode, String>> projects = Lists.newArrayList();
+    final List<Pair<RexNode, String>> projects = new ArrayList<>();
 
     if (origProj != null) {
       for (Pair<RexNode, String> p : origProj.getNamedProjects()) {
@@ -850,34 +848,19 @@ public class PushProjector {
     /**
      * Constant condition that replies {@code false} for all expressions.
      */
-    ExprCondition FALSE =
-        new ExprConditionImpl() {
-          @Override public boolean test(RexNode expr) {
-            return false;
-          }
-        };
+    ExprCondition FALSE = expr -> false;
 
     /**
      * Constant condition that replies {@code true} for all expressions.
      */
-    ExprCondition TRUE =
-        new ExprConditionImpl() {
-          @Override public boolean test(RexNode expr) {
-            return true;
-          }
-        };
-  }
-
-  /** Implementation of {@link ExprCondition}. */
-  abstract static class ExprConditionImpl extends PredicateImpl<RexNode>
-      implements ExprCondition {
+    ExprCondition TRUE = expr -> true;
   }
 
   /**
    * An expression condition that evaluates to true if the expression is
    * a call to one of a set of operators.
    */
-  class OperatorExprCondition extends ExprConditionImpl {
+  class OperatorExprCondition implements ExprCondition {
     private final Set<SqlOperator> operatorSet;
 
     /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ReduceExpressionsRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ReduceExpressionsRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ReduceExpressionsRule.java
index 296cf35..a3ae9d9 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ReduceExpressionsRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ReduceExpressionsRule.java
@@ -377,7 +377,7 @@ public abstract class ReduceExpressionsRule extends RelOptRule {
       final List<RexNode> exprList = program.getExprList();
 
       // Form a list of expressions with sub-expressions fully expanded.
-      final List<RexNode> expandedExprList = Lists.newArrayList();
+      final List<RexNode> expandedExprList = new ArrayList<>();
       final RexShuttle shuttle =
           new RexShuttle() {
             public RexNode visitLocalRef(RexLocalRef localRef) {
@@ -394,7 +394,7 @@ public abstract class ReduceExpressionsRule extends RelOptRule {
             new RexProgramBuilder(
                 calc.getInput().getRowType(),
                 calc.getCluster().getRexBuilder());
-        final List<RexLocalRef> list = Lists.newArrayList();
+        final List<RexLocalRef> list = new ArrayList<>();
         for (RexNode expr : expandedExprList) {
           list.add(builder.registerInput(expr));
         }
@@ -563,9 +563,9 @@ public abstract class ReduceExpressionsRule extends RelOptRule {
     changed |= new CaseShuttle().mutate(expList);
 
     // Find reducible expressions.
-    final List<RexNode> constExps = Lists.newArrayList();
-    List<Boolean> addCasts = Lists.newArrayList();
-    final List<RexNode> removableCasts = Lists.newArrayList();
+    final List<RexNode> constExps = new ArrayList<>();
+    List<Boolean> addCasts = new ArrayList<>();
+    final List<RexNode> removableCasts = new ArrayList<>();
     findReducibleExps(rel.getCluster().getTypeFactory(), expList,
         predicates.constantMap, constExps, addCasts, removableCasts);
     if (constExps.isEmpty() && removableCasts.isEmpty()) {
@@ -577,7 +577,7 @@ public abstract class ReduceExpressionsRule extends RelOptRule {
     // reducing that argument to a constant first will result in not being
     // able to locate the original cast expression.
     if (!removableCasts.isEmpty()) {
-      final List<RexNode> reducedExprs = Lists.newArrayList();
+      final List<RexNode> reducedExprs = new ArrayList<>();
       for (RexNode exp : removableCasts) {
         RexCall call = (RexCall) exp;
         reducedExprs.add(call.getOperands().get(0));
@@ -616,7 +616,7 @@ public abstract class ReduceExpressionsRule extends RelOptRule {
       return changed;
     }
 
-    final List<RexNode> reducedValues = Lists.newArrayList();
+    final List<RexNode> reducedValues = new ArrayList<>();
     executor.reduce(simplify.rexBuilder, constExps2, reducedValues);
 
     // Use RexNode.digest to judge whether each newly generated RexNode

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/SemiJoinRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/SemiJoinRule.java b/core/src/main/java/org/apache/calcite/rel/rules/SemiJoinRule.java
index 39db46d..c236015 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/SemiJoinRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/SemiJoinRule.java
@@ -28,16 +28,14 @@ import org.apache.calcite.rel.core.Project;
 import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.ImmutableIntList;
 
-import com.google.common.base.Predicate;
-import com.google.common.collect.Lists;
-
+import java.util.ArrayList;
 import java.util.List;
+import java.util.function.Predicate;
 
 /**
  * Planner rule that creates a {@code SemiJoinRule} from a
@@ -46,25 +44,19 @@ import java.util.List;
  */
 public abstract class SemiJoinRule extends RelOptRule {
   private static final Predicate<Join> IS_LEFT_OR_INNER =
-      new PredicateImpl<Join>() {
-        public boolean test(Join input) {
-          switch (input.getJoinType()) {
-          case LEFT:
-          case INNER:
-            return true;
-          default:
-            return false;
-          }
+      join -> {
+        switch (join.getJoinType()) {
+        case LEFT:
+        case INNER:
+          return true;
+        default:
+          return false;
         }
       };
 
   /* Tests if an Aggregate always produces 1 row and 0 columns. */
   private static final Predicate<Aggregate> IS_EMPTY_AGGREGATE =
-      new PredicateImpl<Aggregate>() {
-        public boolean test(Aggregate input) {
-          return input.getRowType().getFieldCount() == 0;
-        }
-      };
+      aggregate -> aggregate.getRowType().getFieldCount() == 0;
 
   public static final SemiJoinRule PROJECT =
       new ProjectToSemiJoinRule(Project.class, Join.class, Aggregate.class,
@@ -80,7 +72,7 @@ public abstract class SemiJoinRule extends RelOptRule {
     super(
         operand(projectClass,
             some(
-                operand(joinClass, null, IS_LEFT_OR_INNER,
+                operandJ(joinClass, null, IS_LEFT_OR_INNER,
                     some(operand(RelNode.class, any()),
                         operand(aggregateClass, any()))))),
         relBuilderFactory, description);
@@ -89,9 +81,9 @@ public abstract class SemiJoinRule extends RelOptRule {
   protected SemiJoinRule(Class<Join> joinClass, Class<Aggregate> aggregateClass,
       RelBuilderFactory relBuilderFactory, String description) {
     super(
-        operand(joinClass, null, IS_LEFT_OR_INNER,
+        operandJ(joinClass, null, IS_LEFT_OR_INNER,
             some(operand(RelNode.class, any()),
-                operand(aggregateClass, null, IS_EMPTY_AGGREGATE, any()))),
+                operandJ(aggregateClass, null, IS_EMPTY_AGGREGATE, any()))),
         relBuilderFactory, description);
   }
 
@@ -123,7 +115,7 @@ public abstract class SemiJoinRule extends RelOptRule {
     relBuilder.push(left);
     switch (join.getJoinType()) {
     case INNER:
-      final List<Integer> newRightKeyBuilder = Lists.newArrayList();
+      final List<Integer> newRightKeyBuilder = new ArrayList<>();
       final List<Integer> aggregateKeys = aggregate.getGroupSet().asList();
       for (int key : joinInfo.rightKeys) {
         newRightKeyBuilder.add(aggregateKeys.get(key));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/SortJoinTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/SortJoinTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/SortJoinTransposeRule.java
index 04fbb6d..6a1c76b 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/SortJoinTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/SortJoinTransposeRule.java
@@ -34,7 +34,6 @@ import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.tools.RelBuilderFactory;
 
-
 /**
  * Planner rule that pushes a {@link org.apache.calcite.rel.core.Sort} past a
  * {@link org.apache.calcite.rel.core.Join}.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/SortProjectTransposeRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/SortProjectTransposeRule.java b/core/src/main/java/org/apache/calcite/rel/rules/SortProjectTransposeRule.java
index 19cde5f..8bdcdd2 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/SortProjectTransposeRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/SortProjectTransposeRule.java
@@ -140,7 +140,7 @@ public class SortProjectTransposeRule extends RelOptRule {
     RelNode newProject =
         project.copy(
             sort.getTraitSet(),
-            ImmutableList.<RelNode>of(newSort));
+            ImmutableList.of(newSort));
     // Not only is newProject equivalent to sort;
     // newSort is equivalent to project's input
     // (but only if the sort is not also applying an offset/limit).

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/SubQueryRemoveRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/SubQueryRemoveRule.java b/core/src/main/java/org/apache/calcite/rel/rules/SubQueryRemoveRule.java
index 628219f..974c57d 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/SubQueryRemoveRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/SubQueryRemoveRule.java
@@ -497,8 +497,9 @@ public abstract class SubQueryRemoveRule extends RelOptRule {
   public static class SubQueryProjectRemoveRule extends SubQueryRemoveRule {
     public SubQueryProjectRemoveRule(RelBuilderFactory relBuilderFactory) {
       super(
-          operand(Project.class, null, RexUtil.SubQueryFinder.PROJECT_PREDICATE,
-              any()), relBuilderFactory, "SubQueryRemoveRule:Project");
+          operandJ(Project.class, null,
+              RexUtil.SubQueryFinder::containsSubQuery, any()),
+          relBuilderFactory, "SubQueryRemoveRule:Project");
     }
 
     public void onMatch(RelOptRuleCall call) {
@@ -526,7 +527,7 @@ public abstract class SubQueryRemoveRule extends RelOptRule {
   public static class SubQueryFilterRemoveRule extends SubQueryRemoveRule {
     public SubQueryFilterRemoveRule(RelBuilderFactory relBuilderFactory) {
       super(
-          operand(Filter.class, null, RexUtil.SubQueryFinder.FILTER_PREDICATE,
+          operandJ(Filter.class, null, RexUtil.SubQueryFinder::containsSubQuery,
               any()), relBuilderFactory, "SubQueryRemoveRule:Filter");
     }
 
@@ -563,7 +564,7 @@ public abstract class SubQueryRemoveRule extends RelOptRule {
   public static class SubQueryJoinRemoveRule extends SubQueryRemoveRule {
     public SubQueryJoinRemoveRule(RelBuilderFactory relBuilderFactory) {
       super(
-          operand(Join.class, null, RexUtil.SubQueryFinder.JOIN_PREDICATE,
+          operandJ(Join.class, null, RexUtil.SubQueryFinder::containsSubQuery,
               any()), relBuilderFactory, "SubQueryRemoveRule:Join");
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/UnionPullUpConstantsRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/UnionPullUpConstantsRule.java b/core/src/main/java/org/apache/calcite/rel/rules/UnionPullUpConstantsRule.java
index 9fb0426..b7cfab3 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/UnionPullUpConstantsRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/UnionPullUpConstantsRule.java
@@ -118,7 +118,7 @@ public class UnionPullUpConstantsRule extends RelOptRule {
       List<Pair<RexNode, String>> newChildExprs = new ArrayList<>();
       for (int j : refsIndex) {
         newChildExprs.add(
-            Pair.<RexNode, String>of(rexBuilder.makeInputRef(input, j),
+            Pair.of(rexBuilder.makeInputRef(input, j),
                 input.getRowType().getFieldList().get(j).getName()));
       }
       if (newChildExprs.isEmpty()) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/rules/ValuesReduceRule.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/ValuesReduceRule.java b/core/src/main/java/org/apache/calcite/rel/rules/ValuesReduceRule.java
index b8b02c6..3774430 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/ValuesReduceRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/ValuesReduceRule.java
@@ -75,7 +75,7 @@ public abstract class ValuesReduceRule extends RelOptRule {
   public static final ValuesReduceRule FILTER_INSTANCE =
       new ValuesReduceRule(
           operand(LogicalFilter.class,
-              operand(LogicalValues.class, null, Values.IS_NOT_EMPTY, none())),
+              operandJ(LogicalValues.class, null, Values::isNotEmpty, none())),
           RelFactories.LOGICAL_BUILDER,
           "ValuesReduceRule(Filter)") {
         public void onMatch(RelOptRuleCall call) {
@@ -92,7 +92,7 @@ public abstract class ValuesReduceRule extends RelOptRule {
   public static final ValuesReduceRule PROJECT_INSTANCE =
       new ValuesReduceRule(
           operand(LogicalProject.class,
-              operand(LogicalValues.class, null, Values.IS_NOT_EMPTY, none())),
+              operandJ(LogicalValues.class, null, Values::isNotEmpty, none())),
           RelFactories.LOGICAL_BUILDER,
           "ValuesReduceRule(Project)") {
         public void onMatch(RelOptRuleCall call) {
@@ -110,7 +110,7 @@ public abstract class ValuesReduceRule extends RelOptRule {
       new ValuesReduceRule(
           operand(LogicalProject.class,
               operand(LogicalFilter.class,
-                  operand(LogicalValues.class, null, Values.IS_NOT_EMPTY,
+                  operandJ(LogicalValues.class, null, Values::isNotEmpty,
                       none()))),
           RelFactories.LOGICAL_BUILDER,
           "ValuesReduceRule(Project-Filter)") {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/stream/StreamRules.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/stream/StreamRules.java b/core/src/main/java/org/apache/calcite/rel/stream/StreamRules.java
index a1e0d58..02d8e68 100644
--- a/core/src/main/java/org/apache/calcite/rel/stream/StreamRules.java
+++ b/core/src/main/java/org/apache/calcite/rel/stream/StreamRules.java
@@ -45,8 +45,8 @@ import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -130,7 +130,8 @@ public class StreamRules {
     public DeltaAggregateTransposeRule(RelBuilderFactory relBuilderFactory) {
       super(
           operand(Delta.class,
-              operand(Aggregate.class, null, Aggregate.NO_INDICATOR, any())),
+              operandJ(Aggregate.class, null, Aggregate::noIndicator,
+                  any())),
           relBuilderFactory, null);
     }
 
@@ -193,7 +194,7 @@ public class StreamRules {
       final Delta delta = call.rel(0);
       Util.discard(delta);
       final Union union = call.rel(1);
-      final List<RelNode> newInputs = Lists.newArrayList();
+      final List<RelNode> newInputs = new ArrayList<>();
       for (RelNode input : union.getInputs()) {
         final LogicalDelta newDelta =
             LogicalDelta.create(input);
@@ -326,7 +327,7 @@ public class StreamRules {
           join.isSemiJoinDone(),
           ImmutableList.copyOf(join.getSystemFieldList()));
 
-      List<RelNode> inputsToUnion = Lists.newArrayList();
+      List<RelNode> inputsToUnion = new ArrayList<>();
       inputsToUnion.add(joinL);
       inputsToUnion.add(joinR);
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/type/DynamicRecordTypeImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/type/DynamicRecordTypeImpl.java b/core/src/main/java/org/apache/calcite/rel/type/DynamicRecordTypeImpl.java
index 82b6714..50f426b 100644
--- a/core/src/main/java/org/apache/calcite/rel/type/DynamicRecordTypeImpl.java
+++ b/core/src/main/java/org/apache/calcite/rel/type/DynamicRecordTypeImpl.java
@@ -20,7 +20,8 @@ import org.apache.calcite.sql.type.SqlTypeExplicitPrecedenceList;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.Pair;
 
-import java.util.Collections;
+import com.google.common.collect.ImmutableList;
+
 import java.util.List;
 
 /**
@@ -69,7 +70,7 @@ public class DynamicRecordTypeImpl extends DynamicRecordType {
   }
 
   @Override public RelDataTypePrecedenceList getPrecedenceList() {
-    return new SqlTypeExplicitPrecedenceList(Collections.<SqlTypeName>emptyList());
+    return new SqlTypeExplicitPrecedenceList(ImmutableList.of());
   }
 
   protected void generateTypeString(StringBuilder sb, boolean withDetail) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactory.java b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactory.java
index da65d87..c83e6a2 100644
--- a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactory.java
+++ b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactory.java
@@ -23,12 +23,11 @@ import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.sql.validate.SqlValidatorUtil;
 
-import com.google.common.base.Preconditions;
-
 import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * RelDataTypeFactory is a factory for datatype descriptors. It defines methods
@@ -408,7 +407,7 @@ public interface RelDataTypeFactory {
      * Creates a Builder with the given type factory.
      */
     public Builder(RelDataTypeFactory typeFactory) {
-      this.typeFactory = Preconditions.checkNotNull(typeFactory);
+      this.typeFactory = Objects.requireNonNull(typeFactory);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java
index 4151c1a..d529ff7 100644
--- a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java
+++ b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeFactoryImpl.java
@@ -25,7 +25,6 @@ import org.apache.calcite.sql.type.SqlTypeUtil;
 import org.apache.calcite.util.Glossary;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
@@ -56,24 +55,23 @@ public abstract class RelDataTypeFactoryImpl implements RelDataTypeFactory {
   private static final LoadingCache<Object, RelDataType> CACHE =
       CacheBuilder.newBuilder()
           .softValues()
-          .build(
-              new CacheLoader<Object, RelDataType>() {
-                @Override public RelDataType load(@Nonnull Object k) {
-                  if (k instanceof RelDataType) {
-                    return (RelDataType) k;
-                  }
-                  @SuppressWarnings("unchecked")
-                  final Key key = (Key) k;
-                  final ImmutableList.Builder<RelDataTypeField> list =
-                      ImmutableList.builder();
-                  for (int i = 0; i < key.names.size(); i++) {
-                    list.add(
-                        new RelDataTypeFieldImpl(
-                            key.names.get(i), i, key.types.get(i)));
-                  }
-                  return new RelRecordType(key.kind, list.build());
-                }
-              });
+          .build(CacheLoader.from(RelDataTypeFactoryImpl::keyToType));
+
+  private static RelDataType keyToType(@Nonnull Object k) {
+    if (k instanceof RelDataType) {
+      return (RelDataType) k;
+    }
+    @SuppressWarnings("unchecked")
+    final Key key = (Key) k;
+    final ImmutableList.Builder<RelDataTypeField> list =
+        ImmutableList.builder();
+    for (int i = 0; i < key.names.size(); i++) {
+      list.add(
+          new RelDataTypeFieldImpl(
+              key.names.get(i), i, key.types.get(i)));
+    }
+    return new RelRecordType(key.kind, list.build());
+  }
 
   private static final Map<Class, RelDataTypeFamily> CLASS_FAMILIES =
       ImmutableMap.<Class, RelDataTypeFamily>builder()
@@ -104,7 +102,7 @@ public abstract class RelDataTypeFactoryImpl implements RelDataTypeFactory {
 
   /** Creates a type factory. */
   protected RelDataTypeFactoryImpl(RelDataTypeSystem typeSystem) {
-    this.typeSystem = Preconditions.checkNotNull(typeSystem);
+    this.typeSystem = Objects.requireNonNull(typeSystem);
   }
 
   //~ Methods ----------------------------------------------------------------
@@ -312,7 +310,7 @@ public abstract class RelDataTypeFactoryImpl implements RelDataTypeFactory {
   public RelDataType createTypeWithNullability(
       final RelDataType type,
       final boolean nullable) {
-    Preconditions.checkNotNull(type);
+    Objects.requireNonNull(type);
     RelDataType newType;
     if (type.isNullable() == nullable) {
       newType = type;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeField.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeField.java b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeField.java
index 36acc1b..913c3a3 100644
--- a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeField.java
+++ b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeField.java
@@ -16,8 +16,6 @@
  */
 package org.apache.calcite.rel.type;
 
-import com.google.common.base.Function;
-
 import java.util.Map;
 
 /**
@@ -34,8 +32,12 @@ public interface RelDataTypeField extends Map.Entry<String, RelDataType> {
   /**
    * Function to transform a set of {@link RelDataTypeField} to
    * a set of {@link Integer} of the field keys.
+   *
+   * @deprecated Use {@code RelDataTypeField::getIndex}
    */
-  class ToFieldIndex implements Function<RelDataTypeField, Integer> {
+  @Deprecated // to be removed before 2.0
+  class ToFieldIndex
+      implements com.google.common.base.Function<RelDataTypeField, Integer> {
     @Override public Integer apply(RelDataTypeField o) {
       return o.getIndex();
     }
@@ -44,8 +46,12 @@ public interface RelDataTypeField extends Map.Entry<String, RelDataType> {
   /**
    * Function to transform a set of {@link RelDataTypeField} to
    * a set of {@link String} of the field names.
+   *
+   * @deprecated Use {@code RelDataTypeField::getName}
    */
-  class ToFieldName implements Function<RelDataTypeField, String> {
+  @Deprecated // to be removed before 2.0
+  class ToFieldName
+      implements com.google.common.base.Function<RelDataTypeField, String> {
     @Override public String apply(RelDataTypeField o) {
       return o.getName();
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeImpl.java b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeImpl.java
index a559686..5c001f7 100644
--- a/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeImpl.java
+++ b/core/src/main/java/org/apache/calcite/rel/type/RelDataTypeImpl.java
@@ -27,10 +27,10 @@ import org.apache.calcite.util.Util;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 
 import java.io.Serializable;
 import java.nio.charset.Charset;
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -85,7 +85,7 @@ public abstract class RelDataTypeImpl
       }
     }
     if (elideRecord) {
-      final List<Slot> slots = Lists.newArrayList();
+      final List<Slot> slots = new ArrayList<>();
       getFieldRecurse(slots, this, 0, fieldName, caseSensitive);
     loop:
       for (Slot slot : slots) {
@@ -298,11 +298,7 @@ public abstract class RelDataTypeImpl
    */
   public static RelProtoDataType proto(final RelDataType protoType) {
     assert protoType != null;
-    return new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory typeFactory) {
-        return typeFactory.copyType(protoType);
-      }
-    };
+    return typeFactory -> typeFactory.copyType(protoType);
   }
 
   /** Returns a {@link org.apache.calcite.rel.type.RelProtoDataType}
@@ -318,11 +314,9 @@ public abstract class RelDataTypeImpl
   public static RelProtoDataType proto(final SqlTypeName typeName,
       final boolean nullable) {
     assert typeName != null;
-    return new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory typeFactory) {
-        final RelDataType type = typeFactory.createSqlType(typeName);
-        return typeFactory.createTypeWithNullability(type, nullable);
-      }
+    return typeFactory -> {
+      final RelDataType type = typeFactory.createSqlType(typeName);
+      return typeFactory.createTypeWithNullability(type, nullable);
     };
   }
 
@@ -340,11 +334,9 @@ public abstract class RelDataTypeImpl
   public static RelProtoDataType proto(final SqlTypeName typeName,
       final int precision, final boolean nullable) {
     assert typeName != null;
-    return new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory typeFactory) {
-        final RelDataType type = typeFactory.createSqlType(typeName, precision);
-        return typeFactory.createTypeWithNullability(type, nullable);
-      }
+    return typeFactory -> {
+      final RelDataType type = typeFactory.createSqlType(typeName, precision);
+      return typeFactory.createTypeWithNullability(type, nullable);
     };
   }
 
@@ -362,12 +354,10 @@ public abstract class RelDataTypeImpl
    */
   public static RelProtoDataType proto(final SqlTypeName typeName,
       final int precision, final int scale, final boolean nullable) {
-    return new RelProtoDataType() {
-      public RelDataType apply(RelDataTypeFactory typeFactory) {
-        final RelDataType type =
-            typeFactory.createSqlType(typeName, precision, scale);
-        return typeFactory.createTypeWithNullability(type, nullable);
-      }
+    return typeFactory -> {
+      final RelDataType type =
+          typeFactory.createSqlType(typeName, precision, scale);
+      return typeFactory.createTypeWithNullability(type, nullable);
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rel/type/RelRecordType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rel/type/RelRecordType.java b/core/src/main/java/org/apache/calcite/rel/type/RelRecordType.java
index f8bf907..0bb4ed0 100644
--- a/core/src/main/java/org/apache/calcite/rel/type/RelRecordType.java
+++ b/core/src/main/java/org/apache/calcite/rel/type/RelRecordType.java
@@ -19,10 +19,9 @@ package org.apache.calcite.rel.type;
 import org.apache.calcite.linq4j.Ord;
 import org.apache.calcite.sql.type.SqlTypeName;
 
-import com.google.common.base.Preconditions;
-
 import java.io.Serializable;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * RelRecordType represents a structured type having named fields.
@@ -39,7 +38,7 @@ public class RelRecordType extends RelDataTypeImpl implements Serializable {
    */
   public RelRecordType(StructKind kind, List<RelDataTypeField> fields) {
     super(fields);
-    this.kind = Preconditions.checkNotNull(kind);
+    this.kind = Objects.requireNonNull(kind);
     computeDigest();
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexBuilder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexBuilder.java b/core/src/main/java/org/apache/calcite/rex/RexBuilder.java
index 5dcc85b..4a26cd8 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexBuilder.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexBuilder.java
@@ -20,7 +20,6 @@ import org.apache.calcite.avatica.util.ByteString;
 import org.apache.calcite.avatica.util.DateTimeUtils;
 import org.apache.calcite.avatica.util.Spaces;
 import org.apache.calcite.avatica.util.TimeUnit;
-import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.AggregateCall;
 import org.apache.calcite.rel.core.CorrelationId;
@@ -49,7 +48,6 @@ import org.apache.calcite.util.TimeString;
 import org.apache.calcite.util.TimestampString;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
@@ -62,6 +60,7 @@ import java.util.Arrays;
 import java.util.Calendar;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Factory for row expressions.
@@ -78,13 +77,6 @@ public class RexBuilder {
   public static final SqlSpecialOperator GET_OPERATOR =
       new SqlSpecialOperator("_get", SqlKind.OTHER_FUNCTION);
 
-  private static final Function<RelDataTypeField, RexInputRef> TO_INPUT_REF =
-      new Function<RelDataTypeField, RexInputRef>() {
-        public RexInputRef apply(RelDataTypeField input) {
-          return new RexInputRef(input.getIndex(), input.getType());
-        }
-      };
-
   //~ Instance fields --------------------------------------------------------
 
   protected final RelDataTypeFactory typeFactory;
@@ -128,7 +120,8 @@ public class RexBuilder {
   /** Creates a list of {@link org.apache.calcite.rex.RexInputRef} expressions,
    * projecting the fields of a given record type. */
   public List<? extends RexNode> identityProjects(final RelDataType rowType) {
-    return Lists.transform(rowType.getFieldList(), TO_INPUT_REF);
+    return Lists.transform(rowType.getFieldList(),
+        input -> new RexInputRef(input.getIndex(), input.getType()));
   }
 
   //~ Methods ----------------------------------------------------------------
@@ -273,7 +266,7 @@ public class RexBuilder {
       List<? extends RexNode> exprs) {
     return op.inferReturnType(
         new RexCallBinding(typeFactory, op, exprs,
-            ImmutableList.<RelCollation>of()));
+            ImmutableList.of()));
   }
 
   /**
@@ -391,7 +384,7 @@ public class RexBuilder {
                   new RexOver(
                       bigintType,
                       SqlStdOperatorTable.COUNT,
-                      ImmutableList.<RexNode>of(),
+                      ImmutableList.of(),
                       window,
                       distinct),
                   makeLiteral(
@@ -1110,7 +1103,7 @@ public class RexBuilder {
    * Creates a Date literal.
    */
   public RexLiteral makeDateLiteral(DateString date) {
-    return makeLiteral(Preconditions.checkNotNull(date),
+    return makeLiteral(Objects.requireNonNull(date),
         typeFactory.createSqlType(SqlTypeName.DATE), SqlTypeName.DATE);
   }
 
@@ -1124,7 +1117,7 @@ public class RexBuilder {
    * Creates a Time literal.
    */
   public RexLiteral makeTimeLiteral(TimeString time, int precision) {
-    return makeLiteral(Preconditions.checkNotNull(time),
+    return makeLiteral(Objects.requireNonNull(time),
         typeFactory.createSqlType(SqlTypeName.TIME, precision),
         SqlTypeName.TIME);
   }
@@ -1135,7 +1128,7 @@ public class RexBuilder {
   public RexLiteral makeTimeWithLocalTimeZoneLiteral(
       TimeString time,
       int precision) {
-    return makeLiteral(Preconditions.checkNotNull(time),
+    return makeLiteral(Objects.requireNonNull(time),
         typeFactory.createSqlType(SqlTypeName.TIME_WITH_LOCAL_TIME_ZONE, precision),
         SqlTypeName.TIME_WITH_LOCAL_TIME_ZONE);
   }
@@ -1152,7 +1145,7 @@ public class RexBuilder {
    */
   public RexLiteral makeTimestampLiteral(TimestampString timestamp,
       int precision) {
-    return makeLiteral(Preconditions.checkNotNull(timestamp),
+    return makeLiteral(Objects.requireNonNull(timestamp),
         typeFactory.createSqlType(SqlTypeName.TIMESTAMP, precision),
         SqlTypeName.TIMESTAMP);
   }
@@ -1163,7 +1156,7 @@ public class RexBuilder {
   public RexLiteral makeTimestampWithLocalTimeZoneLiteral(
       TimestampString timestamp,
       int precision) {
-    return makeLiteral(Preconditions.checkNotNull(timestamp),
+    return makeLiteral(Objects.requireNonNull(timestamp),
         typeFactory.createSqlType(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE, precision),
         SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE);
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexCall.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexCall.java b/core/src/main/java/org/apache/calcite/rex/RexCall.java
index ac9e09e..498d86e 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexCall.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexCall.java
@@ -22,10 +22,10 @@ import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlSyntax;
 import org.apache.calcite.util.Litmus;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.Objects;
 
 /**
  * An expression formed by a call to an operator with zero or more expressions
@@ -56,8 +56,8 @@ public class RexCall extends RexNode {
       RelDataType type,
       SqlOperator op,
       List<? extends RexNode> operands) {
-    this.type = Preconditions.checkNotNull(type);
-    this.op = Preconditions.checkNotNull(op);
+    this.type = Objects.requireNonNull(type);
+    this.op = Objects.requireNonNull(op);
     this.operands = ImmutableList.copyOf(operands);
     assert op.getKind() != null : op;
     assert op.validRexOperands(operands.size(), Litmus.THROW) : this;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexCorrelVariable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexCorrelVariable.java b/core/src/main/java/org/apache/calcite/rex/RexCorrelVariable.java
index 2f6197a..750a97b 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexCorrelVariable.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexCorrelVariable.java
@@ -20,7 +20,7 @@ import org.apache.calcite.rel.core.CorrelationId;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.sql.SqlKind;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /**
  * Reference to the current row of a correlating relational expression.
@@ -38,7 +38,7 @@ public class RexCorrelVariable extends RexVariable {
       CorrelationId id,
       RelDataType type) {
     super(id.getName(), type);
-    this.id = Preconditions.checkNotNull(id);
+    this.id = Objects.requireNonNull(id);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexExecutorImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexExecutorImpl.java b/core/src/main/java/org/apache/calcite/rex/RexExecutorImpl.java
index 99f8e78..a5e0aab 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexExecutorImpl.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexExecutorImpl.java
@@ -116,11 +116,8 @@ public class RexExecutorImpl implements RexExecutor {
   public void reduce(RexBuilder rexBuilder, List<RexNode> constExps,
       List<RexNode> reducedValues) {
     final String code = compile(rexBuilder, constExps,
-        new RexToLixTranslator.InputGetter() {
-          public Expression field(BlockBuilder list, int index,
-              Type storageType) {
-            throw new UnsupportedOperationException();
-          }
+        (list, index, storageType) -> {
+          throw new UnsupportedOperationException();
         });
 
     final RexExecutable executable = new RexExecutable(code, constExps);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexLiteral.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexLiteral.java b/core/src/main/java/org/apache/calcite/rex/RexLiteral.java
index 94ea886..ade5556 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexLiteral.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexLiteral.java
@@ -211,8 +211,8 @@ public class RexLiteral extends RexNode {
       RelDataType type,
       SqlTypeName typeName) {
     this.value = value;
-    this.type = Preconditions.checkNotNull(type);
-    this.typeName = Preconditions.checkNotNull(typeName);
+    this.type = Objects.requireNonNull(type);
+    this.typeName = Objects.requireNonNull(typeName);
     Preconditions.checkArgument(valueMatchesType(value, typeName, true));
     Preconditions.checkArgument((value == null) == type.isNullable());
     Preconditions.checkArgument(typeName != SqlTypeName.ANY);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexOver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexOver.java b/core/src/main/java/org/apache/calcite/rex/RexOver.java
index 7be2af3..fe7f7d9 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexOver.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexOver.java
@@ -25,6 +25,7 @@ import org.apache.calcite.util.Util;
 import com.google.common.base.Preconditions;
 
 import java.util.List;
+import java.util.Objects;
 
 /**
  * Call to an aggregate function over a window.
@@ -66,7 +67,7 @@ public class RexOver extends RexCall {
       boolean distinct) {
     super(type, op, operands);
     Preconditions.checkArgument(op.isAggregator());
-    this.window = Preconditions.checkNotNull(window);
+    this.window = Objects.requireNonNull(window);
     this.distinct = distinct;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexPermuteInputsShuttle.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexPermuteInputsShuttle.java b/core/src/main/java/org/apache/calcite/rex/RexPermuteInputsShuttle.java
index 1750477..1d8d41e 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexPermuteInputsShuttle.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexPermuteInputsShuttle.java
@@ -66,7 +66,7 @@ public class RexPermuteInputsShuttle extends RexShuttle {
    * otherwise works OK. */
   public static RexPermuteInputsShuttle of(Mappings.TargetMapping mapping) {
     return new RexPermuteInputsShuttle(mapping,
-        ImmutableList.<RelDataTypeField>of());
+        ImmutableList.of());
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexProgram.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexProgram.java b/core/src/main/java/org/apache/calcite/rex/RexProgram.java
index e710386..32e438c 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexProgram.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexProgram.java
@@ -34,7 +34,6 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Permutation;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Ordering;
 
 import java.io.PrintWriter;
@@ -514,7 +513,7 @@ public class RexProgram {
    * <p>Neither list is null.
    * The filters are evaluated first. */
   public Pair<ImmutableList<RexNode>, ImmutableList<RexNode>> split() {
-    final List<RexNode> filters = Lists.newArrayList();
+    final List<RexNode> filters = new ArrayList<>();
     if (condition != null) {
       RelOptUtil.decomposeConjunction(expandLocalRef(condition), filters);
     }
@@ -574,7 +573,7 @@ public class RexProgram {
       // to the output.
       outputCollations.add(RelCollations.of(fieldCollations));
     }
-    Collections.sort(outputCollations, Ordering.natural());
+    outputCollations.sort(Ordering.natural());
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexProgramBuilder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexProgramBuilder.java b/core/src/main/java/org/apache/calcite/rex/RexProgramBuilder.java
index 2964a48..a4a62d9 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexProgramBuilder.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexProgramBuilder.java
@@ -24,12 +24,11 @@ import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
-
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Workspace for constructing a {@link RexProgram}.
@@ -67,8 +66,8 @@ public class RexProgramBuilder {
    */
   private RexProgramBuilder(RelDataType inputRowType, RexBuilder rexBuilder,
       RexSimplify simplify) {
-    this.inputRowType = Preconditions.checkNotNull(inputRowType);
-    this.rexBuilder = Preconditions.checkNotNull(rexBuilder);
+    this.inputRowType = Objects.requireNonNull(inputRowType);
+    this.rexBuilder = Objects.requireNonNull(rexBuilder);
     this.simplify = simplify; // may be null
     this.validating = assertionsAreEnabled();
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexShuttle.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexShuttle.java b/core/src/main/java/org/apache/calcite/rex/RexShuttle.java
index 6714be1..d79dcbf 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexShuttle.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexShuttle.java
@@ -16,13 +16,11 @@
  */
 package org.apache.calcite.rex;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
 import java.util.ArrayList;
 import java.util.List;
-import javax.annotation.Nullable;
 
 /**
  * Passes over a row-expression, calling a handler method for each node,
@@ -269,11 +267,8 @@ public class RexShuttle implements RexVisitor<RexNode> {
    * Applies this shuttle to each expression in an iterable.
    */
   public final Iterable<RexNode> apply(Iterable<? extends RexNode> iterable) {
-    return Iterables.transform(iterable, new Function<RexNode, RexNode>() {
-      public RexNode apply(@Nullable RexNode t) {
-        return t == null ? null : t.accept(RexShuttle.this);
-      }
-    });
+    return Iterables.transform(iterable,
+        t -> t == null ? null : t.accept(RexShuttle.this));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexSimplify.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexSimplify.java b/core/src/main/java/org/apache/calcite/rex/RexSimplify.java
index d51ffe7..8ebf045 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexSimplify.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexSimplify.java
@@ -31,7 +31,6 @@ import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.BoundType;
 import com.google.common.collect.ImmutableList;
@@ -47,6 +46,7 @@ import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.function.Function;
 
@@ -76,11 +76,11 @@ public class RexSimplify {
   /** Internal constructor. */
   private RexSimplify(RexBuilder rexBuilder, RelOptPredicateList predicates,
       boolean unknownAsFalse, boolean paranoid, RexExecutor executor) {
-    this.rexBuilder = Preconditions.checkNotNull(rexBuilder);
-    this.predicates = Preconditions.checkNotNull(predicates);
+    this.rexBuilder = Objects.requireNonNull(rexBuilder);
+    this.predicates = Objects.requireNonNull(predicates);
     this.unknownAsFalse = unknownAsFalse;
     this.paranoid = paranoid;
-    this.executor = Preconditions.checkNotNull(executor);
+    this.executor = Objects.requireNonNull(executor);
   }
 
   @Deprecated // to be removed before 2.0
@@ -1152,8 +1152,8 @@ public class RexSimplify {
         break;
       }
       final List<RexNode> reducedValues = new ArrayList<>();
-      executor.reduce(rexBuilder, ImmutableList.<RexNode>of(e), reducedValues);
-      return Preconditions.checkNotNull(
+      executor.reduce(rexBuilder, ImmutableList.of(e), reducedValues);
+      return Objects.requireNonNull(
           Iterables.getOnlyElement(reducedValues));
     default:
       return e;
@@ -1504,9 +1504,9 @@ public class RexSimplify {
     final RexLiteral literal;
 
     private Comparison(RexNode ref, SqlKind kind, RexLiteral literal) {
-      this.ref = Preconditions.checkNotNull(ref);
-      this.kind = Preconditions.checkNotNull(kind);
-      this.literal = Preconditions.checkNotNull(literal);
+      this.ref = Objects.requireNonNull(ref);
+      this.kind = Objects.requireNonNull(kind);
+      this.literal = Objects.requireNonNull(literal);
     }
 
     /** Creates a comparison, or returns null. */
@@ -1545,8 +1545,8 @@ public class RexSimplify {
     final SqlKind kind;
 
     private IsPredicate(RexNode ref, SqlKind kind) {
-      this.ref = Preconditions.checkNotNull(ref);
-      this.kind = Preconditions.checkNotNull(kind);
+      this.ref = Objects.requireNonNull(ref);
+      this.kind = Objects.requireNonNull(kind);
     }
 
     /** Creates an IS predicate, or returns null. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexSqlStandardConvertletTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexSqlStandardConvertletTable.java b/core/src/main/java/org/apache/calcite/rex/RexSqlStandardConvertletTable.java
index e69dfc1..e93df95 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexSqlStandardConvertletTable.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexSqlStandardConvertletTable.java
@@ -189,26 +189,21 @@ public class RexSqlStandardConvertletTable
    */
   private void registerTypeAppendOp(final SqlOperator op) {
     registerOp(
-        op,
-        new RexSqlConvertlet() {
-          public SqlNode convertCall(
-              RexToSqlNodeConverter converter,
-              RexCall call) {
-            SqlNode[] operands =
-                convertExpressionList(converter, call.operands);
-            if (operands == null) {
-              return null;
-            }
-            List<SqlNode> operandList =
-                new ArrayList<SqlNode>(Arrays.asList(operands));
-            SqlDataTypeSpec typeSpec =
-                SqlTypeUtil.convertTypeToSpec(call.getType());
-            operandList.add(typeSpec);
-            return new SqlBasicCall(
-                op,
-                operandList.toArray(new SqlNode[operandList.size()]),
-                SqlParserPos.ZERO);
+        op, (converter, call) -> {
+          SqlNode[] operands =
+              convertExpressionList(converter, call.operands);
+          if (operands == null) {
+            return null;
           }
+          List<SqlNode> operandList =
+              new ArrayList<SqlNode>(Arrays.asList(operands));
+          SqlDataTypeSpec typeSpec =
+              SqlTypeUtil.convertTypeToSpec(call.getType());
+          operandList.add(typeSpec);
+          return new SqlBasicCall(
+              op,
+              operandList.toArray(new SqlNode[0]),
+              SqlParserPos.ZERO);
         });
   }
 
@@ -220,33 +215,28 @@ public class RexSqlStandardConvertletTable
    */
   private void registerCaseOp(final SqlOperator op) {
     registerOp(
-        op,
-        new RexSqlConvertlet() {
-          public SqlNode convertCall(
-              RexToSqlNodeConverter converter,
-              RexCall call) {
-            assert op instanceof SqlCaseOperator;
-            SqlNode[] operands =
-                convertExpressionList(converter, call.operands);
-            if (operands == null) {
-              return null;
-            }
-            SqlNodeList whenList = new SqlNodeList(SqlParserPos.ZERO);
-            SqlNodeList thenList = new SqlNodeList(SqlParserPos.ZERO);
-            int i = 0;
-            while (i < operands.length - 1) {
-              whenList.add(operands[i]);
-              ++i;
-              thenList.add(operands[i]);
-              ++i;
-            }
-            SqlNode elseExpr = operands[i];
-            SqlNode[] newOperands = new SqlNode[3];
-            newOperands[0] = whenList;
-            newOperands[1] = thenList;
-            newOperands[2] = elseExpr;
-            return op.createCall(null, SqlParserPos.ZERO, newOperands);
+        op, (converter, call) -> {
+          assert op instanceof SqlCaseOperator;
+          SqlNode[] operands =
+              convertExpressionList(converter, call.operands);
+          if (operands == null) {
+            return null;
+          }
+          SqlNodeList whenList = new SqlNodeList(SqlParserPos.ZERO);
+          SqlNodeList thenList = new SqlNodeList(SqlParserPos.ZERO);
+          int i = 0;
+          while (i < operands.length - 1) {
+            whenList.add(operands[i]);
+            ++i;
+            thenList.add(operands[i]);
+            ++i;
           }
+          SqlNode elseExpr = operands[i];
+          SqlNode[] newOperands = new SqlNode[3];
+          newOperands[0] = whenList;
+          newOperands[1] = thenList;
+          newOperands[2] = elseExpr;
+          return op.createCall(null, SqlParserPos.ZERO, newOperands);
         });
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/rex/RexSubQuery.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/rex/RexSubQuery.java b/core/src/main/java/org/apache/calcite/rex/RexSubQuery.java
index dc0d405..05fd176 100644
--- a/core/src/main/java/org/apache/calcite/rex/RexSubQuery.java
+++ b/core/src/main/java/org/apache/calcite/rex/RexSubQuery.java
@@ -86,7 +86,7 @@ public class RexSubQuery extends RexCall {
     final RelDataTypeFactory typeFactory = rel.getCluster().getTypeFactory();
     final RelDataType type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
     return new RexSubQuery(type, SqlStdOperatorTable.EXISTS,
-        ImmutableList.<RexNode>of(), rel);
+        ImmutableList.of(), rel);
   }
 
   /** Creates a scalar sub-query. */
@@ -97,7 +97,7 @@ public class RexSubQuery extends RexCall {
     final RelDataType type =
         typeFactory.createTypeWithNullability(fieldList.get(0).getType(), true);
     return new RexSubQuery(type, SqlStdOperatorTable.SCALAR_QUERY,
-        ImmutableList.<RexNode>of(), rel);
+        ImmutableList.of(), rel);
   }
 
   public <R> R accept(RexVisitor<R> visitor) {


[09/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/JdbcTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/JdbcTest.java b/core/src/test/java/org/apache/calcite/test/JdbcTest.java
index 4af601b..6d51261 100644
--- a/core/src/test/java/org/apache/calcite/test/JdbcTest.java
+++ b/core/src/test/java/org/apache/calcite/test/JdbcTest.java
@@ -85,9 +85,7 @@ import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.sql.SqlSpecialOperator;
 import org.apache.calcite.sql.advise.SqlAdvisorGetHintsFunction;
-import org.apache.calcite.sql.parser.SqlAbstractParserImpl;
 import org.apache.calcite.sql.parser.SqlParser;
-import org.apache.calcite.sql.parser.SqlParserImplFactory;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.sql.parser.SqlParserUtil;
 import org.apache.calcite.sql.parser.impl.SqlParserImpl;
@@ -98,7 +96,6 @@ import org.apache.calcite.util.Smalls;
 import org.apache.calcite.util.TryThreadLocal;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.LinkedListMultimap;
 import com.google.common.collect.Multimap;
@@ -112,7 +109,6 @@ import org.junit.Test;
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.io.Reader;
 import java.math.BigDecimal;
 import java.sql.Array;
 import java.sql.Connection;
@@ -141,6 +137,7 @@ import java.util.Objects;
 import java.util.Properties;
 import java.util.Set;
 import java.util.TimeZone;
+import java.util.function.Consumer;
 import java.util.regex.Pattern;
 import javax.sql.DataSource;
 
@@ -261,67 +258,63 @@ public class JdbcTest {
           null);
       with.query("select \"name\" from \"adhoc\".V order by \"name\"")
           .returns("name=Simon\n");
-      with.doWithConnection(
-          new Function<CalciteConnection, Object>() {
-            @Override public Object apply(CalciteConnection input) {
-              try {
-                final Statement statement = input.createStatement();
-                ResultSet resultSet =
-                    statement.executeQuery("explain plan for\n"
-                        + "insert into \"adhoc\".V\n"
-                        + "values ('Fred', 56, 123.4)");
-                assertThat(resultSet.next(), is(true));
-                assertThat(resultSet.getString(1),
-                    isLinux(
-                        "EnumerableTableModify(table=[[adhoc, MUTABLE_EMPLOYEES]], operation=[INSERT], flattened=[false])\n"
-                        + "  EnumerableCalc(expr#0..2=[{inputs}], expr#3=[CAST($t1):JavaType(int) NOT NULL], expr#4=[10], expr#5=[CAST($t0):JavaType(class java.lang.String)], expr#6=[CAST($t2):JavaType(float) NOT NULL], expr#7=[null], empid=[$t3], deptno=[$t4], name=[$t5], salary=[$t6], commission=[$t7])\n"
-                        + "    EnumerableValues(tuples=[[{ 'Fred', 56, 123.4 }]])\n"));
-
-                // With named columns
-                resultSet =
-                    statement.executeQuery("explain plan for\n"
-                        + "insert into \"adhoc\".V (\"name\", e, \"salary\")\n"
-                        + "values ('Fred', 56, 123.4)");
-                assertThat(resultSet.next(), is(true));
-
-                // With named columns, in different order
-                resultSet =
-                    statement.executeQuery("explain plan for\n"
-                        + "insert into \"adhoc\".V (e, \"salary\", \"name\")\n"
-                        + "values (56, 123.4, 'Fred')");
-                assertThat(resultSet.next(), is(true));
-
-                // Mis-named column
-                try {
-                  final PreparedStatement s =
-                      input.prepareStatement("explain plan for\n"
-                          + "insert into \"adhoc\".V (empno, \"salary\", \"name\")\n"
-                          + "values (56, 123.4, 'Fred')");
-                  fail("expected error, got " + s);
-                } catch (SQLException e) {
-                  assertThat(e.getMessage(),
-                      startsWith("Error while preparing statement"));
-                }
-
-                // Fail to provide mandatory column
-                try {
-                  final PreparedStatement s =
-                      input.prepareStatement("explain plan for\n"
-                          + "insert into \"adhoc\".V (e, name)\n"
-                          + "values (56, 'Fred')");
-                  fail("expected error, got " + s);
-                } catch (SQLException e) {
-                  assertThat(e.getMessage(),
-                      startsWith("Error while preparing statement"));
-                }
-
-                statement.close();
-                return null;
-              } catch (SQLException e) {
-                throw new RuntimeException(e);
-              }
-            }
-          });
+      with.doWithConnection(connection -> {
+        try {
+          final Statement statement = connection.createStatement();
+          ResultSet resultSet =
+              statement.executeQuery("explain plan for\n"
+                  + "insert into \"adhoc\".V\n"
+                  + "values ('Fred', 56, 123.4)");
+          assertThat(resultSet.next(), is(true));
+          assertThat(resultSet.getString(1),
+              isLinux(
+                  "EnumerableTableModify(table=[[adhoc, MUTABLE_EMPLOYEES]], operation=[INSERT], flattened=[false])\n"
+                  + "  EnumerableCalc(expr#0..2=[{inputs}], expr#3=[CAST($t1):JavaType(int) NOT NULL], expr#4=[10], expr#5=[CAST($t0):JavaType(class java.lang.String)], expr#6=[CAST($t2):JavaType(float) NOT NULL], expr#7=[null], empid=[$t3], deptno=[$t4], name=[$t5], salary=[$t6], commission=[$t7])\n"
+                  + "    EnumerableValues(tuples=[[{ 'Fred', 56, 123.4 }]])\n"));
+
+          // With named columns
+          resultSet =
+              statement.executeQuery("explain plan for\n"
+                  + "insert into \"adhoc\".V (\"name\", e, \"salary\")\n"
+                  + "values ('Fred', 56, 123.4)");
+          assertThat(resultSet.next(), is(true));
+
+          // With named columns, in different order
+          resultSet =
+              statement.executeQuery("explain plan for\n"
+                  + "insert into \"adhoc\".V (e, \"salary\", \"name\")\n"
+                  + "values (56, 123.4, 'Fred')");
+          assertThat(resultSet.next(), is(true));
+
+          // Mis-named column
+          try {
+            final PreparedStatement s =
+                connection.prepareStatement("explain plan for\n"
+                    + "insert into \"adhoc\".V (empno, \"salary\", \"name\")\n"
+                    + "values (56, 123.4, 'Fred')");
+            fail("expected error, got " + s);
+          } catch (SQLException e) {
+            assertThat(e.getMessage(),
+                startsWith("Error while preparing statement"));
+          }
+
+          // Fail to provide mandatory column
+          try {
+            final PreparedStatement s =
+                connection.prepareStatement("explain plan for\n"
+                    + "insert into \"adhoc\".V (e, name)\n"
+                    + "values (56, 'Fred')");
+            fail("expected error, got " + s);
+          } catch (SQLException e) {
+            assertThat(e.getMessage(),
+                startsWith("Error while preparing statement"));
+          }
+
+          statement.close();
+        } catch (SQLException e) {
+          throw new RuntimeException(e);
+        }
+      });
     }
   }
 
@@ -441,7 +434,7 @@ public class JdbcTest {
             "id=hr.locations; names=[hr, locations]; type=TABLE"));
   }
 
-  private void adviseSql(String sql, Function<ResultSet, Void> checker)
+  private void adviseSql(String sql, Consumer<ResultSet> checker)
       throws ClassNotFoundException, SQLException {
     Properties info = new Properties();
     info.put("lex", "JAVA");
@@ -463,7 +456,7 @@ public class JdbcTest {
     ps.setString(1, sap.sql);
     ps.setInt(2, sap.cursor);
     final ResultSet resultSet = ps.executeQuery();
-    checker.apply(resultSet);
+    checker.accept(resultSet);
     resultSet.close();
     connection.close();
   }
@@ -975,60 +968,56 @@ public class JdbcTest {
     // insensitive. If a select list contains the same column more than once,
     // the first instance of the column will be returned."
     CalciteAssert.that()
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection c) {
-                try {
-                  Statement s = c.createStatement();
-                  ResultSet rs =
-                      s.executeQuery(""
-                          + "SELECT 1 as \"a\", 2 as \"b\", 3 as \"a\", 4 as \"B\"\n"
-                          + "FROM (VALUES (0))");
-                  assertTrue(rs.next());
-                  assertEquals(1, rs.getInt("a"));
-                  assertEquals(1, rs.getInt("A"));
-                  assertEquals(2, rs.getInt("b"));
-                  assertEquals(2, rs.getInt("B"));
-                  assertEquals(1, rs.getInt(1));
-                  assertEquals(2, rs.getInt(2));
-                  assertEquals(3, rs.getInt(3));
-                  assertEquals(4, rs.getInt(4));
-                  try {
-                    int x = rs.getInt("z");
-                    fail("expected error, got " + x);
-                  } catch (SQLException e) {
-                    // ok
-                  }
-                  assertEquals(1, rs.findColumn("a"));
-                  assertEquals(1, rs.findColumn("A"));
-                  assertEquals(2, rs.findColumn("b"));
-                  assertEquals(2, rs.findColumn("B"));
-                  try {
-                    int x = rs.findColumn("z");
-                    fail("expected error, got " + x);
-                  } catch (SQLException e) {
-                    assertThat(e.getMessage(), equalTo("column 'z' not found"));
-                  }
-                  try {
-                    int x = rs.getInt(0);
-                    fail("expected error, got " + x);
-                  } catch (SQLException e) {
-                    assertThat(e.getMessage(),
-                        equalTo("invalid column ordinal: 0"));
-                  }
-                  try {
-                    int x = rs.getInt(5);
-                    fail("expected error, got " + x);
-                  } catch (SQLException e) {
-                    assertThat(e.getMessage(),
-                        equalTo("invalid column ordinal: 5"));
-                  }
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(c -> {
+          try {
+            Statement s = c.createStatement();
+            ResultSet rs =
+                s.executeQuery(""
+                    + "SELECT 1 as \"a\", 2 as \"b\", 3 as \"a\", 4 as \"B\"\n"
+                    + "FROM (VALUES (0))");
+            assertTrue(rs.next());
+            assertEquals(1, rs.getInt("a"));
+            assertEquals(1, rs.getInt("A"));
+            assertEquals(2, rs.getInt("b"));
+            assertEquals(2, rs.getInt("B"));
+            assertEquals(1, rs.getInt(1));
+            assertEquals(2, rs.getInt(2));
+            assertEquals(3, rs.getInt(3));
+            assertEquals(4, rs.getInt(4));
+            try {
+              int x = rs.getInt("z");
+              fail("expected error, got " + x);
+            } catch (SQLException e) {
+              // ok
+            }
+            assertEquals(1, rs.findColumn("a"));
+            assertEquals(1, rs.findColumn("A"));
+            assertEquals(2, rs.findColumn("b"));
+            assertEquals(2, rs.findColumn("B"));
+            try {
+              int x = rs.findColumn("z");
+              fail("expected error, got " + x);
+            } catch (SQLException e) {
+              assertThat(e.getMessage(), equalTo("column 'z' not found"));
+            }
+            try {
+              int x = rs.getInt(0);
+              fail("expected error, got " + x);
+            } catch (SQLException e) {
+              assertThat(e.getMessage(),
+                  equalTo("invalid column ordinal: 0"));
+            }
+            try {
+              int x = rs.getInt(5);
+              fail("expected error, got " + x);
+            } catch (SQLException e) {
+              assertThat(e.getMessage(),
+                  equalTo("invalid column ordinal: 5"));
+            }
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testCloneSchema()
@@ -1514,32 +1503,28 @@ public class JdbcTest {
     CalciteAssert.that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
         .query("values extract(year from date '2008-2-23')")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet a0) {
-                // The following behavior is not quite correct. See
-                //   [CALCITE-508] Reading from ResultSet before calling next()
-                //   should throw SQLException not NoSuchElementException
-                // for details.
-                try {
-                  final BigDecimal bigDecimal = a0.getBigDecimal(1);
-                  fail("expected error, got " + bigDecimal);
-                } catch (SQLException e) {
-                  assertThat(e.getMessage(),
-                      is("java.util.NoSuchElementException: Expecting cursor "
-                          + "position to be Position.OK, actual "
-                          + "is Position.BEFORE_START"));
-                }
-                try {
-                  assertTrue(a0.next());
-                  final BigDecimal bigDecimal = a0.getBigDecimal(1);
-                  assertThat(bigDecimal, equalTo(BigDecimal.valueOf(2008)));
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                return null;
-              }
-            });
+        .returns(resultSet -> {
+          // The following behavior is not quite correct. See
+          //   [CALCITE-508] Reading from ResultSet before calling next()
+          //   should throw SQLException not NoSuchElementException
+          // for details.
+          try {
+            final BigDecimal bigDecimal = resultSet.getBigDecimal(1);
+            fail("expected error, got " + bigDecimal);
+          } catch (SQLException e) {
+            assertThat(e.getMessage(),
+                is("java.util.NoSuchElementException: Expecting cursor "
+                    + "position to be Position.OK, actual "
+                    + "is Position.BEFORE_START"));
+          }
+          try {
+            assertTrue(resultSet.next());
+            final BigDecimal bigDecimal = resultSet.getBigDecimal(1);
+            assertThat(bigDecimal, equalTo(BigDecimal.valueOf(2008)));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testExtractMonthFromTimestamp() {
@@ -1978,58 +1963,54 @@ public class JdbcTest {
   /** Tests JDBC support for nested arrays. */
   @Test public void testNestedArray() throws Exception {
     CalciteAssert.hr()
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try {
-                  final Statement statement = a0.createStatement();
-                  ResultSet resultSet =
-                      statement.executeQuery("select \"empid\",\n"
-                          + "  array[\n"
-                          + "    array['x', 'y', 'z'],\n"
-                          + "    array[\"name\"]] as a\n"
-                          + "from \"hr\".\"emps\"");
-                  assertThat(resultSet.next(), is(true));
-                  assertThat(resultSet.getInt(1), equalTo(100));
-                  assertThat(resultSet.getString(2),
-                      equalTo("[[x, y, z], [Bill]]"));
-                  final Array array = resultSet.getArray(2);
-                  assertThat(array.getBaseType(),
-                      equalTo(java.sql.Types.ARRAY));
-                  final Object[] arrayValues =
-                      (Object[]) array.getArray();
-                  assertThat(arrayValues.length, equalTo(2));
-                  final Array subArray = (Array) arrayValues[0];
-                  assertThat(subArray.getBaseType(),
-                      equalTo(java.sql.Types.VARCHAR));
-                  final Object[] subArrayValues =
-                      (Object[]) subArray.getArray();
-                  assertThat(subArrayValues.length, equalTo(3));
-                  assertThat(subArrayValues[2], equalTo((Object) "z"));
-
-                  final ResultSet subResultSet = subArray.getResultSet();
-                  assertThat(subResultSet.next(), is(true));
-                  assertThat(subResultSet.getString(1), equalTo("x"));
-                  try {
-                    final String string = subResultSet.getString(2);
-                    fail("expected error, got " + string);
-                  } catch (SQLException e) {
-                    assertThat(e.getMessage(),
-                        equalTo("invalid column ordinal: 2"));
-                  }
-                  assertThat(subResultSet.next(), is(true));
-                  assertThat(subResultSet.next(), is(true));
-                  assertThat(subResultSet.isAfterLast(), is(false));
-                  assertThat(subResultSet.getString(1), equalTo("z"));
-                  assertThat(subResultSet.next(), is(false));
-                  assertThat(subResultSet.isAfterLast(), is(true));
-                  statement.close();
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            final Statement statement = connection.createStatement();
+            ResultSet resultSet =
+                statement.executeQuery("select \"empid\",\n"
+                    + "  array[\n"
+                    + "    array['x', 'y', 'z'],\n"
+                    + "    array[\"name\"]] as a\n"
+                    + "from \"hr\".\"emps\"");
+            assertThat(resultSet.next(), is(true));
+            assertThat(resultSet.getInt(1), equalTo(100));
+            assertThat(resultSet.getString(2),
+                equalTo("[[x, y, z], [Bill]]"));
+            final Array array = resultSet.getArray(2);
+            assertThat(array.getBaseType(),
+                equalTo(Types.ARRAY));
+            final Object[] arrayValues =
+                (Object[]) array.getArray();
+            assertThat(arrayValues.length, equalTo(2));
+            final Array subArray = (Array) arrayValues[0];
+            assertThat(subArray.getBaseType(),
+                equalTo(Types.VARCHAR));
+            final Object[] subArrayValues =
+                (Object[]) subArray.getArray();
+            assertThat(subArrayValues.length, equalTo(3));
+            assertThat(subArrayValues[2], equalTo((Object) "z"));
+
+            final ResultSet subResultSet = subArray.getResultSet();
+            assertThat(subResultSet.next(), is(true));
+            assertThat(subResultSet.getString(1), equalTo("x"));
+            try {
+              final String string = subResultSet.getString(2);
+              fail("expected error, got " + string);
+            } catch (SQLException e) {
+              assertThat(e.getMessage(),
+                  equalTo("invalid column ordinal: 2"));
+            }
+            assertThat(subResultSet.next(), is(true));
+            assertThat(subResultSet.next(), is(true));
+            assertThat(subResultSet.isAfterLast(), is(false));
+            assertThat(subResultSet.getString(1), equalTo("z"));
+            assertThat(subResultSet.next(), is(false));
+            assertThat(subResultSet.isAfterLast(), is(true));
+            statement.close();
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testArrayConstructor() {
@@ -3057,21 +3038,19 @@ public class JdbcTest {
 
   public void checkOrderBy(final boolean desc,
       final NullCollation nullCollation) {
-    final Function<ResultSet, Void> checker = new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        final String msg = (desc ? "DESC" : "ASC") + ":" + nullCollation;
-        final List<Number> numbers = new ArrayList<>();
-        try {
-          while (resultSet.next()) {
-            numbers.add((Number) resultSet.getObject(2));
-          }
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+    final Consumer<ResultSet> checker = resultSet -> {
+      final String msg = (desc ? "DESC" : "ASC") + ":" + nullCollation;
+      final List<Number> numbers = new ArrayList<>();
+      try {
+        while (resultSet.next()) {
+          numbers.add((Number) resultSet.getObject(2));
         }
-        assertThat(msg, numbers.size(), is(3));
-        assertThat(msg, numbers.get(nullCollation.last(desc) ? 2 : 0), nullValue());
-        return null;
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
+      assertThat(msg, numbers.size(), is(3));
+      assertThat(msg, numbers.get(nullCollation.last(desc) ? 2 : 0),
+          nullValue());
     };
     final CalciteAssert.AssertThat with = CalciteAssert.that()
         .with(CalciteAssert.Config.FOODMART_CLONE)
@@ -3429,12 +3408,8 @@ public class JdbcTest {
         + "select \"empid\", \"name\" from \"hr\".\"emps\" where \"empid\">=150";
     CalciteAssert.hr()
         .query(sql)
-        .withHook(Hook.PLANNER, new Function<RelOptPlanner, Void>() {
-          @Override public Void apply(RelOptPlanner planner) {
-            planner.removeRule(IntersectToDistinctRule.INSTANCE);
-            return null;
-          }
-        })
+        .withHook(Hook.PLANNER, (Consumer<RelOptPlanner>) planner ->
+            planner.removeRule(IntersectToDistinctRule.INSTANCE))
         .explainContains(""
             + "PLAN=EnumerableIntersect(all=[false])")
         .returnsUnordered("empid=150; name=Sebastian");
@@ -4663,14 +4638,11 @@ public class JdbcTest {
             + "  from \"hr\".\"depts\" as d2\n"
             + "  join \"hr\".\"emps\" as e2 using (\"deptno\")\n"
             + "where d.\"deptno\" = d2.\"deptno\")")
-        .convertMatches(
-            new Function<RelNode, Void>() {
-              public Void apply(RelNode relNode) {
-                String s = RelOptUtil.toString(relNode);
-                assertThat(s, not(containsString("Correlate")));
-                return null;
-              }
-            });
+        .convertMatches(relNode -> {
+          String s = RelOptUtil.toString(relNode);
+          assertThat(s, not(containsString("Correlate")));
+          return null;
+        });
   }
 
   /** Tests a correlated scalar sub-query in the SELECT clause.
@@ -4891,103 +4863,95 @@ public class JdbcTest {
   /** Tests that {@link java.sql.Statement#setMaxRows(int)} is honored. */
   @Test public void testSetMaxRows() throws Exception {
     CalciteAssert.hr()
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try {
-                  final Statement statement = a0.createStatement();
-                  try {
-                    statement.setMaxRows(-1);
-                    fail("expected error");
-                  } catch (SQLException e) {
-                    assertEquals(e.getMessage(), "illegal maxRows value: -1");
-                  }
-                  statement.setMaxRows(2);
-                  assertEquals(2, statement.getMaxRows());
-                  final ResultSet resultSet = statement.executeQuery(
-                      "select * from \"hr\".\"emps\"");
-                  assertTrue(resultSet.next());
-                  assertTrue(resultSet.next());
-                  assertFalse(resultSet.next());
-                  resultSet.close();
-                  statement.close();
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            final Statement statement = connection.createStatement();
+            try {
+              statement.setMaxRows(-1);
+              fail("expected error");
+            } catch (SQLException e) {
+              assertEquals(e.getMessage(), "illegal maxRows value: -1");
+            }
+            statement.setMaxRows(2);
+            assertEquals(2, statement.getMaxRows());
+            final ResultSet resultSet = statement.executeQuery(
+                "select * from \"hr\".\"emps\"");
+            assertTrue(resultSet.next());
+            assertTrue(resultSet.next());
+            assertFalse(resultSet.next());
+            resultSet.close();
+            statement.close();
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests a {@link PreparedStatement} with parameters. */
   @Test public void testPreparedStatement() throws Exception {
     CalciteAssert.hr()
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection connection) {
-                try {
-                  final PreparedStatement preparedStatement =
-                      connection.prepareStatement("select \"deptno\", \"name\" "
-                          + "from \"hr\".\"emps\"\n"
-                          + "where \"deptno\" < ? and \"name\" like ?");
-
-                  // execute with vars unbound - gives error
-                  ResultSet resultSet;
-                  try {
-                    resultSet = preparedStatement.executeQuery();
-                    fail("expected error, got " + resultSet);
-                  } catch (SQLException e) {
-                    assertThat(e.getMessage(),
-                        containsString(
-                            "exception while executing query: unbound parameter"));
-                  }
-
-                  // execute with both vars null - no results
-                  preparedStatement.setNull(1, java.sql.Types.INTEGER);
-                  preparedStatement.setNull(2, java.sql.Types.VARCHAR);
-                  resultSet = preparedStatement.executeQuery();
-                  assertFalse(resultSet.next());
-
-                  // execute with ?0=15, ?1='%' - 3 rows
-                  preparedStatement.setInt(1, 15);
-                  preparedStatement.setString(2, "%");
-                  resultSet = preparedStatement.executeQuery();
-                  assertEquals("deptno=10; name=Bill\n"
-                      + "deptno=10; name=Sebastian\n"
-                      + "deptno=10; name=Theodore\n",
-                      CalciteAssert.toString(resultSet));
-
-                  // execute with ?0=15 (from last bind), ?1='%r%' - 1 row
-                  preparedStatement.setString(2, "%r%");
-                  resultSet = preparedStatement.executeQuery();
-                  assertEquals(
-                      "deptno=10; name=Theodore\n",
-                      CalciteAssert.toString(resultSet));
-
-                  // Now BETWEEN, with 3 arguments, 2 of which are parameters
-                  final String sql2 = "select \"deptno\", \"name\" "
-                      + "from \"hr\".\"emps\"\n"
-                      + "where \"deptno\" between symmetric ? and ?\n"
-                      + "order by 2";
-                  final PreparedStatement preparedStatement2 =
-                      connection.prepareStatement(sql2);
-                  preparedStatement2.setInt(1, 15);
-                  preparedStatement2.setInt(2, 5);
-                  resultSet = preparedStatement2.executeQuery();
-                  assertThat(CalciteAssert.toString(resultSet),
-                      is("deptno=10; name=Bill\n"
-                          + "deptno=10; name=Sebastian\n"
-                          + "deptno=10; name=Theodore\n"));
-
-                  resultSet.close();
-                  preparedStatement2.close();
-                  preparedStatement.close();
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            final PreparedStatement preparedStatement =
+                connection.prepareStatement("select \"deptno\", \"name\" "
+                    + "from \"hr\".\"emps\"\n"
+                    + "where \"deptno\" < ? and \"name\" like ?");
+
+            // execute with vars unbound - gives error
+            ResultSet resultSet;
+            try {
+              resultSet = preparedStatement.executeQuery();
+              fail("expected error, got " + resultSet);
+            } catch (SQLException e) {
+              assertThat(e.getMessage(),
+                  containsString(
+                      "exception while executing query: unbound parameter"));
+            }
+
+            // execute with both vars null - no results
+            preparedStatement.setNull(1, Types.INTEGER);
+            preparedStatement.setNull(2, Types.VARCHAR);
+            resultSet = preparedStatement.executeQuery();
+            assertFalse(resultSet.next());
+
+            // execute with ?0=15, ?1='%' - 3 rows
+            preparedStatement.setInt(1, 15);
+            preparedStatement.setString(2, "%");
+            resultSet = preparedStatement.executeQuery();
+            assertEquals("deptno=10; name=Bill\n"
+                + "deptno=10; name=Sebastian\n"
+                + "deptno=10; name=Theodore\n",
+                CalciteAssert.toString(resultSet));
+
+            // execute with ?0=15 (from last bind), ?1='%r%' - 1 row
+            preparedStatement.setString(2, "%r%");
+            resultSet = preparedStatement.executeQuery();
+            assertEquals(
+                "deptno=10; name=Theodore\n",
+                CalciteAssert.toString(resultSet));
+
+            // Now BETWEEN, with 3 arguments, 2 of which are parameters
+            final String sql2 = "select \"deptno\", \"name\" "
+                + "from \"hr\".\"emps\"\n"
+                + "where \"deptno\" between symmetric ? and ?\n"
+                + "order by 2";
+            final PreparedStatement preparedStatement2 =
+                connection.prepareStatement(sql2);
+            preparedStatement2.setInt(1, 15);
+            preparedStatement2.setInt(2, 5);
+            resultSet = preparedStatement2.executeQuery();
+            assertThat(CalciteAssert.toString(resultSet),
+                is("deptno=10; name=Bill\n"
+                    + "deptno=10; name=Sebastian\n"
+                    + "deptno=10; name=Theodore\n"));
+
+            resultSet.close();
+            preparedStatement2.close();
+            preparedStatement.close();
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Test case for
@@ -5003,29 +4967,25 @@ public class JdbcTest {
   private void checkPreparedOffsetFetch(final int offset, final int fetch,
       final Matcher<? super ResultSet> matcher) throws Exception {
     CalciteAssert.hr()
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection connection) {
-                final String sql = "select \"name\"\n"
-                    + "from \"hr\".\"emps\"\n"
-                    + "order by \"empid\" offset ? fetch next ? rows only";
-                try (final PreparedStatement p =
-                         connection.prepareStatement(sql)) {
-                  final ParameterMetaData pmd = p.getParameterMetaData();
-                  assertThat(pmd.getParameterCount(), is(2));
-                  assertThat(pmd.getParameterType(1), is(Types.INTEGER));
-                  assertThat(pmd.getParameterType(2), is(Types.INTEGER));
-                  p.setInt(1, offset);
-                  p.setInt(2, fetch);
-                  try (final ResultSet r = p.executeQuery()) {
-                    assertThat(r, matcher);
-                    return null;
-                  }
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          final String sql = "select \"name\"\n"
+              + "from \"hr\".\"emps\"\n"
+              + "order by \"empid\" offset ? fetch next ? rows only";
+          try (final PreparedStatement p =
+                   connection.prepareStatement(sql)) {
+            final ParameterMetaData pmd = p.getParameterMetaData();
+            assertThat(pmd.getParameterCount(), is(2));
+            assertThat(pmd.getParameterType(1), is(Types.INTEGER));
+            assertThat(pmd.getParameterType(2), is(Types.INTEGER));
+            p.setInt(1, offset);
+            p.setInt(2, fetch);
+            try (final ResultSet r = p.executeQuery()) {
+              assertThat(r, matcher);
+            }
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests a JDBC connection that provides a model (a single schema based on
@@ -5167,17 +5127,13 @@ public class JdbcTest {
             + "  ]\n"
             + "}");
     // check that the specified 'defaultSchema' was used
-    that.doWithConnection(
-        new Function<CalciteConnection, Object>() {
-          public Object apply(CalciteConnection connection) {
-            try {
-              assertEquals("adhoc", connection.getSchema());
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        });
+    that.doWithConnection(connection -> {
+      try {
+        assertEquals("adhoc", connection.getSchema());
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+    });
     that.query("select * from \"adhoc\".ELVIS where \"deptno\" = 10")
         .returns(""
             + "empid=100; deptno=10; name=Bill; salary=10000.0; commission=1000\n"
@@ -5403,89 +5359,84 @@ public class JdbcTest {
             + "empid=100; deptno=10; name=Bill; salary=10000.0; commission=1000\n");
 
     // Make sure that views appear in metadata.
-    with.doWithConnection(
-        new Function<CalciteConnection, Void>() {
-          public Void apply(CalciteConnection a0) {
-            try {
-              final DatabaseMetaData metaData = a0.getMetaData();
-
-              // all table types
-              try (ResultSet r =
-                   metaData.getTables(null, "adhoc", null, null)) {
-                assertEquals(
-                    "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=MUTABLE_EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; TABLE_TYPE=VIEW; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n",
-                    CalciteAssert.toString(r));
-              }
-
-              // including system tables; note that table type is "SYSTEM TABLE"
-              // not "SYSTEM_TABLE"
-              try (ResultSet r = metaData.getTables(null, null, null, null)) {
-                assertEquals(
-                    "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=MUTABLE_EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; TABLE_TYPE=VIEW; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=metadata; TABLE_NAME=COLUMNS; TABLE_TYPE=SYSTEM TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=metadata; TABLE_NAME=TABLES; TABLE_TYPE=SYSTEM TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n",
-                    CalciteAssert.toString(r));
-              }
+    with.doWithConnection(connection -> {
+      try {
+        final DatabaseMetaData metaData = connection.getMetaData();
+
+        // all table types
+        try (ResultSet r =
+             metaData.getTables(null, "adhoc", null, null)) {
+          assertEquals(
+              "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=MUTABLE_EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; TABLE_TYPE=VIEW; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n",
+              CalciteAssert.toString(r));
+        }
 
-              // views only
-              try (ResultSet r = metaData.getTables(null, "adhoc", null,
-                  new String[]{Schema.TableType.VIEW.jdbcName})) {
-                assertEquals(
-                    "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; TABLE_TYPE=VIEW; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n",
-                    CalciteAssert.toString(r));
-              }
+        // including system tables; note that table type is "SYSTEM TABLE"
+        // not "SYSTEM_TABLE"
+        try (ResultSet r = metaData.getTables(null, null, null, null)) {
+          assertEquals(
+              "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=MUTABLE_EMPLOYEES; TABLE_TYPE=TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; TABLE_TYPE=VIEW; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=metadata; TABLE_NAME=COLUMNS; TABLE_TYPE=SYSTEM TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=metadata; TABLE_NAME=TABLES; TABLE_TYPE=SYSTEM TABLE; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n",
+              CalciteAssert.toString(r));
+        }
 
-              // columns
-              try (ResultSet r =
-                       metaData.getColumns(null, "adhoc", "V", null)) {
-                assertEquals(
-                    "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=empid; DATA_TYPE=4; TYPE_NAME=JavaType(int) NOT NULL; COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=0; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=1; IS_NULLABLE=NO; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=deptno; DATA_TYPE=4; TYPE_NAME=JavaType(int) NOT NULL; COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=0; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=2; IS_NULLABLE=NO; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=name; DATA_TYPE=12; TYPE_NAME=JavaType(class java.lang.String); COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=1; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=3; IS_NULLABLE=YES; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=salary; DATA_TYPE=7; TYPE_NAME=JavaType(float) NOT NULL; COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=0; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=4; IS_NULLABLE=NO; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
-                        + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=commission; DATA_TYPE=4; TYPE_NAME=JavaType(class java.lang.Integer); COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=1; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=5; IS_NULLABLE=YES; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n",
-                    CalciteAssert.toString(r));
-              }
+        // views only
+        try (ResultSet r = metaData.getTables(null, "adhoc", null,
+            new String[]{Schema.TableType.VIEW.jdbcName})) {
+          assertEquals(
+              "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; TABLE_TYPE=VIEW; REMARKS=null; TYPE_CAT=null; TYPE_SCHEM=null; TYPE_NAME=null; SELF_REFERENCING_COL_NAME=null; REF_GENERATION=null\n",
+              CalciteAssert.toString(r));
+        }
 
-              // catalog
-              try (ResultSet r = metaData.getCatalogs()) {
-                assertEquals(
-                    "TABLE_CAT=null\n",
-                    CalciteAssert.toString(r));
-              }
+        // columns
+        try (ResultSet r =
+                 metaData.getColumns(null, "adhoc", "V", null)) {
+          assertEquals(
+              "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=empid; DATA_TYPE=4; TYPE_NAME=JavaType(int) NOT NULL; COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=0; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=1; IS_NULLABLE=NO; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=deptno; DATA_TYPE=4; TYPE_NAME=JavaType(int) NOT NULL; COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=0; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=2; IS_NULLABLE=NO; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=name; DATA_TYPE=12; TYPE_NAME=JavaType(class java.lang.String); COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=1; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=3; IS_NULLABLE=YES; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=salary; DATA_TYPE=7; TYPE_NAME=JavaType(float) NOT NULL; COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=0; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=4; IS_NULLABLE=NO; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n"
+                  + "TABLE_CAT=null; TABLE_SCHEM=adhoc; TABLE_NAME=V; COLUMN_NAME=commission; DATA_TYPE=4; TYPE_NAME=JavaType(class java.lang.Integer); COLUMN_SIZE=-1; BUFFER_LENGTH=null; DECIMAL_DIGITS=null; NUM_PREC_RADIX=10; NULLABLE=1; REMARKS=null; COLUMN_DEF=null; SQL_DATA_TYPE=null; SQL_DATETIME_SUB=null; CHAR_OCTET_LENGTH=-1; ORDINAL_POSITION=5; IS_NULLABLE=YES; SCOPE_CATALOG=null; SCOPE_SCHEMA=null; SCOPE_TABLE=null; SOURCE_DATA_TYPE=null; IS_AUTOINCREMENT=; IS_GENERATEDCOLUMN=\n",
+              CalciteAssert.toString(r));
+        }
 
-              // schemas
-              try (ResultSet r = metaData.getSchemas()) {
-                assertEquals(
-                    "TABLE_SCHEM=adhoc; TABLE_CATALOG=null\n"
-                        + "TABLE_SCHEM=metadata; TABLE_CATALOG=null\n",
-                    CalciteAssert.toString(r));
-              }
+        // catalog
+        try (ResultSet r = metaData.getCatalogs()) {
+          assertEquals(
+              "TABLE_CAT=null\n",
+              CalciteAssert.toString(r));
+        }
 
-              // schemas (qualified)
-              try (ResultSet r = metaData.getSchemas(null, "adhoc")) {
-                assertEquals(
-                    "TABLE_SCHEM=adhoc; TABLE_CATALOG=null\n",
-                    CalciteAssert.toString(r));
-              }
+        // schemas
+        try (ResultSet r = metaData.getSchemas()) {
+          assertEquals(
+              "TABLE_SCHEM=adhoc; TABLE_CATALOG=null\n"
+                  + "TABLE_SCHEM=metadata; TABLE_CATALOG=null\n",
+              CalciteAssert.toString(r));
+        }
 
-              // table types
-              try (ResultSet r = metaData.getTableTypes()) {
-                assertEquals("TABLE_TYPE=TABLE\n"
-                        + "TABLE_TYPE=VIEW\n",
-                    CalciteAssert.toString(r));
-              }
+        // schemas (qualified)
+        try (ResultSet r = metaData.getSchemas(null, "adhoc")) {
+          assertEquals(
+              "TABLE_SCHEM=adhoc; TABLE_CATALOG=null\n",
+              CalciteAssert.toString(r));
+        }
 
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        });
+        // table types
+        try (ResultSet r = metaData.getTableTypes()) {
+          assertEquals("TABLE_TYPE=TABLE\n"
+                  + "TABLE_TYPE=VIEW\n",
+              CalciteAssert.toString(r));
+        }
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+    });
   }
 
   /** Tests a view with ORDER BY and LIMIT clauses. */
@@ -5600,21 +5551,17 @@ public class JdbcTest {
                 return connection;
               }
             })
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try {
-                  a0.createStatement()
-                      .executeQuery(
-                          "select * from \"hr\".\"emps\" "
-                              + "where \"deptno\" = 10");
-                  assertEquals(1, objects.size());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            final String sql = "select * from \"hr\".\"emps\" "
+                + "where \"deptno\" = 10";
+            connection.createStatement()
+                .executeQuery(sql);
+            assertThat(objects.size(), is(1));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testExplain() {
@@ -5692,57 +5639,49 @@ public class JdbcTest {
   @Test public void testCurrentTimestamp() throws Exception {
     CalciteAssert.that()
         .with(CalciteConnectionProperty.TIME_ZONE, "GMT+1:00")
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  final PreparedStatement statement =
-                      connection.prepareStatement("VALUES CURRENT_TIMESTAMP");
-                  ResultSet resultSet;
-
-                  resultSet = statement.executeQuery();
-                  assertTrue(resultSet.next());
-                  String s0 = resultSet.getString(1);
-                  assertFalse(resultSet.next());
-
-                  try {
-                    Thread.sleep(1000);
-                  } catch (InterruptedException e) {
-                    throw new RuntimeException(e);
-                  }
-
-                  resultSet = statement.executeQuery();
-                  assertTrue(resultSet.next());
-                  String s1 = resultSet.getString(1);
-                  assertFalse(resultSet.next());
-
-                  assertTrue("\n"
-                          + "s0=" + s0 + "\n"
-                          + "s1=" + s1 + "\n",
-                      s0.compareTo(s1) < 0);
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            final PreparedStatement statement =
+                connection.prepareStatement("VALUES CURRENT_TIMESTAMP");
+            ResultSet resultSet;
+
+            resultSet = statement.executeQuery();
+            assertTrue(resultSet.next());
+            String s0 = resultSet.getString(1);
+            assertFalse(resultSet.next());
+
+            try {
+              Thread.sleep(1000);
+            } catch (InterruptedException e) {
+              throw new RuntimeException(e);
+            }
+
+            resultSet = statement.executeQuery();
+            assertTrue(resultSet.next());
+            String s1 = resultSet.getString(1);
+            assertFalse(resultSet.next());
+
+            assertTrue("\n"
+                    + "s0=" + s0 + "\n"
+                    + "s1=" + s1 + "\n",
+                s0.compareTo(s1) < 0);
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Test for timestamps and time zones, based on pgsql TimezoneTest. */
   @Test public void testGetTimestamp() throws Exception {
     CalciteAssert.that()
         .with(CalciteConnectionProperty.TIME_ZONE, "GMT+1:00")
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  checkGetTimestamp(connection);
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            checkGetTimestamp(connection);
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   private void checkGetTimestamp(Connection con) throws SQLException {
@@ -5879,24 +5818,20 @@ public class JdbcTest {
   public void testGetDate() throws Exception {
     CalciteAssert.that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection conn) {
-                try {
-                  Statement stmt = conn.createStatement();
-                  ResultSet rs = stmt.executeQuery(
-                      "select min(\"date\") mindate from \"foodmart\".\"currency\"");
-                  assertTrue(rs.next());
-                  assertEquals(
-                      Date.valueOf("1997-01-01"),
-                      rs.getDate(1));
-                  assertFalse(rs.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            Statement stmt = connection.createStatement();
+            ResultSet rs = stmt.executeQuery(
+                "select min(\"date\") mindate from \"foodmart\".\"currency\"");
+            assertTrue(rs.next());
+            assertEquals(
+                Date.valueOf("1997-01-01"),
+                rs.getDate(1));
+            assertFalse(rs.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests accessing a date as a string in a JDBC source whose type is DATE. */
@@ -5910,24 +5845,20 @@ public class JdbcTest {
   @Test public void testGetTimestampObject() throws Exception {
     CalciteAssert.that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection conn) {
-                try {
-                  Statement stmt = conn.createStatement();
-                  ResultSet rs = stmt.executeQuery(
-                      "select \"hire_date\" from \"foodmart\".\"employee\" where \"employee_id\" = 1");
-                  assertTrue(rs.next());
-                  assertEquals(
-                      Timestamp.valueOf("1994-12-01 00:00:00"),
-                      rs.getTimestamp(1));
-                  assertFalse(rs.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            Statement stmt = connection.createStatement();
+            ResultSet rs = stmt.executeQuery(
+                "select \"hire_date\" from \"foodmart\".\"employee\" where \"employee_id\" = 1");
+            assertTrue(rs.next());
+            assertEquals(
+                Timestamp.valueOf("1994-12-01 00:00:00"),
+                rs.getTimestamp(1));
+            assertFalse(rs.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testRowComparison() {
@@ -5976,175 +5907,155 @@ public class JdbcTest {
   @Test public void testLexMySQL() throws Exception {
     CalciteAssert.that()
         .with(Lex.MYSQL)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  DatabaseMetaData metaData = connection.getMetaData();
-                  assertThat(metaData.getIdentifierQuoteString(), equalTo("`"));
-                  assertThat(metaData.supportsMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            DatabaseMetaData metaData = connection.getMetaData();
+            assertThat(metaData.getIdentifierQuoteString(), equalTo("`"));
+            assertThat(metaData.supportsMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
+                equalTo(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests metadata for the MySQL ANSI lexical scheme. */
   @Test public void testLexMySQLANSI() throws Exception {
     CalciteAssert.that()
         .with(Lex.MYSQL_ANSI)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  DatabaseMetaData metaData = connection.getMetaData();
-                  assertThat(metaData.getIdentifierQuoteString(), equalTo("\""));
-                  assertThat(metaData.supportsMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            DatabaseMetaData metaData = connection.getMetaData();
+            assertThat(metaData.getIdentifierQuoteString(), equalTo("\""));
+            assertThat(metaData.supportsMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
+                equalTo(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests metadata for different the "SQL_SERVER" lexical scheme. */
   @Test public void testLexSqlServer() throws Exception {
     CalciteAssert.that()
         .with(Lex.SQL_SERVER)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  DatabaseMetaData metaData = connection.getMetaData();
-                  assertThat(metaData.getIdentifierQuoteString(), equalTo("["));
-                  assertThat(metaData.supportsMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            DatabaseMetaData metaData = connection.getMetaData();
+            assertThat(metaData.getIdentifierQuoteString(), equalTo("["));
+            assertThat(metaData.supportsMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
+                equalTo(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests metadata for the ORACLE (and default) lexical scheme. */
   @Test public void testLexOracle() throws Exception {
     CalciteAssert.that()
         .with(Lex.ORACLE)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  DatabaseMetaData metaData = connection.getMetaData();
-                  assertThat(metaData.getIdentifierQuoteString(),
-                      equalTo("\""));
-                  assertThat(metaData.supportsMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesLowerCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
-                      equalTo(true));
-                  // Oracle JDBC 12.1.0.1.0 returns true here, however it is
-                  // not clear if the bug is in JDBC specification or Oracle
-                  // driver
-                  assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesUpperCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            DatabaseMetaData metaData = connection.getMetaData();
+            assertThat(metaData.getIdentifierQuoteString(),
+                equalTo("\""));
+            assertThat(metaData.supportsMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesLowerCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
+                equalTo(true));
+            // Oracle JDBC 12.1.0.1.0 returns true here, however it is
+            // not clear if the bug is in JDBC specification or Oracle
+            // driver
+            assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesUpperCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
+                equalTo(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests metadata for the JAVA lexical scheme. */
   @Test public void testLexJava() throws Exception {
     CalciteAssert.that()
         .with(Lex.JAVA)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  DatabaseMetaData metaData = connection.getMetaData();
-                  assertThat(metaData.getIdentifierQuoteString(),
-                      equalTo("`"));
-                  assertThat(metaData.supportsMixedCaseIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesUpperCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            DatabaseMetaData metaData = connection.getMetaData();
+            assertThat(metaData.getIdentifierQuoteString(),
+                equalTo("`"));
+            assertThat(metaData.supportsMixedCaseIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesUpperCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
+                equalTo(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests metadata for the ORACLE lexical scheme overridden like JAVA. */
@@ -6155,35 +6066,31 @@ public class JdbcTest {
         .with(CalciteConnectionProperty.UNQUOTED_CASING, Casing.UNCHANGED)
         .with(CalciteConnectionProperty.QUOTED_CASING, Casing.UNCHANGED)
         .with(CalciteConnectionProperty.CASE_SENSITIVE, true)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  DatabaseMetaData metaData = connection.getMetaData();
-                  assertThat(metaData.getIdentifierQuoteString(),
-                      equalTo("`"));
-                  assertThat(metaData.supportsMixedCaseIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesMixedCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesUpperCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
-                      equalTo(true));
-                  assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesUpperCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
-                      equalTo(false));
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            DatabaseMetaData metaData = connection.getMetaData();
+            assertThat(metaData.getIdentifierQuoteString(),
+                equalTo("`"));
+            assertThat(metaData.supportsMixedCaseIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesMixedCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesUpperCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.supportsMixedCaseQuotedIdentifiers(),
+                equalTo(true));
+            assertThat(metaData.storesMixedCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesUpperCaseQuotedIdentifiers(),
+                equalTo(false));
+            assertThat(metaData.storesLowerCaseQuotedIdentifiers(),
+                equalTo(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests case-insensitive resolution of schema and table names. */
@@ -6286,19 +6193,16 @@ public class JdbcTest {
   /** Tests that {@link Hook#PARSE_TREE} works. */
   @Test public void testHook() {
     final int[] callCount = {0};
-    try (Hook.Closeable hook = Hook.PARSE_TREE.addThread(
-        new Function<Object[], Object>() {
-          public Void apply(Object[] args) {
-            assertThat(args.length, equalTo(2));
-            assertThat(args[0], instanceOf(String.class));
-            assertThat((String) args[0],
-                equalTo("select \"deptno\", \"commission\", sum(\"salary\") s\n"
-                    + "from \"hr\".\"emps\"\n"
-                    + "group by \"deptno\", \"commission\""));
-            assertThat(args[1], instanceOf(SqlSelect.class));
-            ++callCount[0];
-            return null;
-          }
+    try (Hook.Closeable ignored = Hook.PARSE_TREE.<Object[]>addThread(
+        args -> {
+          assertThat(args.length, equalTo(2));
+          assertThat(args[0], instanceOf(String.class));
+          assertThat(args[0],
+              equalTo("select \"deptno\", \"commission\", sum(\"salary\") s\n"
+                  + "from \"hr\".\"emps\"\n"
+                  + "group by \"deptno\", \"commission\""));
+          assertThat(args[1], instanceOf(SqlSelect.class));
+          ++callCount[0];
         })) {
       // Simple query does not run the hook.
       testSimple();
@@ -6318,13 +6222,7 @@ public class JdbcTest {
         .query("select count(*) as c from \"foodmart\".\"employee\" as e1\n"
             + "  where \"first_name\" = 'abcde'\n"
             + "  and \"gender\" = 'F'")
-        .withHook(Hook.QUERY_PLAN,
-            new Function<String, Void>() {
-              public Void apply(String sql) {
-                sqls[0] = sql;
-                return null;
-              }
-            })
+        .withHook(Hook.QUERY_PLAN, (Consumer<String>) sql -> sqls[0] = sql)
         .returns("C=0\n");
     switch (CalciteAssert.DB) {
     case HSQLDB:
@@ -6744,23 +6642,19 @@ public class JdbcTest {
             + "   } } ]\n"
             + "}")
         .query("select * from emp")
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet input) {
-                final StringBuilder buf = new StringBuilder();
-                try {
-                  final int columnCount = input.getMetaData().getColumnCount();
-                  while (input.next()) {
-                    for (int i = 0; i < columnCount; i++) {
-                      buf.append(input.getObject(i + 1));
-                    }
-                  }
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
+        .returns(input -> {
+          final StringBuilder buf = new StringBuilder();
+          try {
+            final int columnCount = input.getMetaData().getColumnCount();
+            while (input.next()) {
+              for (int i = 0; i < columnCount; i++) {
+                buf.append(input.getObject(i + 1));
               }
-            });
+            }
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Test case for
@@ -6830,8 +6724,7 @@ public class JdbcTest {
     public final Department[] depts = {
       new Department(10, "Sales", Arrays.asList(emps[0], emps[2]),
           new Location(-122, 38)),
-      new Department(30, "Marketing", Collections.<Employee>emptyList(),
-          new Location(0, 52)),
+      new Department(30, "Marketing", ImmutableList.of(), new Location(0, 52)),
       new Department(40, "HR", Collections.singletonList(emps[1]), null),
     };
     public final Dependent[] dependents = {
@@ -7193,22 +7086,17 @@ public class JdbcTest {
         @Override public CalcitePrepare apply() {
           return new CalcitePrepareImpl() {
             @Override protected SqlParser.ConfigBuilder createParserConfig() {
-              return super.createParserConfig().setParserFactory(
-                  new SqlParserImplFactory() {
-                    @Override public SqlAbstractParserImpl
-                    getParser(Reader stream) {
-                      return new SqlParserImpl(stream) {
-                        @Override public SqlNode parseSqlStmtEof() {
-                          return new SqlCall(SqlParserPos.ZERO) {
-                            @Override public SqlOperator getOperator() {
-                              return new SqlSpecialOperator("COMMIT",
-                                  SqlKind.COMMIT);
-                            }
-
-                            @Override public List<SqlNode> getOperandList() {
-                              return ImmutableList.of();
-                            }
-                          };
+              return super.createParserConfig().setParserFactory(stream ->
+                  new SqlParserImpl(stream) {
+                    @Override public SqlNode parseSqlStmtEof() {
+                      return new SqlCall(SqlParserPos.ZERO) {
+                        @Override public SqlOperator getOperator() {
+                          return new SqlSpecialOperator("COMMIT",
+                              SqlKind.COMMIT);
+                        }
+
+                        @Override public List<SqlNode> getOperandList() {
+                          return ImmutableList.of();
                         }
                       };
                     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/LatticeTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/LatticeTest.java b/core/src/test/java/org/apache/calcite/test/LatticeTest.java
index 539a2cc..aef9b6a 100644
--- a/core/src/test/java/org/apache/calcite/test/LatticeTest.java
+++ b/core/src/test/java/org/apache/calcite/test/LatticeTest.java
@@ -16,22 +16,18 @@
  */
 package org.apache.calcite.test;
 
-import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.jdbc.CalciteSchema;
 import org.apache.calcite.materialize.Lattice;
 import org.apache.calcite.materialize.Lattices;
 import org.apache.calcite.materialize.MaterializationService;
 import org.apache.calcite.plan.RelOptUtil;
-import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.runtime.Hook;
 import org.apache.calcite.schema.SchemaPlus;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.TestUtil;
 
-import com.google.common.base.Function;
 import com.google.common.base.Throwables;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 
 import org.junit.Assume;
 import org.junit.Ignore;
@@ -42,10 +38,12 @@ import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
 
 import static org.apache.calcite.test.Matchers.containsStringLinux;
 import static org.apache.calcite.test.Matchers.within;
@@ -166,29 +164,26 @@ public class LatticeTest {
    * schema. */
   @Test public void testLatticeSql() throws Exception {
     modelWithLattice("EMPLOYEES", "select * from \"foodmart\".\"days\"")
-        .doWithConnection(new Function<CalciteConnection, Void>() {
-          public Void apply(CalciteConnection c) {
-            final SchemaPlus schema = c.getRootSchema();
-            final SchemaPlus adhoc = schema.getSubSchema("adhoc");
-            assertThat(adhoc.getTableNames().contains("EMPLOYEES"), is(true));
-            final Map.Entry<String, CalciteSchema.LatticeEntry> entry =
-                adhoc.unwrap(CalciteSchema.class).getLatticeMap().firstEntry();
-            final Lattice lattice = entry.getValue().getLattice();
-            final String sql = "SELECT \"days\".\"day\"\n"
-                + "FROM \"foodmart\".\"days\" AS \"days\"\n"
-                + "GROUP BY \"days\".\"day\"";
-            assertThat(
-                lattice.sql(ImmutableBitSet.of(0),
-                    ImmutableList.<Lattice.Measure>of()), is(sql));
-            final String sql2 = "SELECT"
-                + " \"days\".\"day\", \"days\".\"week_day\"\n"
-                + "FROM \"foodmart\".\"days\" AS \"days\"";
-            assertThat(
-                lattice.sql(ImmutableBitSet.of(0, 1), false,
-                    ImmutableList.<Lattice.Measure>of()),
-                is(sql2));
-            return null;
-          }
+        .doWithConnection(c -> {
+          final SchemaPlus schema = c.getRootSchema();
+          final SchemaPlus adhoc = schema.getSubSchema("adhoc");
+          assertThat(adhoc.getTableNames().contains("EMPLOYEES"), is(true));
+          final Map.Entry<String, CalciteSchema.LatticeEntry> entry =
+              adhoc.unwrap(CalciteSchema.class).getLatticeMap().firstEntry();
+          final Lattice lattice = entry.getValue().getLattice();
+          final String sql = "SELECT \"days\".\"day\"\n"
+              + "FROM \"foodmart\".\"days\" AS \"days\"\n"
+              + "GROUP BY \"days\".\"day\"";
+          assertThat(
+              lattice.sql(ImmutableBitSet.of(0),
+                  ImmutableList.of()), is(sql));
+          final String sql2 = "SELECT"
+              + " \"days\".\"day\", \"days\".\"week_day\"\n"
+              + "FROM \"foodmart\".\"days\" AS \"days\"";
+          assertThat(
+              lattice.sql(ImmutableBitSet.of(0, 1), false,
+                  ImmutableList.of()),
+              is(sql2));
         });
   }
 
@@ -309,23 +304,20 @@ public class LatticeTest {
             + "from \"foodmart\".\"sales_fact_1997\" as s\n"
             + "join \"foodmart\".\"product\" as p using (\"product_id\")\n")
         .enableMaterializations(true)
-        .substitutionMatches(
-            new Function<RelNode, Void>() {
-              public Void apply(RelNode relNode) {
-                counter.incrementAndGet();
-                String s = RelOptUtil.toString(relNode);
-                assertThat(s,
-                    anyOf(
-                        containsStringLinux(
-                            "LogicalProject(brand_name=[$1], customer_id=[$0])\n"
-                            + "  LogicalAggregate(group=[{2, 10}])\n"
-                            + "    LogicalTableScan(table=[[adhoc, star]])\n"),
-                        containsStringLinux(
-                            "LogicalAggregate(group=[{2, 10}])\n"
-                            + "  LogicalTableScan(table=[[adhoc, star]])\n")));
-                return null;
-              }
-            });
+        .substitutionMatches(relNode -> {
+          counter.incrementAndGet();
+          String s = RelOptUtil.toString(relNode);
+          assertThat(s,
+              anyOf(
+                  containsStringLinux(
+                      "LogicalProject(brand_name=[$1], customer_id=[$0])\n"
+                      + "  LogicalAggregate(group=[{2, 10}])\n"
+                      + "    LogicalTableScan(table=[[adhoc, star]])\n"),
+                  containsStringLinux(
+                      "LogicalAggregate(group=[{2, 10}])\n"
+                      + "  LogicalTableScan(table=[[adhoc, star]])\n")));
+          return null;
+        });
     assertThat(counter.intValue(), equalTo(2));
     that.explainContains(""
         + "EnumerableCalc(expr#0..1=[{inputs}], brand_name=[$t1], customer_id=[$t0])\n"
@@ -334,13 +326,9 @@ public class LatticeTest {
 
     // Run the same query again and see whether it uses the same
     // materialization.
-    that.withHook(
-        Hook.CREATE_MATERIALIZATION,
-        new Function<String, Void>() {
-          public Void apply(String materializationName) {
-            counter.incrementAndGet();
-            return null;
-          }
+    that.withHook(Hook.CREATE_MATERIALIZATION,
+        materializationName -> {
+          counter.incrementAndGet();
         })
         .returnsCount(69203);
 
@@ -546,18 +534,11 @@ public class LatticeTest {
   /** Tests that two queries of the same dimensionality that use different
    * measures can use the same materialization. */
   @Test public void testGroupByEmpty3() {
-    final List<String> mats = Lists.newArrayList();
-    final Function<String, Void> handler =
-        new Function<String, Void>() {
-          public Void apply(String materializationName) {
-            mats.add(materializationName);
-            return null;
-          }
-        };
+    final List<String> mats = new ArrayList<>();
     final CalciteAssert.AssertThat that = foodmartModel().pooled();
     that.query("select sum(\"unit_sales\") as s, count(*) as c\n"
             + "from \"foodmart\".\"sales_fact_1997\"")
-        .withHook(Hook.CREATE_MATERIALIZATION, handler)
+        .withHook(Hook.CREATE_MATERIALIZATION, (Consumer<String>) mats::add)
         .enableMaterializations(true)
         .explainContains("EnumerableTableScan(table=[[adhoc, m{}]])")
         .enable(CalciteAssert.DB != CalciteAssert.DatabaseInstance.ORACLE)
@@ -567,7 +548,7 @@ public class LatticeTest {
     // A similar query can use the same materialization.
     that.query("select sum(\"unit_sales\") as s\n"
         + "from \"foodmart\".\"sales_fact_1997\"")
-        .withHook(Hook.CREATE_MATERIALIZATION, handler)
+        .withHook(Hook.CREATE_MATERIALIZATION, (Consumer<String>) mats::add)
         .enableMaterializations(true)
         .enable(CalciteAssert.DB != CalciteAssert.DatabaseInstance.ORACLE)
         .returnsUnordered("S=266773.0000");

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/LinqFrontJdbcBackTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/LinqFrontJdbcBackTest.java b/core/src/test/java/org/apache/calcite/test/LinqFrontJdbcBackTest.java
index 646ea85..a165656 100644
--- a/core/src/test/java/org/apache/calcite/test/LinqFrontJdbcBackTest.java
+++ b/core/src/test/java/org/apache/calcite/test/LinqFrontJdbcBackTest.java
@@ -17,7 +17,6 @@
 package org.apache.calcite.test;
 
 import org.apache.calcite.jdbc.CalciteConnection;
-import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.ParameterExpression;
 import org.apache.calcite.schema.SchemaPlus;
@@ -47,7 +46,7 @@ public class LinqFrontJdbcBackTest {
             rootSchema.getSubSchema("foodmart"),
             JdbcTest.Customer.class, "customer")
             .where(
-                Expressions.<Predicate1<JdbcTest.Customer>>lambda(
+                Expressions.lambda(
                     Expressions.lessThan(
                         Expressions.field(c, "customer_id"),
                         Expressions.constant(5)),


[10/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/CalciteAssert.java b/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
index 0749de5..9056ecc 100644
--- a/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
+++ b/core/src/test/java/org/apache/calcite/test/CalciteAssert.java
@@ -56,10 +56,6 @@ import org.apache.commons.dbcp2.PoolingDataSource;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.pool2.impl.GenericObjectPool;
 
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableMultiset;
@@ -86,6 +82,7 @@ import java.sql.Statement;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
@@ -96,6 +93,9 @@ import java.util.Properties;
 import java.util.TimeZone;
 import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 import javax.annotation.Nullable;
 import javax.sql.DataSource;
 
@@ -151,8 +151,7 @@ public class CalciteAssert {
   }
 
   public static final ConnectionFactory EMPTY_CONNECTION_FACTORY =
-      new MapConnectionFactory(ImmutableMap.<String, String>of(),
-          ImmutableList.<ConnectionPostProcessor>of());
+      new MapConnectionFactory(ImmutableMap.of(), ImmutableList.of());
 
   /** Implementation of {@link AssertThat} that does nothing. */
   private static final AssertThat DISABLED =
@@ -178,7 +177,7 @@ public class CalciteAssert {
         }
 
         @Override public AssertThat connectThrows(
-            Function<Throwable, Void> exceptionChecker) {
+            Consumer<Throwable> exceptionChecker) {
           return this;
         }
 
@@ -239,38 +238,32 @@ public class CalciteAssert {
 
   static Function<RelNode, Void> checkRel(final String expected,
       final AtomicInteger counter) {
-    return new Function<RelNode, Void>() {
-      public Void apply(RelNode relNode) {
-        if (counter != null) {
-          counter.incrementAndGet();
-        }
-        String s = RelOptUtil.toString(relNode);
-        assertThat(s, containsStringLinux(expected));
-        return null;
+    return relNode -> {
+      if (counter != null) {
+        counter.incrementAndGet();
       }
+      String s = RelOptUtil.toString(relNode);
+      assertThat(s, containsStringLinux(expected));
+      return null;
     };
   }
 
-  static Function<Throwable, Void> checkException(
-      final String expected) {
-    return new Function<Throwable, Void>() {
-      public Void apply(Throwable p0) {
-        assertNotNull(
-            "expected exception but none was thrown", p0);
-        StringWriter stringWriter = new StringWriter();
-        PrintWriter printWriter = new PrintWriter(stringWriter);
-        p0.printStackTrace(printWriter);
-        printWriter.flush();
-        String stack = stringWriter.toString();
-        assertTrue(stack, stack.contains(expected));
-        return null;
-      }
+  static Consumer<Throwable> checkException(final String expected) {
+    return p0 -> {
+      assertNotNull(
+          "expected exception but none was thrown", p0);
+      StringWriter stringWriter = new StringWriter();
+      PrintWriter printWriter = new PrintWriter(stringWriter);
+      p0.printStackTrace(printWriter);
+      printWriter.flush();
+      String stack = stringWriter.toString();
+      assertTrue(stack, stack.contains(expected));
     };
   }
 
-  static Function<Throwable, Void> checkValidationException(final String expected) {
-    return new Function<Throwable, Void>() {
-      @Nullable @Override public Void apply(@Nullable Throwable throwable) {
+  static Consumer<Throwable> checkValidationException(final String expected) {
+    return new Consumer<Throwable>() {
+      @Override public void accept(@Nullable Throwable throwable) {
         assertNotNull("Nothing was thrown", throwable);
 
         Exception exception = containsCorrectException(throwable);
@@ -284,7 +277,6 @@ public class CalciteAssert {
           String stack = stringWriter.toString();
           assertTrue(stack, stack.contains(expected));
         }
-        return null;
       }
 
       private boolean isCorrectException(Throwable throwable) {
@@ -305,67 +297,55 @@ public class CalciteAssert {
     };
   }
 
-  static Function<ResultSet, Void> checkResult(final String expected) {
+  static Consumer<ResultSet> checkResult(final String expected) {
     return checkResult(expected, new ResultSetFormatter());
   }
 
-  static Function<ResultSet, Void> checkResult(final String expected,
+  static Consumer<ResultSet> checkResult(final String expected,
       final ResultSetFormatter resultSetFormatter) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          resultSetFormatter.resultSet(resultSet);
-          assertThat(resultSetFormatter.string(), isLinux(expected));
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    return resultSet -> {
+      try {
+        resultSetFormatter.resultSet(resultSet);
+        assertThat(resultSetFormatter.string(), isLinux(expected));
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  static Function<ResultSet, Void> checkResultValue(final String expected) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          if (!resultSet.next()) {
-            throw new AssertionError("too few rows");
-          }
-          if (resultSet.getMetaData().getColumnCount() != 1) {
-            throw new AssertionError("expected 1 column");
-          }
-          final String resultString = resultSet.getString(1);
-          assertThat(resultString,
-              expected == null ? nullValue(String.class) : isLinux(expected));
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+  static Consumer<ResultSet> checkResultValue(final String expected) {
+    return resultSet -> {
+      try {
+        if (!resultSet.next()) {
+          throw new AssertionError("too few rows");
         }
+        if (resultSet.getMetaData().getColumnCount() != 1) {
+          throw new AssertionError("expected 1 column");
+        }
+        final String resultString = resultSet.getString(1);
+        assertThat(resultString,
+            expected == null ? nullValue(String.class) : isLinux(expected));
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  public static Function<ResultSet, Void> checkResultCount(
+  public static Consumer<ResultSet> checkResultCount(
       final Matcher<Integer> expected) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final int count = CalciteAssert.countRows(resultSet);
-          assertThat(count, expected);
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    return resultSet -> {
+      try {
+        final int count = CalciteAssert.countRows(resultSet);
+        assertThat(count, expected);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  public static Function<Integer, Void> checkUpdateCount(final int expected) {
-    return new Function<Integer, Void>() {
-      public Void apply(Integer updateCount) {
-        assertThat(updateCount, is(expected));
-        return null;
-      }
+  public static Consumer<Integer> checkUpdateCount(final int expected) {
+    return updateCount -> {
+      assertThat(updateCount, is(expected));
     };
   }
 
@@ -374,12 +354,12 @@ public class CalciteAssert {
    *
    * @param ordered Whether order should be the same both times
    */
-  static Function<ResultSet, Void> consistentResult(final boolean ordered) {
-    return new Function<ResultSet, Void>() {
+  static Consumer<ResultSet> consistentResult(final boolean ordered) {
+    return new Consumer<ResultSet>() {
       int executeCount = 0;
       Collection expected;
 
-      public Void apply(ResultSet resultSet) {
+      public void accept(ResultSet resultSet) {
         ++executeCount;
         try {
           final Collection result =
@@ -394,7 +374,6 @@ public class CalciteAssert {
               fail("oops");
             }
           }
-          return null;
         } catch (SQLException e) {
           throw new RuntimeException(e);
         }
@@ -411,105 +390,89 @@ public class CalciteAssert {
   }
 
   /** @see Matchers#returnsUnordered(String...) */
-  static Function<ResultSet, Void> checkResultUnordered(final String... lines) {
+  static Consumer<ResultSet> checkResultUnordered(final String... lines) {
     return checkResult(true, false, lines);
   }
 
   /** @see Matchers#returnsUnordered(String...) */
-  static Function<ResultSet, Void> checkResult(final boolean sort,
+  static Consumer<ResultSet> checkResult(final boolean sort,
       final boolean head, final String... lines) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet resultSet) {
-        try {
-          final List<String> expectedList = Lists.newArrayList(lines);
-          if (sort) {
-            Collections.sort(expectedList);
-          }
-          final List<String> actualList = Lists.newArrayList();
-          CalciteAssert.toStringList(resultSet, actualList);
-          if (sort) {
-            Collections.sort(actualList);
-          }
-          final List<String> trimmedActualList;
-          if (head && actualList.size() > expectedList.size()) {
-            trimmedActualList = actualList.subList(0, expectedList.size());
-          } else {
-            trimmedActualList = actualList;
-          }
-          if (!trimmedActualList.equals(expectedList)) {
-            assertThat(Util.lines(trimmedActualList),
-                equalTo(Util.lines(expectedList)));
-          }
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+    return resultSet -> {
+      try {
+        final List<String> expectedList = Lists.newArrayList(lines);
+        if (sort) {
+          Collections.sort(expectedList);
+        }
+        final List<String> actualList = new ArrayList<>();
+        CalciteAssert.toStringList(resultSet, actualList);
+        if (sort) {
+          Collections.sort(actualList);
+        }
+        final List<String> trimmedActualList;
+        if (head && actualList.size() > expectedList.size()) {
+          trimmedActualList = actualList.subList(0, expectedList.size());
+        } else {
+          trimmedActualList = actualList;
+        }
+        if (!trimmedActualList.equals(expectedList)) {
+          assertThat(Util.lines(trimmedActualList),
+              equalTo(Util.lines(expectedList)));
         }
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  public static Function<ResultSet, Void> checkResultContains(
+  public static Consumer<ResultSet> checkResultContains(
       final String... expected) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet s) {
-        try {
-          final String actual = CalciteAssert.toString(s);
-          for (String st : expected) {
-            assertThat(actual, containsStringLinux(st));
-          }
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
+    return s -> {
+      try {
+        final String actual = toString(s);
+        for (String st : expected) {
+          assertThat(actual, containsStringLinux(st));
         }
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  public static Function<ResultSet, Void> checkResultContains(
+  public static Consumer<ResultSet> checkResultContains(
       final String expected, final int count) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet s) {
-        try {
-          final String actual = Util.toLinux(CalciteAssert.toString(s));
-          assertTrue(
-              actual + " should have " + count + " occurrence of " + expected,
-              StringUtils.countMatches(actual, expected) == count);
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    return s -> {
+      try {
+        final String actual = Util.toLinux(toString(s));
+        assertTrue(
+            actual + " should have " + count + " occurrence of " + expected,
+            StringUtils.countMatches(actual, expected) == count);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  public static Function<ResultSet, Void> checkMaskedResultContains(
+  public static Consumer<ResultSet> checkMaskedResultContains(
       final String expected) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet s) {
-        try {
-          final String actual = Util.toLinux(CalciteAssert.toString(s));
-          final String maskedActual =
-              actual.replaceAll(", id = [0-9]+", "");
-          assertThat(maskedActual, containsString(expected));
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    return s -> {
+      try {
+        final String actual = Util.toLinux(toString(s));
+        final String maskedActual =
+            actual.replaceAll(", id = [0-9]+", "");
+        assertThat(maskedActual, containsString(expected));
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
 
-  public static Function<ResultSet, Void> checkResultType(
-      final String expected) {
-    return new Function<ResultSet, Void>() {
-      public Void apply(ResultSet s) {
-        try {
-          final String actual = typeString(s.getMetaData());
-          assertEquals(expected, actual);
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+  public static Consumer<ResultSet> checkResultType(final String expected) {
+    return s -> {
+      try {
+        final String actual = typeString(s.getMetaData());
+        assertEquals(expected, actual);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     };
   }
@@ -534,10 +497,10 @@ public class CalciteAssert {
       String sql,
       int limit,
       boolean materializationsEnabled,
-      List<Pair<Hook, Function>> hooks,
-      Function<ResultSet, Void> resultChecker,
-      Function<Integer, Void> updateChecker,
-      Function<Throwable, Void> exceptionChecker) throws Exception {
+      List<Pair<Hook, Consumer>> hooks,
+      Consumer<ResultSet> resultChecker,
+      Consumer<Integer> updateChecker,
+      Consumer<Throwable> exceptionChecker) throws Exception {
     final String message =
         "With materializationsEnabled=" + materializationsEnabled
             + ", limit=" + limit;
@@ -560,7 +523,8 @@ public class CalciteAssert {
               DateTimeUtils.UTC_ZONE.getID());
         }
       }
-      for (Pair<Hook, Function> hook : hooks) {
+      for (Pair<Hook, Consumer> hook : hooks) {
+        //noinspection unchecked
         closer.add(hook.left.addThread(hook.right));
       }
       Statement statement = connection.createStatement();
@@ -574,21 +538,21 @@ public class CalciteAssert {
           updateCount = statement.executeUpdate(sql);
         }
         if (exceptionChecker != null) {
-          exceptionChecker.apply(null);
+          exceptionChecker.accept(null);
           return;
         }
       } catch (Exception | Error e) {
         if (exceptionChecker != null) {
-          exceptionChecker.apply(e);
+          exceptionChecker.accept(e);
           return;
         }
         throw e;
       }
       if (resultChecker != null) {
-        resultChecker.apply(resultSet);
+        resultChecker.accept(resultSet);
       }
       if (updateChecker != null) {
-        updateChecker.apply(updateCount);
+        updateChecker.accept(updateCount);
       }
       if (resultSet != null) {
         resultSet.close();
@@ -616,23 +580,12 @@ public class CalciteAssert {
     try (Closer closer = new Closer()) {
       if (convertChecker != null) {
         closer.add(
-            Hook.TRIMMED.addThread(
-                new Function<RelNode, Void>() {
-                  public Void apply(RelNode rel) {
-                    convertChecker.apply(rel);
-                    return null;
-                  }
-                }));
+            Hook.TRIMMED.addThread((Consumer<RelNode>) convertChecker::apply));
       }
       if (substitutionChecker != null) {
         closer.add(
             Hook.SUB.addThread(
-                new Function<RelNode, Void>() {
-                  public Void apply(RelNode rel) {
-                    substitutionChecker.apply(rel);
-                    return null;
-                  }
-                }));
+                (Consumer<RelNode>) substitutionChecker::apply));
       }
       ((CalciteConnection) connection).getProperties().setProperty(
           CalciteConnectionProperty.MATERIALIZATIONS_ENABLED.camelName(),
@@ -769,14 +722,14 @@ public class CalciteAssert {
       }
       return rootSchema.add("foodmart2", new CloneSchema(foodmart));
     case GEO:
-      ModelHandler.addFunctions(rootSchema, null, ImmutableList.<String>of(),
+      ModelHandler.addFunctions(rootSchema, null, ImmutableList.of(),
           GeoFunctions.class.getName(), "*", true);
       final SchemaPlus s = rootSchema.add("GEO", new AbstractSchema());
-      ModelHandler.addFunctions(s, "countries", ImmutableList.<String>of(),
+      ModelHandler.addFunctions(s, "countries", ImmutableList.of(),
           CountriesTableFunction.class.getName(), null, false);
       final String sql = "select * from table(\"countries\"(true))";
       final ViewTableMacro viewMacro = ViewTable.viewMacro(rootSchema, sql,
-          ImmutableList.of("GEO"), ImmutableList.<String>of(), false);
+          ImmutableList.of("GEO"), ImmutableList.of(), false);
       s.add("countries", viewMacro);
       return s;
     case HR:
@@ -808,7 +761,7 @@ public class CalciteAssert {
                   + "    ('Grace', 60, 'F'),\n"
                   + "    ('Wilma', cast(null as integer), 'F'))\n"
                   + "  as t(ename, deptno, gender)",
-              ImmutableList.<String>of(), ImmutableList.of("POST", "EMP"),
+              ImmutableList.of(), ImmutableList.of("POST", "EMP"),
               null));
       post.add("DEPT",
           ViewTable.viewMacro(post,
@@ -817,7 +770,7 @@ public class CalciteAssert {
                   + "    (20, 'Marketing'),\n"
                   + "    (30, 'Engineering'),\n"
                   + "    (40, 'Empty')) as t(deptno, dname)",
-              ImmutableList.<String>of(), ImmutableList.of("POST", "DEPT"),
+              ImmutableList.of(), ImmutableList.of("POST", "DEPT"),
               null));
       post.add("EMPS",
           ViewTable.viewMacro(post,
@@ -828,7 +781,7 @@ public class CalciteAssert {
                   + "    (120, 'Wilma', 20, 'F',                   CAST(NULL AS VARCHAR(20)), 1,                 5, UNKNOWN, TRUE,  DATE '2005-09-07'),\n"
                   + "    (130, 'Alice', 40, 'F',                   'Vancouver',               2, CAST(NULL AS INT), FALSE,   TRUE,  DATE '2007-01-01'))\n"
                   + " as t(empno, name, deptno, gender, city, empid, age, slacker, manager, joinedat)",
-              ImmutableList.<String>of(), ImmutableList.of("POST", "EMPS"),
+              ImmutableList.of(), ImmutableList.of("POST", "EMPS"),
               null));
       return post;
     default:
@@ -852,15 +805,14 @@ public class CalciteAssert {
    */
   public static void assertArrayEqual(
       String message, Object[] expected, Object[] actual) {
-    Joiner joiner = Joiner.on('\n');
-    String strExpected = expected == null ? null : joiner.join(expected);
-    String strActual = actual == null ? null : joiner.join(actual);
-    assertEquals(message, strExpected, strActual);
+    assertEquals(message, str(expected), str(actual));
   }
 
-  static <F, T> Function<F, T> constantNull() {
-    //noinspection unchecked
-    return (Function<F, T>) (Function) Functions.<T>constant(null);
+  private static String str(Object[] objects) {
+    return objects == null
+          ? null
+          : Arrays.stream(objects).map(Object::toString)
+              .collect(Collectors.joining("\n"));
   }
 
   /** Returns a {@link PropBuilder}. */
@@ -878,7 +830,7 @@ public class CalciteAssert {
         new AssertThat(EMPTY_CONNECTION_FACTORY);
 
     private AssertThat(ConnectionFactory connectionFactory) {
-      this.connectionFactory = Preconditions.checkNotNull(connectionFactory);
+      this.connectionFactory = Objects.requireNonNull(connectionFactory);
     }
 
     public AssertThat with(Config config) {
@@ -973,26 +925,23 @@ public class CalciteAssert {
     /** Adds materializations to the schema. */
     public final AssertThat withMaterializations(String model, final boolean existing,
         final String... materializations) {
-      return withMaterializations(model,
-          new Function<JsonBuilder, List<Object>>() {
-            public List<Object> apply(JsonBuilder builder) {
-              assert materializations.length % 2 == 0;
-              final List<Object> list = builder.list();
-              for (int i = 0; i < materializations.length; i++) {
-                String table = materializations[i++];
-                final Map<String, Object> map = builder.map();
-                map.put("table", table);
-                if (!existing) {
-                  map.put("view", table + "v");
-                }
-                String sql = materializations[i];
-                final String sql2 = sql.replaceAll("`", "\"");
-                map.put("sql", sql2);
-                list.add(map);
-              }
-              return list;
-            }
-          });
+      return withMaterializations(model, builder -> {
+        assert materializations.length % 2 == 0;
+        final List<Object> list = builder.list();
+        for (int i = 0; i < materializations.length; i++) {
+          String table = materializations[i++];
+          final Map<String, Object> map = builder.map();
+          map.put("table", table);
+          if (!existing) {
+            map.put("view", table + "v");
+          }
+          String sql = materializations[i];
+          final String sql2 = sql.replaceAll("`", "\"");
+          map.put("sql", sql2);
+          list.add(map);
+        }
+        return list;
+      });
     }
 
     /** Adds materializations to the schema. */
@@ -1033,8 +982,7 @@ public class CalciteAssert {
 
     /** Asserts that there is an exception that matches the given predicate
      * while creating a connection. */
-    public AssertThat connectThrows(
-        Function<Throwable, Void> exceptionChecker) {
+    public AssertThat connectThrows(Consumer<Throwable> exceptionChecker) {
       Throwable throwable;
       try (Connection x = connectionFactory.createConnection()) {
         try {
@@ -1046,7 +994,7 @@ public class CalciteAssert {
       } catch (Throwable e) {
         throwable = e;
       }
-      exceptionChecker.apply(throwable);
+      exceptionChecker.accept(throwable);
       return this;
     }
 
@@ -1061,6 +1009,16 @@ public class CalciteAssert {
       }
     }
 
+    /** Creates a {@link org.apache.calcite.jdbc.CalciteConnection}
+     * and executes a callback that returns no result. */
+    public final AssertThat doWithConnection(Consumer<CalciteConnection> fn)
+        throws Exception {
+      return doWithConnection(c -> {
+        fn.accept(c);
+        return null;
+      });
+    }
+
     /** Creates a {@link DataContext} and executes a callback. */
     public <T> AssertThat doWithDataContext(Function<DataContext, T> fn)
         throws Exception {
@@ -1130,6 +1088,7 @@ public class CalciteAssert {
   }
 
   /** Connection post processor */
+  @FunctionalInterface
   public interface ConnectionPostProcessor {
     Connection apply(Connection connection) throws SQLException;
   }
@@ -1209,8 +1168,8 @@ public class CalciteAssert {
 
     private MapConnectionFactory(ImmutableMap<String, String> map,
         ImmutableList<ConnectionPostProcessor> postProcessors) {
-      this.map = Preconditions.checkNotNull(map);
-      this.postProcessors = Preconditions.checkNotNull(postProcessors);
+      this.map = Objects.requireNonNull(map);
+      this.postProcessors = Objects.requireNonNull(postProcessors);
     }
 
     @Override public boolean equals(Object obj) {
@@ -1267,7 +1226,7 @@ public class CalciteAssert {
     private String plan;
     private int limit;
     private boolean materializationsEnabled = false;
-    private final List<Pair<Hook, Function>> hooks = Lists.newArrayList();
+    private final List<Pair<Hook, Consumer>> hooks = new ArrayList<>();
 
     private AssertQuery(ConnectionFactory connectionFactory, String sql) {
       this.sql = sql;
@@ -1280,10 +1239,10 @@ public class CalciteAssert {
 
     /** Performs an action using a connection, and closes the connection
      * afterwards. */
-    public final AssertQuery withConnection(Function<Connection, Void> f)
+    public final AssertQuery withConnection(Consumer<Connection> f)
         throws Exception {
       try (Connection c = createConnection()) {
-        f.apply(c);
+        f.accept(c);
       }
       return this;
     }
@@ -1296,7 +1255,8 @@ public class CalciteAssert {
       return returns(checkResult(expected));
     }
 
-    /** Simlar to {@link #returns}, but trims a few values before comparing. */
+    /** Similar to {@link #returns}, but trims a few values before
+     * comparing. */
     public AssertQuery returns2(final String expected) {
       return returns(
           checkResult(expected,
@@ -1328,7 +1288,7 @@ public class CalciteAssert {
       return returns(checkResultCount(is(expectedCount)));
     }
 
-    public final AssertQuery returns(Function<ResultSet, Void> checker) {
+    public final AssertQuery returns(Consumer<ResultSet> checker) {
       return returns(sql, checker);
     }
 
@@ -1343,8 +1303,14 @@ public class CalciteAssert {
       }
     }
 
-    protected AssertQuery returns(String sql,
-        Function<ResultSet, Void> checker) {
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed in 2.0
+    public final AssertQuery returns(
+        com.google.common.base.Function<ResultSet, Void> checker) {
+      return returns(sql, checker::apply);
+    }
+
+    protected AssertQuery returns(String sql, Consumer<ResultSet> checker) {
       try (final Connection connection = createConnection()) {
         assertQuery(connection, sql, limit, materializationsEnabled,
             hooks, checker, null, null);
@@ -1460,7 +1426,7 @@ public class CalciteAssert {
     }
 
     public final AssertQuery explainMatches(String extra,
-        Function<ResultSet, Void> checker) {
+        Consumer<ResultSet> checker) {
       return returns("explain plan " + extra + "for " + sql, checker);
     }
 
@@ -1478,8 +1444,8 @@ public class CalciteAssert {
       ensurePlan(checkUpdateCount(count));
       expected = "getDataSource(), \""
           + expected.replace("\\", "\\\\")
-              .replace("\"", "\\\"")
-              .replaceAll("\n", "\\\\n")
+          .replace("\"", "\\\"")
+          .replaceAll("\n", "\\\\n")
           + "\"";
       assertTrue(
           "Plan [" + plan + "] contains [" + expected + "]",
@@ -1492,23 +1458,17 @@ public class CalciteAssert {
     public AssertQuery planHasSql(String expected) {
       return planContains(
           "getDataSource(), \""
-          + expected.replace("\\", "\\\\")
+              + expected.replace("\\", "\\\\")
               .replace("\"", "\\\"")
               .replaceAll("\n", "\\\\n")
-          + "\"");
+              + "\"");
     }
 
-    private void ensurePlan(Function<Integer, Void> checkUpdate) {
+    private void ensurePlan(Consumer<Integer> checkUpdate) {
       if (plan != null) {
         return;
       }
-      addHook(Hook.JAVA_PLAN,
-          new Function<String, Void>() {
-            public Void apply(String a0) {
-              plan = a0;
-              return null;
-            }
-          });
+      addHook(Hook.JAVA_PLAN, (Consumer<String>) a0 -> plan = a0);
       try (final Connection connection = createConnection()) {
         assertQuery(connection, sql, limit, materializationsEnabled,
             hooks, null, checkUpdate, null);
@@ -1523,19 +1483,13 @@ public class CalciteAssert {
      * queries. The checker should throw to fail the test if it does not see
      * what it wants. This method can be used to check whether a particular
      * MongoDB or SQL query is generated, for instance. */
-    public AssertQuery queryContains(Function<List, Void> predicate1) {
-      final List<Object> list = Lists.newArrayList();
-      addHook(Hook.QUERY_PLAN,
-          new Function<Object, Void>() {
-            public Void apply(Object a0) {
-              list.add(a0);
-              return null;
-            }
-          });
+    public AssertQuery queryContains(Consumer<List> predicate1) {
+      final List<Object> list = new ArrayList<>();
+      addHook(Hook.QUERY_PLAN, list::add);
       try (final Connection connection = createConnection()) {
         assertQuery(connection, sql, limit, materializationsEnabled,
             hooks, null, null, null);
-        predicate1.apply(list);
+        predicate1.accept(list);
         return this;
       } catch (Exception e) {
         throw new RuntimeException(
@@ -1543,6 +1497,14 @@ public class CalciteAssert {
       }
     }
 
+    /** @deprecated Use {@link #queryContains(Consumer)}. */
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed before 2.0
+    public final AssertQuery queryContains(
+        com.google.common.base.Function<List, Void> predicate1) {
+      return queryContains((Consumer<List>) predicate1::apply);
+    }
+
     /** Sets a limit on the number of rows returned. -1 means no limit. */
     public AssertQuery limit(int limit) {
       this.limit = limit;
@@ -1555,7 +1517,7 @@ public class CalciteAssert {
         materializationsEnabled = false;
         final boolean ordered =
             sql.toUpperCase(Locale.ROOT).contains("ORDER BY");
-        final Function<ResultSet, Void> checker = consistentResult(ordered);
+        final Consumer<ResultSet> checker = consistentResult(ordered);
         returns(checker);
         materializationsEnabled = true;
         returns(checker);
@@ -1569,35 +1531,37 @@ public class CalciteAssert {
       return this;
     }
 
+    @SuppressWarnings("Guava")
+    @Deprecated // to be removed in 2.0
+    public <T> AssertQuery withHook(Hook hook, Function<T, Void> handler) {
+      return withHook(hook, (Consumer<T>) handler::apply);
+    }
+
     /** Adds a hook and a handler for that hook. Calcite will create a thread
-     * hook (by calling {@link Hook#addThread(com.google.common.base.Function)})
+     * hook (by calling {@link Hook#addThread(Consumer)})
      * just before running the query, and remove the hook afterwards. */
-    public <T> AssertQuery withHook(Hook hook, Function<T, Void> handler) {
+    public <T> AssertQuery withHook(Hook hook, Consumer<T> handler) {
       addHook(hook, handler);
       return this;
     }
 
-    private <T> void addHook(Hook hook, Function<T, Void> handler) {
-      hooks.add(Pair.of(hook, (Function) handler));
+    private <T> void addHook(Hook hook, Consumer<T> handler) {
+      hooks.add(Pair.of(hook, handler));
     }
 
     /** Adds a property hook. */
     public <V> AssertQuery withProperty(Hook hook, V value) {
-      return withHook(hook, Hook.property(value));
+      return withHook(hook, Hook.propertyJ(value));
     }
 
     /** Adds a factory to create a {@link RelNode} query. This {@code RelNode}
      * will be used instead of the SQL string. */
     public AssertQuery withRel(final Function<RelBuilder, RelNode> relFn) {
       return withHook(Hook.STRING_TO_QUERY,
-          new Function<
-              Pair<FrameworkConfig, Holder<CalcitePrepare.Query>>, Void>() {
-            public Void apply(
-                Pair<FrameworkConfig, Holder<CalcitePrepare.Query>> pair) {
-              final RelBuilder b = RelBuilder.create(pair.left);
-              pair.right.set(CalcitePrepare.Query.of(relFn.apply(b)));
-              return null;
-            }
+          (Consumer<Pair<FrameworkConfig, Holder<CalcitePrepare.Query>>>)
+          pair -> {
+            final RelBuilder b = RelBuilder.create(pair.left);
+            pair.right.set(CalcitePrepare.Query.of(relFn.apply(b)));
           });
     }
   }
@@ -1613,10 +1577,10 @@ public class CalciteAssert {
       this.function = function;
     }
 
-    public final AssertMetaData returns(Function<ResultSet, Void> checker) {
+    public final AssertMetaData returns(Consumer<ResultSet> checker) {
       try (final Connection c = connectionFactory.createConnection()) {
         final ResultSet resultSet = function.apply(c);
-        checker.apply(resultSet);
+        checker.accept(resultSet);
         resultSet.close();
         c.close();
         return this;
@@ -1701,7 +1665,7 @@ public class CalciteAssert {
     }
 
     @Override public AssertQuery returns(String sql,
-        Function<ResultSet, Void> checker) {
+        Consumer<ResultSet> checker) {
       return this;
     }
 
@@ -1735,8 +1699,7 @@ public class CalciteAssert {
       return this;
     }
 
-    @Override public AssertQuery
-    queryContains(Function<List, Void> predicate1) {
+    @Override public AssertQuery queryContains(Consumer<List> predicate1) {
       return this;
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/CollectionTypeTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/CollectionTypeTest.java b/core/src/test/java/org/apache/calcite/test/CollectionTypeTest.java
index 99440c8..a095f8c 100644
--- a/core/src/test/java/org/apache/calcite/test/CollectionTypeTest.java
+++ b/core/src/test/java/org/apache/calcite/test/CollectionTypeTest.java
@@ -452,8 +452,7 @@ public class CollectionTypeTest {
     }
 
     @Override public boolean rolledUpColumnValidInsideAgg(String column,
-                                                          SqlCall call, SqlNode parent,
-                                                          CalciteConnectionConfig config) {
+        SqlCall call, SqlNode parent, CalciteConnectionConfig config) {
       return false;
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/ExceptionMessageTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/ExceptionMessageTest.java b/core/src/test/java/org/apache/calcite/test/ExceptionMessageTest.java
index 2d61698..6d605f8 100644
--- a/core/src/test/java/org/apache/calcite/test/ExceptionMessageTest.java
+++ b/core/src/test/java/org/apache/calcite/test/ExceptionMessageTest.java
@@ -27,7 +27,6 @@ import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.SQLException;
 import java.sql.Statement;
-import java.util.Iterator;
 
 import static org.hamcrest.CoreMatchers.containsString;
 import static org.hamcrest.CoreMatchers.equalTo;
@@ -51,10 +50,8 @@ public class ExceptionMessageTest {
         new Entry(2, "name2")
     };
 
-    public Iterable<Entry> badEntries = new Iterable<Entry>() {
-      public Iterator<Entry> iterator() {
-        throw new IllegalStateException("Can't iterate over badEntries");
-      }
+    public Iterable<Entry> badEntries = () -> {
+      throw new IllegalStateException("Can't iterate over badEntries");
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/FoodMartLatticeStatisticProvider.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/FoodMartLatticeStatisticProvider.java b/core/src/test/java/org/apache/calcite/test/FoodMartLatticeStatisticProvider.java
index 4eae872..be9213e 100644
--- a/core/src/test/java/org/apache/calcite/test/FoodMartLatticeStatisticProvider.java
+++ b/core/src/test/java/org/apache/calcite/test/FoodMartLatticeStatisticProvider.java
@@ -36,12 +36,8 @@ import java.util.Map;
 public class FoodMartLatticeStatisticProvider
     extends DelegatingLatticeStatisticProvider {
   public static final FoodMartLatticeStatisticProvider.Factory FACTORY =
-      new Factory() {
-        public LatticeStatisticProvider apply(Lattice lattice) {
-          return new FoodMartLatticeStatisticProvider(lattice,
-              Lattices.CACHED_SQL.apply(lattice));
-        }
-      };
+      lattice -> new FoodMartLatticeStatisticProvider(lattice,
+          Lattices.CACHED_SQL.apply(lattice));
 
   private static final Map<String, Integer> CARDINALITY_MAP =
       ImmutableMap.<String, Integer>builder()

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/InduceGroupingTypeTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/InduceGroupingTypeTest.java b/core/src/test/java/org/apache/calcite/test/InduceGroupingTypeTest.java
index 59b7f73..de82061 100644
--- a/core/src/test/java/org/apache/calcite/test/InduceGroupingTypeTest.java
+++ b/core/src/test/java/org/apache/calcite/test/InduceGroupingTypeTest.java
@@ -19,10 +19,9 @@ package org.apache.calcite.test;
 import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.util.ImmutableBitSet;
 
-import com.google.common.collect.Lists;
-
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import static org.junit.Assert.assertEquals;
@@ -37,7 +36,7 @@ public class InduceGroupingTypeTest {
     final ImmutableBitSet groupSet = ImmutableBitSet.of(1, 2, 4, 5);
 
     // SIMPLE
-    List<ImmutableBitSet> groupSets = Lists.newArrayList();
+    List<ImmutableBitSet> groupSets = new ArrayList<>();
     groupSets.add(groupSet);
     assertEquals(Aggregate.Group.SIMPLE,
         Aggregate.Group.induce(groupSet, groupSets));
@@ -48,7 +47,7 @@ public class InduceGroupingTypeTest {
         Aggregate.Group.induce(groupSet, groupSets));
 
     // ROLLUP
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(ImmutableBitSet.of(1, 2, 4, 5));
     groupSets.add(ImmutableBitSet.of(1, 2, 4));
     groupSets.add(ImmutableBitSet.of(1, 2));
@@ -58,7 +57,7 @@ public class InduceGroupingTypeTest {
         Aggregate.Group.induce(groupSet, groupSets));
 
     // OTHER
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(ImmutableBitSet.of(1, 2, 4, 5));
     groupSets.add(ImmutableBitSet.of(1, 2, 4));
     groupSets.add(ImmutableBitSet.of(1, 2));
@@ -66,7 +65,7 @@ public class InduceGroupingTypeTest {
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(ImmutableBitSet.of(1, 2, 4, 5));
     groupSets.add(ImmutableBitSet.of(1, 2, 4));
     groupSets.add(ImmutableBitSet.of(1, 2));
@@ -74,7 +73,7 @@ public class InduceGroupingTypeTest {
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(ImmutableBitSet.of(1, 2, 5));
     groupSets.add(ImmutableBitSet.of(1, 2, 4));
     groupSets.add(ImmutableBitSet.of(1, 2));
@@ -92,11 +91,11 @@ public class InduceGroupingTypeTest {
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(ImmutableBitSet.of());
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
@@ -108,23 +107,23 @@ public class InduceGroupingTypeTest {
     final ImmutableBitSet groupSet = ImmutableBitSet.of(2);
 
     // Could be ROLLUP but we prefer CUBE
-    List<ImmutableBitSet> groupSets = Lists.newArrayList();
+    List<ImmutableBitSet> groupSets = new ArrayList<>();
     groupSets.add(groupSet);
     groupSets.add(ImmutableBitSet.of());
     assertEquals(Aggregate.Group.CUBE,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(ImmutableBitSet.of());
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     groupSets.add(groupSet);
     assertEquals(Aggregate.Group.SIMPLE,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
   }
@@ -133,12 +132,12 @@ public class InduceGroupingTypeTest {
     final ImmutableBitSet groupSet = ImmutableBitSet.of();
 
     // Could be CUBE or ROLLUP but we choose SIMPLE
-    List<ImmutableBitSet> groupSets = Lists.newArrayList();
+    List<ImmutableBitSet> groupSets = new ArrayList<>();
     groupSets.add(groupSet);
     assertEquals(Aggregate.Group.SIMPLE,
         Aggregate.Group.induce(groupSet, groupSets));
 
-    groupSets = Lists.newArrayList();
+    groupSets = new ArrayList<>();
     assertEquals(Aggregate.Group.OTHER,
         Aggregate.Group.induce(groupSet, groupSets));
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/InterpreterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/InterpreterTest.java b/core/src/test/java/org/apache/calcite/test/InterpreterTest.java
index 9e419fd..a179da7 100644
--- a/core/src/test/java/org/apache/calcite/test/InterpreterTest.java
+++ b/core/src/test/java/org/apache/calcite/test/InterpreterTest.java
@@ -28,12 +28,11 @@ import org.apache.calcite.tools.FrameworkConfig;
 import org.apache.calcite.tools.Frameworks;
 import org.apache.calcite.tools.Planner;
 
-import com.google.common.collect.Lists;
-
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
@@ -130,7 +129,7 @@ public class InterpreterTest {
 
   private static void assertRows(Interpreter interpreter,
       boolean unordered, String... rows) {
-    final List<String> list = Lists.newArrayList();
+    final List<String> list = new ArrayList<>();
     for (Object[] row : interpreter) {
       list.add(Arrays.toString(row));
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/JdbcAdapterTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/JdbcAdapterTest.java b/core/src/test/java/org/apache/calcite/test/JdbcAdapterTest.java
index e65fe65..1bf0f7f 100644
--- a/core/src/test/java/org/apache/calcite/test/JdbcAdapterTest.java
+++ b/core/src/test/java/org/apache/calcite/test/JdbcAdapterTest.java
@@ -17,12 +17,9 @@
 package org.apache.calcite.test;
 
 import org.apache.calcite.config.Lex;
-import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.test.CalciteAssert.AssertThat;
 import org.apache.calcite.test.CalciteAssert.DatabaseInstance;
 
-import com.google.common.base.Function;
-
 import org.hsqldb.jdbcDriver;
 
 import org.junit.Test;
@@ -622,19 +619,15 @@ public class JdbcAdapterTest {
             "jdbcSchema: null");
     CalciteAssert.model(
         model)
-        .doWithConnection(
-            new Function<CalciteConnection, Void>() {
-              public Void apply(CalciteConnection connection) {
-                try {
-                  final ResultSet resultSet =
-                      connection.getMetaData().getTables(null, null, "%", null);
-                  assertFalse(CalciteAssert.toString(resultSet).isEmpty());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            final ResultSet resultSet =
+                connection.getMetaData().getTables(null, null, "%", null);
+            assertFalse(CalciteAssert.toString(resultSet).isEmpty());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Test case for
@@ -720,19 +713,15 @@ public class JdbcAdapterTest {
         CalciteAssert.model(JdbcTest.FOODMART_MODEL)
             .enable(CalciteAssert.DB == DatabaseInstance.HSQLDB
                 || CalciteAssert.DB == DatabaseInstance.POSTGRESQL);
-    that.doWithConnection(
-        new Function<CalciteConnection, Void>() {
-          public Void apply(CalciteConnection connection) {
-            try (LockWrapper ignore = exclusiveCleanDb(connection)) {
-              that.query(sql)
-                  .explainContains(explain)
-                  .planUpdateHasSql(jdbcSql, 1);
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        });
+    that.doWithConnection(connection -> {
+      try (LockWrapper ignore = exclusiveCleanDb(connection)) {
+        that.query(sql)
+            .explainContains(explain)
+            .planUpdateHasSql(jdbcSql, 1);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+    });
   }
 
   @Test public void testTableModifyInsertMultiValues() throws Exception {
@@ -756,19 +745,15 @@ public class JdbcAdapterTest {
         CalciteAssert.model(JdbcTest.FOODMART_MODEL)
             .enable(CalciteAssert.DB == DatabaseInstance.HSQLDB
                 || CalciteAssert.DB == DatabaseInstance.POSTGRESQL);
-    that.doWithConnection(
-        new Function<CalciteConnection, Void>() {
-          public Void apply(CalciteConnection connection) {
-            try (LockWrapper ignore = exclusiveCleanDb(connection)) {
-              that.query(sql)
-                  .explainContains(explain)
-                  .planUpdateHasSql(jdbcSql, 2);
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        });
+    that.doWithConnection(connection -> {
+      try (LockWrapper ignore = exclusiveCleanDb(connection)) {
+        that.query(sql)
+            .explainContains(explain)
+            .planUpdateHasSql(jdbcSql, 2);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+    });
   }
 
   @Test public void testTableModifyInsertWithSubQuery() throws Exception {
@@ -776,37 +761,34 @@ public class JdbcAdapterTest {
         .model(JdbcTest.FOODMART_MODEL)
         .enable(CalciteAssert.DB == DatabaseInstance.HSQLDB);
 
-    that.doWithConnection(new Function<CalciteConnection, Void>() {
-      public Void apply(CalciteConnection connection) {
-        try (LockWrapper ignore = exclusiveCleanDb(connection)) {
-          final String sql = "INSERT INTO \"foodmart\".\"expense_fact\"(\n"
-              + " \"store_id\", \"account_id\", \"exp_date\", \"time_id\","
-              + " \"category_id\", \"currency_id\", \"amount\")\n"
-              + "SELECT  \"store_id\", \"account_id\", \"exp_date\","
-              + " \"time_id\" + 1, \"category_id\", \"currency_id\","
-              + " \"amount\"\n"
-              + "FROM \"foodmart\".\"expense_fact\"\n"
-              + "WHERE \"store_id\" = 666";
-          final String explain = "PLAN=JdbcToEnumerableConverter\n"
-              + "  JdbcTableModify(table=[[foodmart, expense_fact]], operation=[INSERT], flattened=[false])\n"
-              + "    JdbcProject(store_id=[$0], account_id=[$1], exp_date=[$2], time_id=[+($3, 1)], category_id=[$4], currency_id=[$5], amount=[$6])\n"
-              + "      JdbcFilter(condition=[=($0, 666)])\n"
-              + "        JdbcTableScan(table=[[foodmart, expense_fact]])\n";
-          final String jdbcSql = "INSERT INTO \"foodmart\".\"expense_fact\""
-              + " (\"store_id\", \"account_id\", \"exp_date\", \"time_id\","
-              + " \"category_id\", \"currency_id\", \"amount\")\n"
-              + "(SELECT \"store_id\", \"account_id\", \"exp_date\","
-              + " \"time_id\" + 1 AS \"time_id\", \"category_id\","
-              + " \"currency_id\", \"amount\"\n"
-              + "FROM \"foodmart\".\"expense_fact\"\n"
-              + "WHERE \"store_id\" = 666)";
-          that.query(sql)
-              .explainContains(explain)
-              .planUpdateHasSql(jdbcSql, 1);
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    that.doWithConnection(connection -> {
+      try (LockWrapper ignore = exclusiveCleanDb(connection)) {
+        final String sql = "INSERT INTO \"foodmart\".\"expense_fact\"(\n"
+            + " \"store_id\", \"account_id\", \"exp_date\", \"time_id\","
+            + " \"category_id\", \"currency_id\", \"amount\")\n"
+            + "SELECT  \"store_id\", \"account_id\", \"exp_date\","
+            + " \"time_id\" + 1, \"category_id\", \"currency_id\","
+            + " \"amount\"\n"
+            + "FROM \"foodmart\".\"expense_fact\"\n"
+            + "WHERE \"store_id\" = 666";
+        final String explain = "PLAN=JdbcToEnumerableConverter\n"
+            + "  JdbcTableModify(table=[[foodmart, expense_fact]], operation=[INSERT], flattened=[false])\n"
+            + "    JdbcProject(store_id=[$0], account_id=[$1], exp_date=[$2], time_id=[+($3, 1)], category_id=[$4], currency_id=[$5], amount=[$6])\n"
+            + "      JdbcFilter(condition=[=($0, 666)])\n"
+            + "        JdbcTableScan(table=[[foodmart, expense_fact]])\n";
+        final String jdbcSql = "INSERT INTO \"foodmart\".\"expense_fact\""
+            + " (\"store_id\", \"account_id\", \"exp_date\", \"time_id\","
+            + " \"category_id\", \"currency_id\", \"amount\")\n"
+            + "(SELECT \"store_id\", \"account_id\", \"exp_date\","
+            + " \"time_id\" + 1 AS \"time_id\", \"category_id\","
+            + " \"currency_id\", \"amount\"\n"
+            + "FROM \"foodmart\".\"expense_fact\"\n"
+            + "WHERE \"store_id\" = 666)";
+        that.query(sql)
+            .explainContains(explain)
+            .planUpdateHasSql(jdbcSql, 1);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     });
   }
@@ -816,27 +798,25 @@ public class JdbcAdapterTest {
         .model(JdbcTest.FOODMART_MODEL)
         .enable(CalciteAssert.DB == DatabaseInstance.HSQLDB);
 
-    that.doWithConnection(new Function<CalciteConnection, Void>() {
-      public Void apply(CalciteConnection connection) {
-        try (LockWrapper ignore = exclusiveCleanDb(connection)) {
-          final String sql = "UPDATE \"foodmart\".\"expense_fact\"\n"
-              + " SET \"account_id\"=888\n"
-              + " WHERE \"store_id\"=666\n";
-          final String explain = "PLAN=JdbcToEnumerableConverter\n"
-              + "  JdbcTableModify(table=[[foodmart, expense_fact]], operation=[UPDATE], updateColumnList=[[account_id]], sourceExpressionList=[[888]], flattened=[false])\n"
-              + "    JdbcProject(store_id=[$0], account_id=[$1], exp_date=[$2], time_id=[$3], category_id=[$4], currency_id=[$5], amount=[$6], EXPR$0=[888])\n"
-              + "      JdbcFilter(condition=[=($0, 666)])\n"
-              + "        JdbcTableScan(table=[[foodmart, expense_fact]])";
-          final String jdbcSql = "UPDATE \"foodmart\".\"expense_fact\""
-              + " SET \"account_id\" = 888\n"
-              + "WHERE \"store_id\" = 666";
-          that.query(sql)
-              .explainContains(explain)
-              .planUpdateHasSql(jdbcSql, 1);
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    that.doWithConnection(connection -> {
+      try (LockWrapper ignore = exclusiveCleanDb(connection)) {
+        final String sql = "UPDATE \"foodmart\".\"expense_fact\"\n"
+            + " SET \"account_id\"=888\n"
+            + " WHERE \"store_id\"=666\n";
+        final String explain = "PLAN=JdbcToEnumerableConverter\n"
+            + "  JdbcTableModify(table=[[foodmart, expense_fact]], operation=[UPDATE], updateColumnList=[[account_id]], sourceExpressionList=[[888]], flattened=[false])\n"
+            + "    JdbcProject(store_id=[$0], account_id=[$1], exp_date=[$2], time_id=[$3], category_id=[$4], currency_id=[$5], amount=[$6], EXPR$0=[888])\n"
+            + "      JdbcFilter(condition=[=($0, 666)])\n"
+            + "        JdbcTableScan(table=[[foodmart, expense_fact]])";
+        final String jdbcSql = "UPDATE \"foodmart\".\"expense_fact\""
+            + " SET \"account_id\" = 888\n"
+            + "WHERE \"store_id\" = 666";
+        that.query(sql)
+            .explainContains(explain)
+            .planUpdateHasSql(jdbcSql, 1);
+        return null;
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     });
   }
@@ -846,24 +826,21 @@ public class JdbcAdapterTest {
         .model(JdbcTest.FOODMART_MODEL)
         .enable(CalciteAssert.DB == DatabaseInstance.HSQLDB);
 
-    that.doWithConnection(new Function<CalciteConnection, Void>() {
-      public Void apply(CalciteConnection connection) {
-        try (LockWrapper ignore = exclusiveCleanDb(connection)) {
-          final String sql = "DELETE FROM \"foodmart\".\"expense_fact\"\n"
-              + "WHERE \"store_id\"=666\n";
-          final String explain = "PLAN=JdbcToEnumerableConverter\n"
-              + "  JdbcTableModify(table=[[foodmart, expense_fact]], operation=[DELETE], flattened=[false])\n"
-              + "    JdbcFilter(condition=[=($0, 666)])\n"
-              + "      JdbcTableScan(table=[[foodmart, expense_fact]]";
-          final String jdbcSql = "DELETE FROM \"foodmart\".\"expense_fact\"\n"
-              + "WHERE \"store_id\" = 666";
-          that.query(sql)
-              .explainContains(explain)
-              .planUpdateHasSql(jdbcSql, 1);
-          return null;
-        } catch (SQLException e) {
-          throw new RuntimeException(e);
-        }
+    that.doWithConnection(connection -> {
+      try (LockWrapper ignore = exclusiveCleanDb(connection)) {
+        final String sql = "DELETE FROM \"foodmart\".\"expense_fact\"\n"
+            + "WHERE \"store_id\"=666\n";
+        final String explain = "PLAN=JdbcToEnumerableConverter\n"
+            + "  JdbcTableModify(table=[[foodmart, expense_fact]], operation=[DELETE], flattened=[false])\n"
+            + "    JdbcFilter(condition=[=($0, 666)])\n"
+            + "      JdbcTableScan(table=[[foodmart, expense_fact]]";
+        final String jdbcSql = "DELETE FROM \"foodmart\".\"expense_fact\"\n"
+            + "WHERE \"store_id\" = 666";
+        that.query(sql)
+            .explainContains(explain)
+            .planUpdateHasSql(jdbcSql, 1);
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
       }
     });
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java b/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
index 377c23b..a0a753c 100644
--- a/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
+++ b/core/src/test/java/org/apache/calcite/test/JdbcFrontJdbcBackTest.java
@@ -16,10 +16,6 @@
  */
 package org.apache.calcite.test;
 
-import org.apache.calcite.jdbc.CalciteConnection;
-
-import com.google.common.base.Function;
-
 import org.hamcrest.Matcher;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -56,26 +52,22 @@ public class JdbcFrontJdbcBackTest {
   @Test public void testTables() throws Exception {
     that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try {
-                  ResultSet rset =
-                      a0.getMetaData().getTables(
-                          null, null, null, null);
-                  StringBuilder buf = new StringBuilder();
-                  while (rset.next()) {
-                    buf.append(rset.getString(3)).append(';');
-                  }
-                  assertEquals(
-                      "account;agg_c_10_sales_fact_1997;agg_c_14_sales_fact_1997;agg_c_special_sales_fact_1997;agg_g_ms_pcat_sales_fact_1997;agg_l_03_sales_fact_1997;agg_l_04_sales_fact_1997;agg_l_05_sales_fact_1997;agg_lc_06_sales_fact_1997;agg_lc_100_sales_fact_1997;agg_ll_01_sales_fact_1997;agg_pl_01_sales_fact_1997;category;currency;customer;days;department;employee;employee_closure;expense_fact;inventory_fact_1997;inventory_fact_1998;position;product;product_class;products;promotion;region;reserve_employee;salary;sales_fact_1997;sales_fact_1998;sales_fact_dec_1998;store;store_ragged;time_by_day;warehouse;warehouse_class;COLUMNS;TABLES;",
-                      buf.toString());
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                return null;
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            ResultSet rset =
+                connection.getMetaData().getTables(
+                    null, null, null, null);
+            StringBuilder buf = new StringBuilder();
+            while (rset.next()) {
+              buf.append(rset.getString(3)).append(';');
+            }
+            assertEquals(
+                "account;agg_c_10_sales_fact_1997;agg_c_14_sales_fact_1997;agg_c_special_sales_fact_1997;agg_g_ms_pcat_sales_fact_1997;agg_l_03_sales_fact_1997;agg_l_04_sales_fact_1997;agg_l_05_sales_fact_1997;agg_lc_06_sales_fact_1997;agg_lc_100_sales_fact_1997;agg_ll_01_sales_fact_1997;agg_pl_01_sales_fact_1997;category;currency;customer;days;department;employee;employee_closure;expense_fact;inventory_fact_1997;inventory_fact_1998;position;product;product_class;products;promotion;region;reserve_employee;salary;sales_fact_1997;sales_fact_1998;sales_fact_dec_1998;store;store_ragged;time_by_day;warehouse;warehouse_class;COLUMNS;TABLES;",
+                buf.toString());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testTablesByType() throws Exception {
@@ -89,47 +81,39 @@ public class JdbcFrontJdbcBackTest {
       final Matcher<String> matcher) throws Exception {
     that()
         .with(CalciteAssert.Config.REGULAR_PLUS_METADATA)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try (ResultSet rset = a0.getMetaData().getTables(null, null,
-                    null, new String[] {tableType})) {
-                  StringBuilder buf = new StringBuilder();
-                  while (rset.next()) {
-                    buf.append(rset.getString(3)).append(';');
-                  }
-                  assertThat(buf.toString(), matcher);
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            });
+        .doWithConnection(connection -> {
+          try (ResultSet rset = connection.getMetaData().getTables(null, null,
+              null, new String[] {tableType})) {
+            StringBuilder buf = new StringBuilder();
+            while (rset.next()) {
+              buf.append(rset.getString(3)).append(';');
+            }
+            assertThat(buf.toString(), matcher);
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testColumns() throws Exception {
     that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try {
-                  ResultSet rset =
-                      a0.getMetaData().getColumns(
-                          null, null, "sales_fact_1997", null);
-                  StringBuilder buf = new StringBuilder();
-                  while (rset.next()) {
-                    buf.append(rset.getString(4)).append(';');
-                  }
-                  assertEquals(
-                      "product_id;time_id;customer_id;promotion_id;store_id;store_sales;store_cost;unit_sales;",
-                      buf.toString());
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                return null;
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            ResultSet rset =
+                connection.getMetaData().getColumns(
+                    null, null, "sales_fact_1997", null);
+            StringBuilder buf = new StringBuilder();
+            while (rset.next()) {
+              buf.append(rset.getString(4)).append(';');
+            }
+            assertEquals(
+                "product_id;time_id;customer_id;promotion_id;store_id;store_sales;store_cost;unit_sales;",
+                buf.toString());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   /** Tests a JDBC method known to be not implemented (as it happens,
@@ -138,20 +122,16 @@ public class JdbcFrontJdbcBackTest {
   @Test public void testEmpty() throws Exception {
     that()
         .with(CalciteAssert.Config.JDBC_FOODMART)
-        .doWithConnection(
-            new Function<CalciteConnection, Object>() {
-              public Object apply(CalciteConnection a0) {
-                try {
-                  ResultSet rset =
-                      a0.getMetaData().getPrimaryKeys(
-                          null, null, "sales_fact_1997");
-                  assertFalse(rset.next());
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                return null;
-              }
-            });
+        .doWithConnection(connection -> {
+          try {
+            ResultSet rset =
+                connection.getMetaData().getPrimaryKeys(
+                    null, null, "sales_fact_1997");
+            assertFalse(rset.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testCase() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/test/java/org/apache/calcite/test/JdbcFrontLinqBackTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/JdbcFrontLinqBackTest.java b/core/src/test/java/org/apache/calcite/test/JdbcFrontLinqBackTest.java
index da6facc..a8c86f8 100644
--- a/core/src/test/java/org/apache/calcite/test/JdbcFrontLinqBackTest.java
+++ b/core/src/test/java/org/apache/calcite/test/JdbcFrontLinqBackTest.java
@@ -30,8 +30,6 @@ import org.apache.calcite.schema.Schemas;
 import org.apache.calcite.schema.impl.AbstractSchema;
 import org.apache.calcite.schema.impl.AbstractTableQueryable;
 
-import com.google.common.base.Function;
-
 import org.junit.Ignore;
 import org.junit.Test;
 
@@ -246,24 +244,20 @@ public class JdbcFrontLinqBackTest {
     CalciteAssert.AssertThat with = mutable(employees);
     with.query("select count(*) as c from \"foo\".\"bar\"")
         .returns("C=1\n");
-    with.doWithConnection(
-        new Function<CalciteConnection, Object>() {
-          public Object apply(CalciteConnection c) {
-            try {
-              final String sql = "insert into \"foo\".\"bar\"\n"
-                  + "values (?, 0, ?, 10.0, null)";
-              try (PreparedStatement p = c.prepareStatement(sql)) {
-                p.setInt(1, 1);
-                p.setString(2, "foo");
-                final int count = p.executeUpdate();
-                assertThat(count, is(1));
-              }
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
-          }
-        });
+    with.doWithConnection(c -> {
+      try {
+        final String sql = "insert into \"foo\".\"bar\"\n"
+            + "values (?, 0, ?, 10.0, null)";
+        try (PreparedStatement p = c.prepareStatement(sql)) {
+          p.setInt(1, 1);
+          p.setString(2, "foo");
+          final int count = p.executeUpdate();
+          assertThat(count, is(1));
+        }
+      } catch (SQLException e) {
+        throw new RuntimeException(e);
+      }
+    });
     with.query("select count(*) as c from \"foo\".\"bar\"")
         .returns("C=2\n");
     with.query("select * from \"foo\".\"bar\"")
@@ -305,19 +299,16 @@ public class JdbcFrontLinqBackTest {
    */
   private static CalciteAssert.ConnectionPostProcessor makePostProcessor(
       final List<JdbcTest.Employee> initialData) {
-    return new CalciteAssert.ConnectionPostProcessor() {
-      public Connection apply(final Connection connection)
-          throws SQLException {
-        CalciteConnection calciteConnection =
-            connection.unwrap(CalciteConnection.class);
-        SchemaPlus rootSchema = calciteConnection.getRootSchema();
-        SchemaPlus mapSchema = rootSchema.add("foo", new AbstractSchema());
-        final String tableName = "bar";
-        final JdbcTest.AbstractModifiableTable table =
-            mutable(tableName, initialData);
-        mapSchema.add(tableName, table);
-        return calciteConnection;
-      }
+    return connection -> {
+      CalciteConnection calciteConnection =
+          connection.unwrap(CalciteConnection.class);
+      SchemaPlus rootSchema = calciteConnection.getRootSchema();
+      SchemaPlus mapSchema = rootSchema.add("foo", new AbstractSchema());
+      final String tableName = "bar";
+      final JdbcTest.AbstractModifiableTable table =
+          mutable(tableName, initialData);
+      mapSchema.add(tableName, table);
+      return calciteConnection;
     };
   }
 


[28/30] calcite git commit: [CALCITE-2396] Allow NULL intervals in TIMESTAMPADD and DATETIME_PLUS functions (James Duong)

Posted by jh...@apache.org.
[CALCITE-2396] Allow NULL intervals in TIMESTAMPADD and DATETIME_PLUS functions (James Duong)

Fix bug where NULL can be used as an interval for these operators only
for specific time units.

Add a fluent API for testing validation of SQL expressions. (Julian Hyde)

Close apache/calcite#2396


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/cf3eca29
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/cf3eca29
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/cf3eca29

Branch: refs/heads/master
Commit: cf3eca294bedb5e268752cb54056700541177c99
Parents: 606240d
Author: James Duong <jd...@dremio.com>
Authored: Tue Jul 3 15:44:01 2018 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:41:09 2018 -0700

----------------------------------------------------------------------
 .../sql/fun/SqlTimestampAddFunction.java        | 11 +++++----
 .../apache/calcite/test/SqlValidatorTest.java   | 25 ++++++++++++++++++++
 .../calcite/test/SqlValidatorTestCase.java      | 22 ++++++++++++-----
 3 files changed, 47 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/cf3eca29/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
index 6dc7dba..a9bf004 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
@@ -68,13 +68,13 @@ public class SqlTimestampAddFunction extends SqlFunction {
 
   public static RelDataType deduceType(RelDataTypeFactory typeFactory,
       TimeUnit timeUnit, RelDataType operandType1, RelDataType operandType2) {
+    final RelDataType type;
     switch (timeUnit) {
     case HOUR:
     case MINUTE:
     case SECOND:
     case MILLISECOND:
     case MICROSECOND:
-      final RelDataType type;
       switch (timeUnit) {
       case MILLISECOND:
         type = typeFactory.createSqlType(SqlTypeName.TIMESTAMP,
@@ -87,12 +87,13 @@ public class SqlTimestampAddFunction extends SqlFunction {
       default:
         type = typeFactory.createSqlType(SqlTypeName.TIMESTAMP);
       }
-      return typeFactory.createTypeWithNullability(type,
-          operandType1.isNullable()
-              || operandType2.isNullable());
+      break;
     default:
-      return operandType2;
+      type = operandType2;
     }
+    return typeFactory.createTypeWithNullability(type,
+        operandType1.isNullable()
+            || operandType2.isNullable());
   }
 
   /** Creates a SqlTimestampAddFunction. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/cf3eca29/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
index d1f0ee6..e96f1d2 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
@@ -3490,6 +3490,22 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
             + " INTERVAL SECOND\\(1, 0\\)");
   }
 
+  @Test public void testDatetimePlusNullInterval() {
+    expr("TIME '8:8:8' + cast(NULL AS interval hour)").columnType("TIME(0)");
+    expr("TIME '8:8:8' + cast(NULL AS interval YEAR)").columnType("TIME(0)");
+    expr("TIMESTAMP '1990-12-12 12:12:12' + cast(NULL AS interval hour)")
+        .columnType("TIMESTAMP(0)");
+    expr("TIMESTAMP '1990-12-12 12:12:12' + cast(NULL AS interval YEAR)")
+        .columnType("TIMESTAMP(0)");
+
+    expr("cast(NULL AS interval hour) + TIME '8:8:8'").columnType("TIME(0)");
+    expr("cast(NULL AS interval YEAR) + TIME '8:8:8'").columnType("TIME(0)");
+    expr("cast(NULL AS interval hour) + TIMESTAMP '1990-12-12 12:12:12'")
+        .columnType("TIMESTAMP(0)");
+    expr("cast(NULL AS interval YEAR) + TIMESTAMP '1990-12-12 12:12:12'")
+        .columnType("TIMESTAMP(0)");
+  }
+
   @Test public void testIntervalLiterals() {
     // First check that min, max, and defaults are what we expect
     // (values used in subtests depend on these being true to
@@ -3682,6 +3698,15 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
         "(?s).*Was expecting one of.*");
   }
 
+  @Test public void testTimestampAddNullInterval() {
+    expr("timestampadd(SQL_TSI_SECOND, cast(NULL AS INTEGER),"
+        + " current_timestamp)")
+        .columnType("TIMESTAMP(0)");
+    expr("timestampadd(SQL_TSI_DAY, cast(NULL AS INTEGER),"
+        + " current_timestamp)")
+        .columnType("TIMESTAMP(0)");
+  }
+
   @Test public void testNumericOperators() {
     // unary operator
     checkExpType("- cast(1 as TINYINT)", "TINYINT NOT NULL");

http://git-wip-us.apache.org/repos/asf/calcite/blob/cf3eca29/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
index 7e983dd..f09009c 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTestCase.java
@@ -107,7 +107,11 @@ public class SqlValidatorTestCase {
   }
 
   public final Sql sql(String sql) {
-    return new Sql(tester, sql);
+    return new Sql(tester, sql, true);
+  }
+
+  public final Sql expr(String sql) {
+    return new Sql(tester, sql, false);
   }
 
   public final Sql winSql(String sql) {
@@ -559,17 +563,23 @@ public class SqlValidatorTestCase {
     private final SqlTester tester;
     private final String sql;
 
-    Sql(SqlTester tester, String sql) {
+    /** Creates a Sql.
+     *
+     * @param tester Tester
+     * @param sql SQL query or expression
+     * @param query True if {@code sql} is a query, false if it is an expression
+     */
+    Sql(SqlTester tester, String sql, boolean query) {
       this.tester = tester;
-      this.sql = sql;
+      this.sql = query ? sql : SqlTesterImpl.buildQuery(sql);
     }
 
     Sql tester(SqlTester tester) {
-      return new Sql(tester, sql);
+      return new Sql(tester, sql, true);
     }
 
     public Sql sql(String sql) {
-      return new Sql(tester, sql);
+      return new Sql(tester, sql, true);
     }
 
     Sql withExtendedCatalog() {
@@ -629,7 +639,7 @@ public class SqlValidatorTestCase {
      * a test once at a conformance level where it fails, then run it again
      * at a conformance level where it succeeds. */
     public Sql sansCarets() {
-      return new Sql(tester, sql.replace("^", ""));
+      return new Sql(tester, sql.replace("^", ""), true);
     }
   }
 }


[25/30] calcite git commit: [CALCITE-2304] In Babel parser, allow Hive-style syntax "LEFT SEMI JOIN"

Posted by jh...@apache.org.
[CALCITE-2304] In Babel parser, allow Hive-style syntax "LEFT SEMI JOIN"


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/870e54fa
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/870e54fa
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/870e54fa

Branch: refs/heads/master
Commit: 870e54facba01b7c3cbeb7c5386ebc0787ed50aa
Parents: 3e50a53
Author: Julian Hyde <jh...@apache.org>
Authored: Tue May 8 10:23:10 2018 -0700
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jul 8 22:41:08 2018 -0700

----------------------------------------------------------------------
 babel/src/main/codegen/config.fmpp                          | 6 ++++++
 babel/src/main/codegen/includes/parserImpls.ftl             | 7 +++++++
 babel/src/test/resources/sql/select.iq                      | 9 +++++++++
 core/src/main/codegen/config.fmpp                           | 5 +++++
 core/src/main/codegen/templates/Parser.jj                   | 4 ++++
 core/src/main/java/org/apache/calcite/sql/JoinType.java     | 7 +++++++
 core/src/main/java/org/apache/calcite/sql/SqlJoin.java      | 3 +++
 .../org/apache/calcite/sql/validate/SqlValidatorImpl.java   | 6 ++++++
 core/src/test/codegen/config.fmpp                           | 5 +++++
 server/src/main/codegen/config.fmpp                         | 5 +++++
 10 files changed, 57 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/babel/src/main/codegen/config.fmpp
----------------------------------------------------------------------
diff --git a/babel/src/main/codegen/config.fmpp b/babel/src/main/codegen/config.fmpp
index 57bbe86..57b6419 100644
--- a/babel/src/main/codegen/config.fmpp
+++ b/babel/src/main/codegen/config.fmpp
@@ -33,6 +33,12 @@ data: {
         "SEMI"
       ]
 
+      # List of additional join types. Each is a method with no arguments.
+      # Example: LeftSemiJoin()
+      joinTypes: [
+        "LeftSemiJoin"
+      ]
+
       # List of methods for parsing custom SQL statements.
       statementParserMethods: [
       ]

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/babel/src/main/codegen/includes/parserImpls.ftl
----------------------------------------------------------------------
diff --git a/babel/src/main/codegen/includes/parserImpls.ftl b/babel/src/main/codegen/includes/parserImpls.ftl
index 627a634..09b5d3d 100644
--- a/babel/src/main/codegen/includes/parserImpls.ftl
+++ b/babel/src/main/codegen/includes/parserImpls.ftl
@@ -15,4 +15,11 @@
 // limitations under the License.
 -->
 
+JoinType LeftSemiJoin() :
+{
+}
+{
+    <LEFT> <SEMI> <JOIN> { return JoinType.LEFT_SEMI_JOIN; }
+}
+
 // End parserImpls.ftl

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/babel/src/test/resources/sql/select.iq
----------------------------------------------------------------------
diff --git a/babel/src/test/resources/sql/select.iq b/babel/src/test/resources/sql/select.iq
index ef692dc..d429c6c 100755
--- a/babel/src/test/resources/sql/select.iq
+++ b/babel/src/test/resources/sql/select.iq
@@ -29,6 +29,15 @@ FROM "scott"."EMP" AS "EMP",
 ORDER BY "EMP"."DEPTNO"
 !explain-validated-on all
 
+# LEFT SEMI JOIN (Hive only)
+SELECT *
+FROM emp LEFT SEMI JOIN dept ON emp.deptno = dept.deptno;
+
+SELECT "EMP"."EMPNO", "EMP"."ENAME", "EMP"."JOB", "EMP"."MGR", "EMP"."HIREDATE", "EMP"."SAL", "EMP"."COMM", "EMP"."DEPTNO", "DEPT"."DEPTNO" AS "DEPTNO0", "DEPT"."DNAME", "DEPT"."LOC"
+FROM "scott"."EMP" AS "EMP"
+    LEFT SEMI JOIN "scott"."DEPT" AS "DEPT" ON "EMP"."DEPTNO" = "DEPT"."DEPTNO"
+!explain-validated-on hive
+
 # Test CONNECT BY (Oracle only)
 !if (false) {
 SELECT *

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/core/src/main/codegen/config.fmpp
----------------------------------------------------------------------
diff --git a/core/src/main/codegen/config.fmpp b/core/src/main/codegen/config.fmpp
index 41cfeee..2cec0c8 100644
--- a/core/src/main/codegen/config.fmpp
+++ b/core/src/main/codegen/config.fmpp
@@ -52,6 +52,11 @@ data: {
     nonReservedKeywords: [
     ]
 
+    # List of additional join types. Each is a method with no arguments.
+    # Example: LeftSemiJoin()
+    joinTypes: [
+    ]
+
     # List of methods for parsing custom SQL statements.
     # Return type of method implementation should be 'SqlNode'.
     # Example: SqlShowDatabases(), SqlShowTables().

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/core/src/main/codegen/templates/Parser.jj
----------------------------------------------------------------------
diff --git a/core/src/main/codegen/templates/Parser.jj b/core/src/main/codegen/templates/Parser.jj
index 4096cfe..7fda2bc 100644
--- a/core/src/main/codegen/templates/Parser.jj
+++ b/core/src/main/codegen/templates/Parser.jj
@@ -1614,6 +1614,10 @@ SqlLiteral JoinType() :
         <FULL> [ <OUTER> ] <JOIN> { joinType = JoinType.FULL; }
     |
         <CROSS> <JOIN> { joinType = JoinType.CROSS; }
+<#list parser.joinTypes as method>
+    |
+        joinType = ${method}()
+</#list>
     )
     {
         return joinType.symbol(getPos());

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/core/src/main/java/org/apache/calcite/sql/JoinType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/JoinType.java b/core/src/main/java/org/apache/calcite/sql/JoinType.java
index acbff50..3ee64d4 100644
--- a/core/src/main/java/org/apache/calcite/sql/JoinType.java
+++ b/core/src/main/java/org/apache/calcite/sql/JoinType.java
@@ -50,6 +50,13 @@ public enum JoinType {
   RIGHT,
 
   /**
+   * Left semi join.
+   *
+   * <p>Not used by Calcite; only in Babel's Hive dialect.
+   */
+  LEFT_SEMI_JOIN,
+
+  /**
    * Comma join: the good old-fashioned SQL <code>FROM</code> clause,
    * where table expressions are specified with commas between them, and
    * join conditions are specified in the <code>WHERE</code> clause.

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlJoin.java b/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
index e533ee9..bf97c25 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlJoin.java
@@ -222,6 +222,9 @@ public class SqlJoin extends SqlCall {
       case LEFT:
         writer.sep(natural + "LEFT JOIN");
         break;
+      case LEFT_SEMI_JOIN:
+        writer.sep(natural + "LEFT SEMI JOIN");
+        break;
       case RIGHT:
         writer.sep(natural + "RIGHT JOIN");
         break;

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
index 71b4b76..2d14bd5 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
@@ -3133,6 +3133,12 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     // Which join types require/allow a ON/USING condition, or allow
     // a NATURAL keyword?
     switch (joinType) {
+    case LEFT_SEMI_JOIN:
+      if (!conformance.isLiberal()) {
+        throw newValidationError(join.getJoinTypeNode(),
+            RESOURCE.dialectDoesNotSupportFeature("LEFT SEMI JOIN"));
+      }
+      // fall through
     case INNER:
     case LEFT:
     case RIGHT:

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/core/src/test/codegen/config.fmpp
----------------------------------------------------------------------
diff --git a/core/src/test/codegen/config.fmpp b/core/src/test/codegen/config.fmpp
index 2f747e2..7833ee2 100644
--- a/core/src/test/codegen/config.fmpp
+++ b/core/src/test/codegen/config.fmpp
@@ -36,6 +36,11 @@ data: {
       nonReservedKeywords: [
       ]
 
+      # List of additional join types. Each is a method with no arguments.
+      # Example: LeftSemiJoin()
+      joinTypes: [
+      ]
+
       # List of methods for parsing custom SQL statements.
       statementParserMethods: [
         "SqlDescribeSpacePower()"

http://git-wip-us.apache.org/repos/asf/calcite/blob/870e54fa/server/src/main/codegen/config.fmpp
----------------------------------------------------------------------
diff --git a/server/src/main/codegen/config.fmpp b/server/src/main/codegen/config.fmpp
index 34fe90c..00a32ca 100644
--- a/server/src/main/codegen/config.fmpp
+++ b/server/src/main/codegen/config.fmpp
@@ -43,6 +43,11 @@ data: {
         "VIRTUAL"
       ]
 
+      # List of additional join types. Each is a method with no arguments.
+      # Example: LeftSemiJoin()
+      joinTypes: [
+      ]
+
       # List of methods for parsing custom SQL statements.
       statementParserMethods: [
       ]


[15/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlMatchRecognize.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlMatchRecognize.java b/core/src/main/java/org/apache/calcite/sql/SqlMatchRecognize.java
index b797ef9..dbf6389 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlMatchRecognize.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlMatchRecognize.java
@@ -26,6 +26,7 @@ import org.apache.calcite.util.ImmutableNullableList;
 import com.google.common.base.Preconditions;
 
 import java.util.List;
+import java.util.Objects;
 import javax.annotation.Nonnull;
 
 /**
@@ -75,20 +76,20 @@ public class SqlMatchRecognize extends SqlCall {
       SqlLiteral rowsPerMatch, SqlNodeList partitionList,
       SqlNodeList orderList, SqlLiteral interval) {
     super(pos);
-    this.tableRef = Preconditions.checkNotNull(tableRef);
-    this.pattern = Preconditions.checkNotNull(pattern);
+    this.tableRef = Objects.requireNonNull(tableRef);
+    this.pattern = Objects.requireNonNull(pattern);
     this.strictStart = strictStart;
     this.strictEnd = strictEnd;
-    this.patternDefList = Preconditions.checkNotNull(patternDefList);
+    this.patternDefList = Objects.requireNonNull(patternDefList);
     Preconditions.checkArgument(patternDefList.size() > 0);
-    this.measureList = Preconditions.checkNotNull(measureList);
+    this.measureList = Objects.requireNonNull(measureList);
     this.after = after;
     this.subsetList = subsetList;
     Preconditions.checkArgument(rowsPerMatch == null
         || rowsPerMatch.value instanceof RowsPerMatchOption);
     this.rowsPerMatch = rowsPerMatch;
-    this.partitionList = Preconditions.checkNotNull(partitionList);
-    this.orderList = Preconditions.checkNotNull(orderList);
+    this.partitionList = Objects.requireNonNull(partitionList);
+    this.orderList = Objects.requireNonNull(orderList);
     this.interval = interval;
   }
 
@@ -119,7 +120,7 @@ public class SqlMatchRecognize extends SqlCall {
   @Override public void setOperand(int i, SqlNode operand) {
     switch (i) {
     case OPERAND_TABLE_REF:
-      tableRef = Preconditions.checkNotNull(operand);
+      tableRef = Objects.requireNonNull(operand);
       break;
     case OPERAND_PATTERN:
       pattern = operand;
@@ -131,11 +132,11 @@ public class SqlMatchRecognize extends SqlCall {
       strictEnd = (SqlLiteral) operand;
       break;
     case OPERAND_PATTERN_DEFINES:
-      patternDefList = Preconditions.checkNotNull((SqlNodeList) operand);
+      patternDefList = Objects.requireNonNull((SqlNodeList) operand);
       Preconditions.checkArgument(patternDefList.size() > 0);
       break;
     case OPERAND_MEASURES:
-      measureList = Preconditions.checkNotNull((SqlNodeList) operand);
+      measureList = Objects.requireNonNull((SqlNodeList) operand);
       break;
     case OPERAND_AFTER:
       after = operand;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlNode.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlNode.java b/core/src/main/java/org/apache/calcite/sql/SqlNode.java
index 97080ab..c6d7d0b 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlNode.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlNode.java
@@ -28,10 +28,9 @@ import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-
 import java.util.Collection;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -58,7 +57,7 @@ public abstract class SqlNode implements Cloneable {
    * @param pos Parser position, must not be null.
    */
   SqlNode(SqlParserPos pos) {
-    this.pos = Preconditions.checkNotNull(pos);
+    this.pos = Objects.requireNonNull(pos);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlNodeList.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlNodeList.java b/core/src/main/java/org/apache/calcite/sql/SqlNodeList.java
index b538013..2367afa 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlNodeList.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlNodeList.java
@@ -172,7 +172,7 @@ public class SqlNodeList extends SqlNode implements Iterable<SqlNode> {
   }
 
   public SqlNode[] toArray() {
-    return list.toArray(new SqlNode[list.size()]);
+    return list.toArray(new SqlNode[0]);
   }
 
   public static boolean isEmptyList(final SqlNode node) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
index c979c01..c4c092e 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
@@ -296,7 +296,7 @@ public abstract class SqlOperator {
     return createCall(
         null,
         pos,
-        operandList.toArray(new SqlNode[operandList.size()]));
+        operandList.toArray(new SqlNode[0]));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlSelect.java b/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
index 61b0157..ad7d6ef 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlSelect.java
@@ -21,9 +21,8 @@ import org.apache.calcite.sql.validate.SqlValidator;
 import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.ImmutableNullableList;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 import javax.annotation.Nonnull;
 
 /**
@@ -65,14 +64,14 @@ public class SqlSelect extends SqlCall {
       SqlNode offset,
       SqlNode fetch) {
     super(pos);
-    this.keywordList = Preconditions.checkNotNull(keywordList != null
+    this.keywordList = Objects.requireNonNull(keywordList != null
         ? keywordList : new SqlNodeList(pos));
     this.selectList = selectList;
     this.from = from;
     this.where = where;
     this.groupBy = groupBy;
     this.having = having;
-    this.windowDecls = Preconditions.checkNotNull(windowDecls != null
+    this.windowDecls = Objects.requireNonNull(windowDecls != null
         ? windowDecls : new SqlNodeList(pos));
     this.orderBy = orderBy;
     this.offset = offset;
@@ -97,7 +96,7 @@ public class SqlSelect extends SqlCall {
   @Override public void setOperand(int i, SqlNode operand) {
     switch (i) {
     case 0:
-      keywordList = Preconditions.checkNotNull((SqlNodeList) operand);
+      keywordList = Objects.requireNonNull((SqlNodeList) operand);
       break;
     case 1:
       selectList = (SqlNodeList) operand;
@@ -115,7 +114,7 @@ public class SqlSelect extends SqlCall {
       having = operand;
       break;
     case 6:
-      windowDecls = Preconditions.checkNotNull((SqlNodeList) operand);
+      windowDecls = Objects.requireNonNull((SqlNodeList) operand);
       break;
     case 7:
       orderBy = (SqlNodeList) operand;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlSetOption.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlSetOption.java b/core/src/main/java/org/apache/calcite/sql/SqlSetOption.java
index 8538ffc..2cfe894 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlSetOption.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlSetOption.java
@@ -21,8 +21,7 @@ import org.apache.calcite.sql.validate.SqlValidator;
 import org.apache.calcite.sql.validate.SqlValidatorScope;
 import org.apache.calcite.util.ImmutableNullableList;
 
-import com.google.common.collect.Lists;
-
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -107,7 +106,7 @@ public class SqlSetOption extends SqlAlter {
   }
 
   @Override public List<SqlNode> getOperandList() {
-    final List<SqlNode> operandList = Lists.newArrayList();
+    final List<SqlNode> operandList = new ArrayList<>();
     if (scope == null) {
       operandList.add(null);
     } else {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlSpecialOperator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlSpecialOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlSpecialOperator.java
index 83049ac..9587c2a 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlSpecialOperator.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlSpecialOperator.java
@@ -23,7 +23,7 @@ import org.apache.calcite.sql.type.SqlReturnTypeInference;
 import org.apache.calcite.util.PrecedenceClimbingParser;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Predicate;
+import java.util.function.Predicate;
 
 /**
  * Generic operator for nodes with special syntax.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/SqlUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlUtil.java b/core/src/main/java/org/apache/calcite/sql/SqlUtil.java
index ae3f144..52ba9a4 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlUtil.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlUtil.java
@@ -17,14 +17,12 @@
 package org.apache.calcite.sql;
 
 import org.apache.calcite.linq4j.Ord;
-import org.apache.calcite.linq4j.function.Function1;
 import org.apache.calcite.linq4j.function.Functions;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypePrecedenceList;
 import org.apache.calcite.runtime.CalciteContextException;
 import org.apache.calcite.runtime.CalciteException;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.runtime.Resources;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.parser.SqlParserPos;
@@ -39,10 +37,8 @@ import org.apache.calcite.util.NlsString;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Predicate;
 import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
 import com.google.common.collect.Iterators;
 import com.google.common.collect.Lists;
 
@@ -56,6 +52,9 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -71,7 +70,7 @@ public abstract class SqlUtil {
     if (node1 == null) {
       return node2;
     }
-    ArrayList<SqlNode> list = new ArrayList<SqlNode>();
+    ArrayList<SqlNode> list = new ArrayList<>();
     if (node1.getKind() == SqlKind.AND) {
       list.addAll(((SqlCall) node1).getOperandList());
     } else {
@@ -88,7 +87,7 @@ public abstract class SqlUtil {
   }
 
   static ArrayList<SqlNode> flatten(SqlNode node) {
-    ArrayList<SqlNode> list = new ArrayList<SqlNode>();
+    ArrayList<SqlNode> list = new ArrayList<>();
     flatten(node, list);
     return list;
   }
@@ -386,11 +385,7 @@ public abstract class SqlUtil {
   private static Iterator<SqlOperator> filterOperatorRoutinesByKind(
       Iterator<SqlOperator> routines, final SqlKind sqlKind) {
     return Iterators.filter(routines,
-        new PredicateImpl<SqlOperator>() {
-          public boolean test(SqlOperator input) {
-            return input.getKind() == sqlKind;
-          }
-        });
+        operator -> Objects.requireNonNull(operator).getKind() == sqlKind);
   }
 
   /**
@@ -489,11 +484,7 @@ public abstract class SqlUtil {
           Predicates.instanceOf(SqlFunction.class));
     default:
       return Iterators.filter(sqlOperators.iterator(),
-          new PredicateImpl<SqlOperator>() {
-            public boolean test(SqlOperator operator) {
-              return operator.getSyntax() == syntax;
-            }
-          });
+          operator -> Objects.requireNonNull(operator).getSyntax() == syntax);
     }
   }
 
@@ -501,12 +492,8 @@ public abstract class SqlUtil {
       Iterator<SqlOperator> routines,
       final List<RelDataType> argTypes) {
     return Iterators.filter(routines,
-        new PredicateImpl<SqlOperator>() {
-          public boolean test(SqlOperator operator) {
-            SqlOperandCountRange od = operator.getOperandCountRange();
-            return od.isValidCount(argTypes.size());
-          }
-        });
+        operator -> Objects.requireNonNull(operator)
+            .getOperandCountRange().isValidCount(argTypes.size()));
   }
 
   /**
@@ -523,52 +510,48 @@ public abstract class SqlUtil {
     //noinspection unchecked
     return (Iterator) Iterators.filter(
         Iterators.filter(routines, SqlFunction.class),
-        new PredicateImpl<SqlFunction>() {
-          public boolean test(SqlFunction function) {
-            List<RelDataType> paramTypes = function.getParamTypes();
-            if (paramTypes == null) {
-              // no parameter information for builtins; keep for now
-              return true;
-            }
-            final List<RelDataType> permutedArgTypes;
-            if (argNames != null) {
-              // Arguments passed by name. Make sure that the function has
-              // parameters of all of these names.
-              final Map<Integer, Integer> map = new HashMap<>();
-              for (Ord<String> argName : Ord.zip(argNames)) {
-                final int i = function.getParamNames().indexOf(argName.e);
-                if (i < 0) {
-                  return false;
-                }
-                map.put(i, argName.i);
-              }
-              permutedArgTypes = Functions.generate(paramTypes.size(),
-                  new Function1<Integer, RelDataType>() {
-                    public RelDataType apply(Integer a0) {
-                      if (map.containsKey(a0)) {
-                        return argTypes.get(map.get(a0));
-                      } else {
-                        return null;
-                      }
-                    }
-                  });
-            } else {
-              permutedArgTypes = Lists.newArrayList(argTypes);
-              while (permutedArgTypes.size() < argTypes.size()) {
-                paramTypes.add(null);
+        function -> {
+          List<RelDataType> paramTypes =
+              Objects.requireNonNull(function).getParamTypes();
+          if (paramTypes == null) {
+            // no parameter information for builtins; keep for now
+            return true;
+          }
+          final List<RelDataType> permutedArgTypes;
+          if (argNames != null) {
+            // Arguments passed by name. Make sure that the function has
+            // parameters of all of these names.
+            final Map<Integer, Integer> map = new HashMap<>();
+            for (Ord<String> argName : Ord.zip(argNames)) {
+              final int i = function.getParamNames().indexOf(argName.e);
+              if (i < 0) {
+                return false;
               }
+              map.put(i, argName.i);
             }
-            for (Pair<RelDataType, RelDataType> p
-                : Pair.zip(paramTypes, permutedArgTypes)) {
-              final RelDataType argType = p.right;
-              final RelDataType paramType = p.left;
-              if (argType != null
-                  && !SqlTypeUtil.canCastFrom(paramType, argType, false)) {
-                return false;
+            permutedArgTypes = Functions.generate(paramTypes.size(), a0 -> {
+              if (map.containsKey(a0)) {
+                return argTypes.get(map.get(a0));
+              } else {
+                return null;
               }
+            });
+          } else {
+            permutedArgTypes = Lists.newArrayList(argTypes);
+            while (permutedArgTypes.size() < argTypes.size()) {
+              paramTypes.add(null);
+            }
+          }
+          for (Pair<RelDataType, RelDataType> p
+              : Pair.zip(paramTypes, permutedArgTypes)) {
+            final RelDataType argType = p.right;
+            final RelDataType paramType = p.left;
+            if (argType != null
+                && !SqlTypeUtil.canCastFrom(paramType, argType, false)) {
+              return false;
             }
-            return true;
           }
+          return true;
         });
   }
 
@@ -591,19 +574,16 @@ public abstract class SqlUtil {
           argType.e.getPrecedenceList();
       final RelDataType bestMatch = bestMatch(sqlFunctions, argType.i, precList);
       if (bestMatch != null) {
-        sqlFunctions =
-            Lists.newArrayList(
-                Iterables.filter(sqlFunctions,
-                    new PredicateImpl<SqlFunction>() {
-                      public boolean test(SqlFunction function) {
-                        final List<RelDataType> paramTypes = function.getParamTypes();
-                        if (paramTypes == null) {
-                          return false;
-                        }
-                        final RelDataType paramType = paramTypes.get(argType.i);
-                        return precList.compareTypePrecedence(paramType, bestMatch) >= 0;
-                      }
-                    }));
+        sqlFunctions = sqlFunctions.stream()
+            .filter(function -> {
+              final List<RelDataType> paramTypes = function.getParamTypes();
+              if (paramTypes == null) {
+                return false;
+              }
+              final RelDataType paramType = paramTypes.get(argType.i);
+              return precList.compareTypePrecedence(paramType, bestMatch) >= 0;
+            })
+            .collect(Collectors.toList());
       }
     }
     //noinspection unchecked
@@ -680,7 +660,7 @@ public abstract class SqlUtil {
       SqlOperatorTable opTab,
       SqlIdentifier id) {
     if (id.names.size() == 1) {
-      final List<SqlOperator> list = Lists.newArrayList();
+      final List<SqlOperator> list = new ArrayList<>();
       opTab.lookupOperatorOverloads(id, null, SqlSyntax.FUNCTION, list);
       for (SqlOperator operator : list) {
         if (operator.getSyntax() == SqlSyntax.FUNCTION_ID) {
@@ -928,7 +908,7 @@ public abstract class SqlUtil {
   /** Walks over a {@link org.apache.calcite.sql.SqlNode} tree and returns the
    * ancestry stack when it finds a given node. */
   private static class Genealogist extends SqlBasicVisitor<Void> {
-    private final List<SqlNode> ancestors = Lists.newArrayList();
+    private final List<SqlNode> ancestors = new ArrayList<>();
     private final Predicate<SqlNode> predicate;
     private final Predicate<SqlNode> postPredicate;
 
@@ -945,14 +925,14 @@ public abstract class SqlUtil {
     }
 
     private Void preCheck(SqlNode node) {
-      if (predicate.apply(node)) {
+      if (predicate.test(node)) {
         throw new Util.FoundOne(ImmutableList.copyOf(ancestors));
       }
       return null;
     }
 
     private Void postCheck(SqlNode node) {
-      if (postPredicate.apply(node)) {
+      if (postPredicate.test(node)) {
         throw new Util.FoundOne(ImmutableList.copyOf(ancestors));
       }
       return null;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisor.java b/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisor.java
index 0216cc3..5395fac 100644
--- a/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisor.java
+++ b/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisor.java
@@ -18,7 +18,6 @@ package org.apache.calcite.sql.advise;
 
 import org.apache.calcite.runtime.CalciteContextException;
 import org.apache.calcite.runtime.CalciteException;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlSelect;
@@ -45,6 +44,7 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Locale;
+import java.util.Objects;
 
 /**
  * An assistant which offers hints and corrections to a partially-formed SQL
@@ -240,18 +240,11 @@ public class SqlAdvisor {
   private static boolean isSelectListItem(SqlNode root,
       final SqlParserPos pos) {
     List<SqlNode> nodes = SqlUtil.getAncestry(root,
-        new PredicateImpl<SqlNode>() {
-          public boolean test(SqlNode input) {
-            return input instanceof SqlIdentifier
-                && Util.last(((SqlIdentifier) input).names)
-                    .equals(UPPER_HINT_TOKEN);
-          }
-        },
-        new PredicateImpl<SqlNode>() {
-          public boolean test(SqlNode input) {
-            return input.getParserPosition().startsAt(pos);
-          }
-        });
+        input -> input instanceof SqlIdentifier
+            && Util.last(((SqlIdentifier) input).names)
+                .equals(UPPER_HINT_TOKEN),
+        input -> Objects.requireNonNull(input).getParserPosition()
+            .startsAt(pos));
     assert nodes.get(0) == root;
     nodes = Lists.reverse(nodes);
     return nodes.size() > 2

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorGetHintsFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorGetHintsFunction.java b/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorGetHintsFunction.java
index da8d28e..155228d 100644
--- a/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorGetHintsFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorGetHintsFunction.java
@@ -18,10 +18,8 @@ package org.apache.calcite.sql.advise;
 
 import org.apache.calcite.DataContext;
 import org.apache.calcite.adapter.enumerable.CallImplementor;
-import org.apache.calcite.adapter.enumerable.NotNullImplementor;
 import org.apache.calcite.adapter.enumerable.NullPolicy;
 import org.apache.calcite.adapter.enumerable.RexImpTable;
-import org.apache.calcite.adapter.enumerable.RexToLixTranslator;
 import org.apache.calcite.linq4j.Enumerable;
 import org.apache.calcite.linq4j.Linq4j;
 import org.apache.calcite.linq4j.tree.Expression;
@@ -29,7 +27,6 @@ import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.Types;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
-import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.schema.FunctionParameter;
 import org.apache.calcite.schema.ImplementableFunction;
 import org.apache.calcite.schema.TableFunction;
@@ -63,13 +60,10 @@ public class SqlAdvisorGetHintsFunction
 
   private static final CallImplementor IMPLEMENTOR =
       RexImpTable.createImplementor(
-          new NotNullImplementor() {
-            public Expression implement(RexToLixTranslator translator,
-                RexCall call, List<Expression> operands) {
-              return Expressions.call(GET_COMPLETION_HINTS,
-                  Iterables.concat(Collections.singleton(ADVISOR), operands));
-            }
-          }, NullPolicy.ANY, false);
+          (translator, call, operands) ->
+              Expressions.call(GET_COMPLETION_HINTS,
+                  Iterables.concat(Collections.singleton(ADVISOR), operands)),
+          NullPolicy.ANY, false);
 
   private static final List<FunctionParameter> PARAMETERS =
       ReflectiveFunctionBase.builder()

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorHint.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorHint.java b/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorHint.java
index 95bb404..915550a 100644
--- a/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorHint.java
+++ b/core/src/main/java/org/apache/calcite/sql/advise/SqlAdvisorHint.java
@@ -43,7 +43,7 @@ public class SqlAdvisorHint {
     final List<String> names = id.getFullyQualifiedNames();
     this.names = names == null
       ? null
-      : names.toArray(new String[names.size()]);
+      : names.toArray(new String[0]);
     type = id.getType().name();
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/dialect/JethroDataSqlDialect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/dialect/JethroDataSqlDialect.java b/core/src/main/java/org/apache/calcite/sql/dialect/JethroDataSqlDialect.java
index 26f0148..f945379 100644
--- a/core/src/main/java/org/apache/calcite/sql/dialect/JethroDataSqlDialect.java
+++ b/core/src/main/java/org/apache/calcite/sql/dialect/JethroDataSqlDialect.java
@@ -23,8 +23,6 @@ import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.type.SqlTypeName;
 
-import com.google.common.base.Preconditions;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSetMultimap;
 import com.google.common.collect.LinkedHashMultimap;
@@ -38,9 +36,9 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
-
 /**
  * A <code>SqlDialect</code> implementation for the JethroData database.
  */
@@ -126,7 +124,7 @@ public class JethroDataSqlDialect extends SqlDialect {
     private final List<SqlTypeName> operandTypes;
 
     JethroSupportedFunction(String name, String operands) {
-      Preconditions.checkNotNull(name); // not currently used
+      Objects.requireNonNull(name); // not currently used
       final ImmutableList.Builder<SqlTypeName> b = ImmutableList.builder();
       for (String strType : operands.split(":")) {
         b.add(parse(strType));
@@ -222,7 +220,7 @@ public class JethroDataSqlDialect extends SqlDialect {
   /** Information about the capabilities of a Jethro database. */
   public static class JethroInfo {
     public static final JethroInfo EMPTY = new JethroInfo(
-        ImmutableSetMultimap.<String, JethroSupportedFunction>of());
+        ImmutableSetMultimap.of());
 
     private final ImmutableSetMultimap<String, JethroSupportedFunction> supportedFunctions;
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/dialect/MssqlSqlDialect.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/dialect/MssqlSqlDialect.java b/core/src/main/java/org/apache/calcite/sql/dialect/MssqlSqlDialect.java
index 22881de..6261481 100644
--- a/core/src/main/java/org/apache/calcite/sql/dialect/MssqlSqlDialect.java
+++ b/core/src/main/java/org/apache/calcite/sql/dialect/MssqlSqlDialect.java
@@ -33,8 +33,6 @@ import org.apache.calcite.sql.SqlWriter;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.type.ReturnTypes;
 
-
-
 /**
  * A <code>SqlDialect</code> implementation for the Microsoft SQL Server
  * database.

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/fun/OracleSqlOperatorTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/OracleSqlOperatorTable.java b/core/src/main/java/org/apache/calcite/sql/fun/OracleSqlOperatorTable.java
index a4a3175..f88d95d 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/OracleSqlOperatorTable.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/OracleSqlOperatorTable.java
@@ -21,7 +21,6 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.sql.SqlFunction;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
-import org.apache.calcite.sql.SqlOperatorBinding;
 import org.apache.calcite.sql.type.OperandTypes;
 import org.apache.calcite.sql.type.ReturnTypes;
 import org.apache.calcite.sql.type.SqlReturnTypeInference;
@@ -44,22 +43,20 @@ public class OracleSqlOperatorTable extends ReflectiveSqlOperatorTable {
 
   /** Return type inference for {@code DECODE}. */
   protected static final SqlReturnTypeInference DECODE_RETURN_TYPE =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-          final List<RelDataType> list = new ArrayList<>();
-          for (int i = 1, n = opBinding.getOperandCount(); i < n; i++) {
-            if (i < n - 1) {
-              ++i;
-            }
-            list.add(opBinding.getOperandType(i));
+      opBinding -> {
+        final List<RelDataType> list = new ArrayList<>();
+        for (int i = 1, n = opBinding.getOperandCount(); i < n; i++) {
+          if (i < n - 1) {
+            ++i;
           }
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          RelDataType type = typeFactory.leastRestrictive(list);
-          if (opBinding.getOperandCount() % 2 == 1) {
-            type = typeFactory.createTypeWithNullability(type, true);
-          }
-          return type;
+          list.add(opBinding.getOperandType(i));
+        }
+        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+        RelDataType type = typeFactory.leastRestrictive(list);
+        if (opBinding.getOperandCount() % 2 == 1) {
+          type = typeFactory.createTypeWithNullability(type, true);
         }
+        return type;
       };
 
   /** The "DECODE(v, v1, result1, [v2, result2, ...], resultN)" function. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/fun/SqlDatetimeSubtractionOperator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlDatetimeSubtractionOperator.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlDatetimeSubtractionOperator.java
index 1b78c12..7974d65 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlDatetimeSubtractionOperator.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlDatetimeSubtractionOperator.java
@@ -16,8 +16,6 @@
  */
 package org.apache.calcite.sql.fun;
 
-
-
 import org.apache.calcite.sql.SqlCall;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.SqlOperatorBinding;

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/fun/SqlLeadLagAggFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlLeadLagAggFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlLeadLagAggFunction.java
index 5e5498b..d52c82b 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlLeadLagAggFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlLeadLagAggFunction.java
@@ -20,7 +20,6 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
-import org.apache.calcite.sql.SqlOperatorBinding;
 import org.apache.calcite.sql.type.OperandTypes;
 import org.apache.calcite.sql.type.ReturnTypes;
 import org.apache.calcite.sql.type.SameOperandTypeChecker;
@@ -56,21 +55,18 @@ public class SqlLeadLagAggFunction extends SqlAggFunction {
               }));
 
   private static final SqlReturnTypeInference RETURN_TYPE =
-      ReturnTypes.cascade(ReturnTypes.ARG0, new SqlTypeTransform() {
-        public RelDataType transformType(SqlOperatorBinding binding,
-            RelDataType type) {
-          // Result is NOT NULL if NOT NULL default value is provided
-          SqlTypeTransform transform;
-          if (binding.getOperandCount() < 3) {
-            transform = SqlTypeTransforms.FORCE_NULLABLE;
-          } else {
-            RelDataType defValueType = binding.getOperandType(2);
-            transform = defValueType.isNullable()
-                ? SqlTypeTransforms.FORCE_NULLABLE
-                : SqlTypeTransforms.TO_NOT_NULLABLE;
-          }
-          return transform.transformType(binding, type);
+      ReturnTypes.cascade(ReturnTypes.ARG0, (binding, type) -> {
+        // Result is NOT NULL if NOT NULL default value is provided
+        SqlTypeTransform transform;
+        if (binding.getOperandCount() < 3) {
+          transform = SqlTypeTransforms.FORCE_NULLABLE;
+        } else {
+          RelDataType defValueType = binding.getOperandType(2);
+          transform = defValueType.isNullable()
+              ? SqlTypeTransforms.FORCE_NULLABLE
+              : SqlTypeTransforms.TO_NOT_NULLABLE;
         }
+        return transform.transformType(binding, type);
       });
 
   public SqlLeadLagAggFunction(SqlKind kind) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/fun/SqlQuantifyOperator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlQuantifyOperator.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlQuantifyOperator.java
index 6ee5347..bd00eff 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlQuantifyOperator.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlQuantifyOperator.java
@@ -20,6 +20,8 @@ import org.apache.calcite.sql.SqlKind;
 
 import com.google.common.base.Preconditions;
 
+import java.util.Objects;
+
 /**
  * Definition of the SQL <code>ALL</code> and <code>SOME</code>operators.
  *
@@ -47,7 +49,7 @@ public class SqlQuantifyOperator extends SqlInOperator {
    */
   SqlQuantifyOperator(SqlKind kind, SqlKind comparisonKind) {
     super(comparisonKind.sql + " " + kind, kind);
-    this.comparisonKind = Preconditions.checkNotNull(comparisonKind);
+    this.comparisonKind = Objects.requireNonNull(comparisonKind);
     Preconditions.checkArgument(comparisonKind == SqlKind.EQUALS
         || comparisonKind == SqlKind.NOT_EQUALS
         || comparisonKind == SqlKind.LESS_THAN_OR_EQUAL

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
index 45a5536..c9f8363 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
@@ -2242,7 +2242,7 @@ public class SqlStdOperatorTable extends ReflectiveSqlOperatorTable {
       for (final SqlGroupedWindowFunction f
           : ((SqlGroupedWindowFunction) op).getAuxiliaryFunctions()) {
         builder.add(
-            Pair.<SqlNode, AuxiliaryConverter>of(copy(call, f),
+            Pair.of(copy(call, f),
                 new AuxiliaryConverter.Impl(f)));
       }
       return builder.build();
@@ -2253,7 +2253,7 @@ public class SqlStdOperatorTable extends ReflectiveSqlOperatorTable {
   /** Creates a copy of a call with a new operator. */
   private static SqlCall copy(SqlCall call, SqlOperator operator) {
     final List<SqlNode> list = call.getOperandList();
-    return new SqlBasicCall(operator, list.toArray(new SqlNode[list.size()]),
+    return new SqlBasicCall(operator, list.toArray(new SqlNode[0]),
         call.getParserPosition());
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
index 6c38ec5..6dc7dba 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlTimestampAddFunction.java
@@ -22,7 +22,6 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.sql.SqlFunction;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
-import org.apache.calcite.sql.SqlOperatorBinding;
 import org.apache.calcite.sql.type.OperandTypes;
 import org.apache.calcite.sql.type.SqlReturnTypeInference;
 import org.apache.calcite.sql.type.SqlTypeFamily;
@@ -60,13 +59,11 @@ public class SqlTimestampAddFunction extends SqlFunction {
   private static final int MICROSECOND_PRECISION = 6;
 
   private static final SqlReturnTypeInference RETURN_TYPE_INFERENCE =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          return deduceType(typeFactory,
-              opBinding.getOperandLiteralValue(0, TimeUnit.class),
-              opBinding.getOperandType(1), opBinding.getOperandType(2));
-        }
+      opBinding -> {
+        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+        return deduceType(typeFactory,
+            opBinding.getOperandLiteralValue(0, TimeUnit.class),
+            opBinding.getOperandType(1), opBinding.getOperandType(2));
       };
 
   public static RelDataType deduceType(RelDataTypeFactory typeFactory,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/parser/SqlAbstractParserImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/parser/SqlAbstractParserImpl.java b/core/src/main/java/org/apache/calcite/sql/parser/SqlAbstractParserImpl.java
index 34f10f5..0785909 100644
--- a/core/src/main/java/org/apache/calcite/sql/parser/SqlAbstractParserImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/parser/SqlAbstractParserImpl.java
@@ -32,12 +32,12 @@ import org.apache.calcite.util.Glossary;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 
 import java.io.Reader;
 import java.io.StringReader;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -391,7 +391,7 @@ public abstract class SqlAbstractParserImpl {
     // preserve the correct syntax (i.e. don't quote builtin function
     /// name when regenerating SQL).
     if (funName.isSimple()) {
-      final List<SqlOperator> list = Lists.newArrayList();
+      final List<SqlOperator> list = new ArrayList<>();
       opTab.lookupOperatorOverloads(funName, funcType, SqlSyntax.FUNCTION, list);
       if (list.size() == 1) {
         fun = list.get(0);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/parser/SqlParser.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/parser/SqlParser.java b/core/src/main/java/org/apache/calcite/sql/parser/SqlParser.java
index a343a39..0e3aa22 100644
--- a/core/src/main/java/org/apache/calcite/sql/parser/SqlParser.java
+++ b/core/src/main/java/org/apache/calcite/sql/parser/SqlParser.java
@@ -26,9 +26,8 @@ import org.apache.calcite.sql.validate.SqlConformance;
 import org.apache.calcite.sql.validate.SqlConformanceEnum;
 import org.apache.calcite.sql.validate.SqlDelegatingConformance;
 
-import com.google.common.base.Preconditions;
-
 import java.io.StringReader;
+import java.util.Objects;
 
 /**
  * A <code>SqlParser</code> parses a SQL statement.
@@ -231,17 +230,17 @@ public class SqlParser {
     }
 
     public ConfigBuilder setQuotedCasing(Casing quotedCasing) {
-      this.quotedCasing = Preconditions.checkNotNull(quotedCasing);
+      this.quotedCasing = Objects.requireNonNull(quotedCasing);
       return this;
     }
 
     public ConfigBuilder setUnquotedCasing(Casing unquotedCasing) {
-      this.unquotedCasing = Preconditions.checkNotNull(unquotedCasing);
+      this.unquotedCasing = Objects.requireNonNull(unquotedCasing);
       return this;
     }
 
     public ConfigBuilder setQuoting(Quoting quoting) {
-      this.quoting = Preconditions.checkNotNull(quoting);
+      this.quoting = Objects.requireNonNull(quoting);
       return this;
     }
 
@@ -275,7 +274,7 @@ public class SqlParser {
     }
 
     public ConfigBuilder setParserFactory(SqlParserImplFactory factory) {
-      this.parserFactory = Preconditions.checkNotNull(factory);
+      this.parserFactory = Objects.requireNonNull(factory);
       return this;
     }
 
@@ -313,11 +312,11 @@ public class SqlParser {
         SqlConformance conformance, SqlParserImplFactory parserFactory) {
       this.identifierMaxLength = identifierMaxLength;
       this.caseSensitive = caseSensitive;
-      this.conformance = Preconditions.checkNotNull(conformance);
-      this.quotedCasing = Preconditions.checkNotNull(quotedCasing);
-      this.unquotedCasing = Preconditions.checkNotNull(unquotedCasing);
-      this.quoting = Preconditions.checkNotNull(quoting);
-      this.parserFactory = Preconditions.checkNotNull(parserFactory);
+      this.conformance = Objects.requireNonNull(conformance);
+      this.quotedCasing = Objects.requireNonNull(quotedCasing);
+      this.unquotedCasing = Objects.requireNonNull(unquotedCasing);
+      this.quoting = Objects.requireNonNull(quoting);
+      this.parserFactory = Objects.requireNonNull(parserFactory);
     }
 
     public int identifierMaxLength() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/parser/SqlParserPos.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/parser/SqlParserPos.java b/core/src/main/java/org/apache/calcite/sql/parser/SqlParserPos.java
index 80d9cc9..b744e64 100644
--- a/core/src/main/java/org/apache/calcite/sql/parser/SqlParserPos.java
+++ b/core/src/main/java/org/apache/calcite/sql/parser/SqlParserPos.java
@@ -18,7 +18,6 @@ package org.apache.calcite.sql.parser;
 
 import org.apache.calcite.sql.SqlNode;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 
@@ -46,13 +45,6 @@ public class SqlParserPos implements Serializable {
 
   private static final long serialVersionUID = 1L;
 
-  private static final Function<SqlNode, SqlParserPos> NODE_TO_POS =
-      new Function<SqlNode, SqlParserPos>() {
-        public SqlParserPos apply(SqlNode input) {
-          return input.getParserPosition();
-        }
-      };
-
   //~ Instance fields --------------------------------------------------------
 
   private final int lineNumber;
@@ -190,7 +182,7 @@ public class SqlParserPos implements Serializable {
   }
 
   private static Iterable<SqlParserPos> toPos(Iterable<SqlNode> nodes) {
-    return Iterables.transform(nodes, NODE_TO_POS);
+    return Iterables.transform(nodes, SqlNode::getParserPosition);
   }
 
   /**
@@ -198,7 +190,7 @@ public class SqlParserPos implements Serializable {
    * which spans from the beginning of the first to the end of the last.
    */
   public static SqlParserPos sum(final List<? extends SqlNode> nodes) {
-    return sum(Lists.transform(nodes, NODE_TO_POS));
+    return sum(Lists.transform(nodes, SqlNode::getParserPosition));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/parser/SqlParserUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/parser/SqlParserUtil.java b/core/src/main/java/org/apache/calcite/sql/parser/SqlParserUtil.java
index e82841a..0071c77 100644
--- a/core/src/main/java/org/apache/calcite/sql/parser/SqlParserUtil.java
+++ b/core/src/main/java/org/apache/calcite/sql/parser/SqlParserUtil.java
@@ -20,7 +20,6 @@ import org.apache.calcite.avatica.util.Casing;
 import org.apache.calcite.avatica.util.DateTimeUtils;
 import org.apache.calcite.rel.type.RelDataTypeSystem;
 import org.apache.calcite.runtime.CalciteContextException;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SqlBinaryOperator;
 import org.apache.calcite.sql.SqlDateLiteral;
 import org.apache.calcite.sql.SqlIntervalLiteral;
@@ -47,7 +46,6 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
 
 import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 
 import org.slf4j.Logger;
 
@@ -60,7 +58,9 @@ import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.List;
 import java.util.Locale;
+import java.util.Objects;
 import java.util.StringTokenizer;
+import java.util.function.Predicate;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -571,11 +571,11 @@ public final class SqlParserUtil {
 
   @Deprecated // to be removed before 2.0
   public static String[] toStringArray(List<String> list) {
-    return list.toArray(new String[list.size()]);
+    return list.toArray(new String[0]);
   }
 
   public static SqlNode[] toNodeArray(List<SqlNode> list) {
-    return list.toArray(new SqlNode[list.size()]);
+    return list.toArray(new SqlNode[0]);
   }
 
   public static SqlNode[] toNodeArray(SqlNodeList list) {
@@ -608,7 +608,7 @@ public final class SqlParserUtil {
       int start,
       int end,
       T o) {
-    Preconditions.checkNotNull(list);
+    Objects.requireNonNull(list);
     Preconditions.checkArgument(start < end);
     for (int i = end - 1; i > start; --i) {
       list.remove(i);
@@ -651,21 +651,18 @@ public final class SqlParserUtil {
    */
   public static SqlNode toTreeEx(SqlSpecialOperator.TokenSequence list,
       int start, final int minPrec, final SqlKind stopperKind) {
-    final Predicate<PrecedenceClimbingParser.Token> predicate =
-        new PredicateImpl<PrecedenceClimbingParser.Token>() {
-          public boolean test(PrecedenceClimbingParser.Token t) {
-            if (t instanceof PrecedenceClimbingParser.Op) {
-              final SqlOperator op = ((ToTreeListItem) t.o).op;
-              return stopperKind != SqlKind.OTHER
-                  && op.kind == stopperKind
-                  || minPrec > 0
-                  && op.getLeftPrec() < minPrec;
-            } else {
-              return false;
-            }
+    PrecedenceClimbingParser parser = list.parser(start,
+        token -> {
+          if (token instanceof PrecedenceClimbingParser.Op) {
+            final SqlOperator op = ((ToTreeListItem) token.o).op;
+            return stopperKind != SqlKind.OTHER
+                && op.kind == stopperKind
+                || minPrec > 0
+                && op.getLeftPrec() < minPrec;
+          } else {
+            return false;
           }
-        };
-    PrecedenceClimbingParser parser = list.parser(start, predicate);
+        });
     final int beforeSize = parser.all().size();
     parser.partialParse();
     final int afterSize = parser.all().size();
@@ -814,8 +811,8 @@ public final class SqlParserUtil {
       this.list = parser.all();
     }
 
-    public PrecedenceClimbingParser parser(int start, Predicate
-        <PrecedenceClimbingParser.Token> predicate) {
+    public PrecedenceClimbingParser parser(int start,
+        Predicate<PrecedenceClimbingParser.Token> predicate) {
       return parser.copy(start, predicate);
     }
 
@@ -888,22 +885,18 @@ public final class SqlParserUtil {
                 op.getLeftPrec() < op.getRightPrec());
           } else if (op instanceof SqlSpecialOperator) {
             builder.special(item, op.getLeftPrec(), op.getRightPrec(),
-                new PrecedenceClimbingParser.Special() {
-                  public PrecedenceClimbingParser.Result apply(
-                      PrecedenceClimbingParser parser,
-                      PrecedenceClimbingParser.SpecialOp op) {
-                    final List<PrecedenceClimbingParser.Token> tokens =
-                        parser.all();
-                    final SqlSpecialOperator op1 =
-                        (SqlSpecialOperator) ((ToTreeListItem) op.o).op;
-                    SqlSpecialOperator.ReduceResult r =
-                        op1.reduceExpr(tokens.indexOf(op),
-                            new TokenSequenceImpl(parser));
-                    return new PrecedenceClimbingParser.Result(
-                        tokens.get(r.startOrdinal),
-                        tokens.get(r.endOrdinal - 1),
-                        parser.atom(r.node));
-                  }
+                (parser, op2) -> {
+                  final List<PrecedenceClimbingParser.Token> tokens =
+                      parser.all();
+                  final SqlSpecialOperator op1 =
+                      (SqlSpecialOperator) ((ToTreeListItem) op2.o).op;
+                  SqlSpecialOperator.ReduceResult r =
+                      op1.reduceExpr(tokens.indexOf(op2),
+                          new TokenSequenceImpl(parser));
+                  return new PrecedenceClimbingParser.Result(
+                      tokens.get(r.startOrdinal),
+                      tokens.get(r.endOrdinal - 1),
+                      parser.atom(r.node));
                 });
           } else {
             throw new AssertionError();
@@ -947,11 +940,7 @@ public final class SqlParserUtil {
    * thread, because {@code DateFormat} is not thread-safe. */
   private static class Format {
     private static final ThreadLocal<Format> PER_THREAD =
-        new ThreadLocal<Format>() {
-          @Override protected Format initialValue() {
-            return new Format();
-          }
-        };
+        ThreadLocal.withInitial(Format::new);
     final DateFormat timestamp =
         new SimpleDateFormat(DateTimeUtils.TIMESTAMP_FORMAT_STRING,
             Locale.ROOT);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/pretty/SqlPrettyWriter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/pretty/SqlPrettyWriter.java b/core/src/main/java/org/apache/calcite/sql/pretty/SqlPrettyWriter.java
index 4a84bb5..90ef611 100644
--- a/core/src/main/java/org/apache/calcite/sql/pretty/SqlPrettyWriter.java
+++ b/core/src/main/java/org/apache/calcite/sql/pretty/SqlPrettyWriter.java
@@ -1142,7 +1142,7 @@ public class SqlPrettyWriter implements SqlWriter {
       final Set<String> names = new HashSet<>();
       names.addAll(getterMethods.keySet());
       names.addAll(setterMethods.keySet());
-      return names.toArray(new String[names.size()]);
+      return names.toArray(new String[0]);
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/ArraySqlType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/ArraySqlType.java b/core/src/main/java/org/apache/calcite/sql/type/ArraySqlType.java
index c3ae782..78c3569 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/ArraySqlType.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/ArraySqlType.java
@@ -20,7 +20,7 @@ import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFamily;
 import org.apache.calcite.rel.type.RelDataTypePrecedenceList;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /**
  * SQL array type.
@@ -38,7 +38,7 @@ public class ArraySqlType extends AbstractSqlType {
    */
   public ArraySqlType(RelDataType elementType, boolean isNullable) {
     super(SqlTypeName.ARRAY, isNullable, null);
-    this.elementType = Preconditions.checkNotNull(elementType);
+    this.elementType = Objects.requireNonNull(elementType);
     computeDigest();
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/ComparableOperandTypeChecker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/ComparableOperandTypeChecker.java b/core/src/main/java/org/apache/calcite/sql/type/ComparableOperandTypeChecker.java
index 0849b58..307db46 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/ComparableOperandTypeChecker.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/ComparableOperandTypeChecker.java
@@ -21,7 +21,7 @@ import org.apache.calcite.rel.type.RelDataTypeComparability;
 import org.apache.calcite.sql.SqlCallBinding;
 import org.apache.calcite.sql.SqlOperatorBinding;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /**
  * Type checking strategy which verifies that types have the required attributes
@@ -45,7 +45,7 @@ public class ComparableOperandTypeChecker extends SameOperandTypeChecker {
       RelDataTypeComparability requiredComparability, Consistency consistency) {
     super(nOperands);
     this.requiredComparability = requiredComparability;
-    this.consistency = Preconditions.checkNotNull(consistency);
+    this.consistency = Objects.requireNonNull(consistency);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/CompositeOperandTypeChecker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/CompositeOperandTypeChecker.java b/core/src/main/java/org/apache/calcite/sql/type/CompositeOperandTypeChecker.java
index 36d47cb..7c55750 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/CompositeOperandTypeChecker.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/CompositeOperandTypeChecker.java
@@ -22,11 +22,11 @@ import org.apache.calcite.sql.SqlOperandCountRange;
 import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.AbstractList;
 import java.util.List;
+import java.util.Objects;
 import javax.annotation.Nullable;
 
 /**
@@ -93,8 +93,8 @@ public class CompositeOperandTypeChecker implements SqlOperandTypeChecker {
       ImmutableList<? extends SqlOperandTypeChecker> allowedRules,
       @Nullable String allowedSignatures,
       @Nullable SqlOperandCountRange range) {
-    this.allowedRules = Preconditions.checkNotNull(allowedRules);
-    this.composition = Preconditions.checkNotNull(composition);
+    this.allowedRules = Objects.requireNonNull(allowedRules);
+    this.composition = Objects.requireNonNull(composition);
     this.allowedSignatures = allowedSignatures;
     this.range = range;
     assert (range != null) == (composition == Composition.REPEAT);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/FamilyOperandTypeChecker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/FamilyOperandTypeChecker.java b/core/src/main/java/org/apache/calcite/sql/type/FamilyOperandTypeChecker.java
index b9cf248..455ec41 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/FamilyOperandTypeChecker.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/FamilyOperandTypeChecker.java
@@ -24,10 +24,10 @@ import org.apache.calcite.sql.SqlOperandCountRange;
 import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlUtil;
 
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.function.Predicate;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -55,7 +55,7 @@ public class FamilyOperandTypeChecker implements SqlSingleOperandTypeChecker {
   //~ Methods ----------------------------------------------------------------
 
   public boolean isOptional(int i) {
-    return optional.apply(i);
+    return optional.test(i);
   }
 
   public boolean checkSingleOperandType(
@@ -120,7 +120,7 @@ public class FamilyOperandTypeChecker implements SqlSingleOperandTypeChecker {
   public SqlOperandCountRange getOperandCountRange() {
     final int max = families.size();
     int min = max;
-    while (min > 0 && optional.apply(min - 1)) {
+    while (min > 0 && optional.test(min - 1)) {
       --min;
     }
     return SqlOperandCountRanges.between(min, max);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/InferTypes.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/InferTypes.java b/core/src/main/java/org/apache/calcite/sql/type/InferTypes.java
index 938a058..10dd95c 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/InferTypes.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/InferTypes.java
@@ -18,7 +18,6 @@ package org.apache.calcite.sql.type;
 
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
-import org.apache.calcite.sql.SqlCallBinding;
 import org.apache.calcite.sql.SqlNode;
 
 import com.google.common.collect.ImmutableList;
@@ -39,30 +38,25 @@ public abstract class InferTypes {
    * from the first operand with a known type.
    */
   public static final SqlOperandTypeInference FIRST_KNOWN =
-      new SqlOperandTypeInference() {
-        public void inferOperandTypes(
-            SqlCallBinding callBinding,
-            RelDataType returnType,
-            RelDataType[] operandTypes) {
-          final RelDataType unknownType =
-              callBinding.getValidator().getUnknownType();
-          RelDataType knownType = unknownType;
-          for (SqlNode operand : callBinding.operands()) {
-            knownType = callBinding.getValidator().deriveType(
-                callBinding.getScope(), operand);
-            if (!knownType.equals(unknownType)) {
-              break;
-            }
+      (callBinding, returnType, operandTypes) -> {
+        final RelDataType unknownType =
+            callBinding.getValidator().getUnknownType();
+        RelDataType knownType = unknownType;
+        for (SqlNode operand : callBinding.operands()) {
+          knownType = callBinding.getValidator().deriveType(
+              callBinding.getScope(), operand);
+          if (!knownType.equals(unknownType)) {
+            break;
           }
+        }
 
-          // REVIEW jvs 11-Nov-2008:  We can't assert this
-          // because SqlAdvisorValidator produces
-          // unknown types for incomplete expressions.
-          // Maybe we need to distinguish the two kinds of unknown.
-          //assert !knownType.equals(unknownType);
-          for (int i = 0; i < operandTypes.length; ++i) {
-            operandTypes[i] = knownType;
-          }
+        // REVIEW jvs 11-Nov-2008:  We can't assert this
+        // because SqlAdvisorValidator produces
+        // unknown types for incomplete expressions.
+        // Maybe we need to distinguish the two kinds of unknown.
+        //assert !knownType.equals(unknownType);
+        for (int i = 0; i < operandTypes.length; ++i) {
+          operandTypes[i] = knownType;
         }
       };
 
@@ -72,17 +66,12 @@ public abstract class InferTypes {
    * the same number of fields as the number of operands.
    */
   public static final SqlOperandTypeInference RETURN_TYPE =
-      new SqlOperandTypeInference() {
-        public void inferOperandTypes(
-            SqlCallBinding callBinding,
-            RelDataType returnType,
-            RelDataType[] operandTypes) {
-          for (int i = 0; i < operandTypes.length; ++i) {
-            operandTypes[i] =
-                returnType.isStruct()
-                    ? returnType.getFieldList().get(i).getType()
-                    : returnType;
-          }
+      (callBinding, returnType, operandTypes) -> {
+        for (int i = 0; i < operandTypes.length; ++i) {
+          operandTypes[i] =
+              returnType.isStruct()
+                  ? returnType.getFieldList().get(i).getType()
+                  : returnType;
         }
       };
 
@@ -91,16 +80,11 @@ public abstract class InferTypes {
    * to be boolean.
    */
   public static final SqlOperandTypeInference BOOLEAN =
-      new SqlOperandTypeInference() {
-        public void inferOperandTypes(
-            SqlCallBinding callBinding,
-            RelDataType returnType,
-            RelDataType[] operandTypes) {
-          RelDataTypeFactory typeFactory = callBinding.getTypeFactory();
-          for (int i = 0; i < operandTypes.length; ++i) {
-            operandTypes[i] =
-                typeFactory.createSqlType(SqlTypeName.BOOLEAN);
-          }
+      (callBinding, returnType, operandTypes) -> {
+        RelDataTypeFactory typeFactory = callBinding.getTypeFactory();
+        for (int i = 0; i < operandTypes.length; ++i) {
+          operandTypes[i] =
+              typeFactory.createSqlType(SqlTypeName.BOOLEAN);
         }
       };
 
@@ -112,16 +96,11 @@ public abstract class InferTypes {
    * use something that every other type can be cast to.
    */
   public static final SqlOperandTypeInference VARCHAR_1024 =
-      new SqlOperandTypeInference() {
-        public void inferOperandTypes(
-            SqlCallBinding callBinding,
-            RelDataType returnType,
-            RelDataType[] operandTypes) {
-          RelDataTypeFactory typeFactory = callBinding.getTypeFactory();
-          for (int i = 0; i < operandTypes.length; ++i) {
-            operandTypes[i] =
-                typeFactory.createSqlType(SqlTypeName.VARCHAR, 1024);
-          }
+      (callBinding, returnType, operandTypes) -> {
+        RelDataTypeFactory typeFactory = callBinding.getTypeFactory();
+        for (int i = 0; i < operandTypes.length; ++i) {
+          operandTypes[i] =
+              typeFactory.createSqlType(SqlTypeName.VARCHAR, 1024);
         }
       };
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/IntervalSqlType.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/IntervalSqlType.java b/core/src/main/java/org/apache/calcite/sql/type/IntervalSqlType.java
index 4789c06..399709e 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/IntervalSqlType.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/IntervalSqlType.java
@@ -27,7 +27,7 @@ import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.sql.pretty.SqlPrettyWriter;
 import org.apache.calcite.sql.util.SqlString;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /**
  * IntervalSqlType represents a standard SQL datetime interval type.
@@ -48,8 +48,8 @@ public class IntervalSqlType extends AbstractSqlType {
       SqlIntervalQualifier intervalQualifier,
       boolean isNullable) {
     super(intervalQualifier.typeName(), isNullable, null);
-    this.typeSystem = Preconditions.checkNotNull(typeSystem);
-    this.intervalQualifier = Preconditions.checkNotNull(intervalQualifier);
+    this.typeSystem = Objects.requireNonNull(typeSystem);
+    this.intervalQualifier = Objects.requireNonNull(intervalQualifier);
     computeDigest();
   }
 
@@ -84,10 +84,10 @@ public class IntervalSqlType extends AbstractSqlType {
       IntervalSqlType that) {
     assert this.typeName.isYearMonth() == that.typeName.isYearMonth();
     boolean nullable = isNullable || that.isNullable;
-    TimeUnit thisStart = Preconditions.checkNotNull(typeName.getStartUnit());
+    TimeUnit thisStart = Objects.requireNonNull(typeName.getStartUnit());
     TimeUnit thisEnd = typeName.getEndUnit();
     final TimeUnit thatStart =
-        Preconditions.checkNotNull(that.typeName.getStartUnit());
+        Objects.requireNonNull(that.typeName.getStartUnit());
     final TimeUnit thatEnd = that.typeName.getEndUnit();
 
     int secondPrec =

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java b/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
index c619bb1..dcdaa63 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
@@ -18,7 +18,6 @@ package org.apache.calcite.sql.type;
 
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeComparability;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.sql.SqlCallBinding;
 import org.apache.calcite.sql.SqlLiteral;
 import org.apache.calcite.sql.SqlNode;
@@ -26,12 +25,11 @@ import org.apache.calcite.sql.SqlOperandCountRange;
 import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlUtil;
 
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 
 import java.math.BigDecimal;
 import java.util.List;
+import java.util.function.Predicate;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -62,7 +60,7 @@ public abstract class OperandTypes {
    */
   public static FamilyOperandTypeChecker family(SqlTypeFamily... families) {
     return new FamilyOperandTypeChecker(ImmutableList.copyOf(families),
-        Predicates.<Integer>alwaysFalse());
+        i -> false);
   }
 
   /**
@@ -79,7 +77,7 @@ public abstract class OperandTypes {
    * corresponding family.
    */
   public static FamilyOperandTypeChecker family(List<SqlTypeFamily> families) {
-    return family(families, Predicates.<Integer>alwaysFalse());
+    return family(families, i -> false);
   }
 
   /**
@@ -205,11 +203,7 @@ public abstract class OperandTypes {
   public static final SqlSingleOperandTypeChecker NUMERIC_OPTIONAL_INTEGER =
       family(ImmutableList.of(SqlTypeFamily.NUMERIC, SqlTypeFamily.INTEGER),
           // Second operand optional (operand index 0, 1)
-          new PredicateImpl<Integer>() {
-            public boolean test(Integer number) {
-              return number == 1;
-            }
-          });
+          number -> number == 1);
 
   public static final SqlSingleOperandTypeChecker NUMERIC_INTEGER =
       family(SqlTypeFamily.NUMERIC, SqlTypeFamily.INTEGER);
@@ -288,7 +282,7 @@ public abstract class OperandTypes {
    */
   public static final SqlSingleOperandTypeChecker POSITIVE_INTEGER_LITERAL =
       new FamilyOperandTypeChecker(ImmutableList.of(SqlTypeFamily.INTEGER),
-          Predicates.<Integer>alwaysFalse()) {
+          i -> false) {
         public boolean checkSingleOperandType(
             SqlCallBinding callBinding,
             SqlNode node,
@@ -484,7 +478,7 @@ public abstract class OperandTypes {
       new FamilyOperandTypeChecker(
           ImmutableList.of(SqlTypeFamily.DATETIME, SqlTypeFamily.DATETIME,
               SqlTypeFamily.DATETIME_INTERVAL),
-          Predicates.<Integer>alwaysFalse()) {
+          i -> false) {
         public boolean checkOperandTypes(
             SqlCallBinding callBinding,
             boolean throwOnFailure) {


[14/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java b/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
index 15ca544..8b07b83 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
@@ -186,22 +186,20 @@ public abstract class ReturnTypes {
    * BOOLEAN.
    */
   public static final SqlReturnTypeInference BOOLEAN_NULLABLE_OPTIMIZED =
-      new SqlReturnTypeInference() {
+      opBinding -> {
         // Equivalent to
         //   cascade(ARG0, SqlTypeTransforms.TO_NULLABLE);
         // but implemented by hand because used in AND, which is a very common
         // operator.
-        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-          final int n = opBinding.getOperandCount();
-          RelDataType type1 = null;
-          for (int i = 0; i < n; i++) {
-            type1 = opBinding.getOperandType(i);
-            if (type1.isNullable()) {
-              break;
-            }
+        final int n = opBinding.getOperandCount();
+        RelDataType type1 = null;
+        for (int i = 0; i < n; i++) {
+          type1 = opBinding.getOperandType(i);
+          if (type1.isNullable()) {
+            break;
           }
-          return type1;
         }
+        return type1;
       };
 
   /**
@@ -300,44 +298,36 @@ public abstract class ReturnTypes {
    * @see Glossary#SQL99 SQL:1999 Part 2 Section 9.3
    */
   public static final SqlReturnTypeInference LEAST_RESTRICTIVE =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-          return opBinding.getTypeFactory().leastRestrictive(
-              opBinding.collectOperandTypes());
-        }
-      };
+      opBinding -> opBinding.getTypeFactory().leastRestrictive(
+          opBinding.collectOperandTypes());
   /**
    * Returns the same type as the multiset carries. The multiset type returned
    * is the least restrictive of the call's multiset operands
    */
-  public static final SqlReturnTypeInference MULTISET =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            final SqlOperatorBinding opBinding) {
-          ExplicitOperatorBinding newBinding =
-              new ExplicitOperatorBinding(
-                  opBinding,
-                  new AbstractList<RelDataType>() {
-                    // CHECKSTYLE: IGNORE 12
-                    public RelDataType get(int index) {
-                      RelDataType type =
-                          opBinding.getOperandType(index)
-                              .getComponentType();
-                      assert type != null;
-                      return type;
-                    }
-
-                    public int size() {
-                      return opBinding.getOperandCount();
-                    }
-                  });
-          RelDataType biggestElementType =
-              LEAST_RESTRICTIVE.inferReturnType(newBinding);
-          return opBinding.getTypeFactory().createMultisetType(
-              biggestElementType,
-              -1);
-        }
-      };
+  public static final SqlReturnTypeInference MULTISET = opBinding -> {
+    ExplicitOperatorBinding newBinding =
+        new ExplicitOperatorBinding(
+            opBinding,
+            new AbstractList<RelDataType>() {
+              // CHECKSTYLE: IGNORE 12
+              public RelDataType get(int index) {
+                RelDataType type =
+                    opBinding.getOperandType(index)
+                        .getComponentType();
+                assert type != null;
+                return type;
+              }
+
+              public int size() {
+                return opBinding.getOperandCount();
+              }
+            });
+    RelDataType biggestElementType =
+        LEAST_RESTRICTIVE.inferReturnType(newBinding);
+    return opBinding.getTypeFactory().createMultisetType(
+        biggestElementType,
+        -1);
+  };
 
   /**
    * Returns a multiset type.
@@ -383,33 +373,29 @@ public abstract class ReturnTypes {
    * The result type of a call is a decimal with a scale of 0, and the same
    * precision and nullability as the first argument.
    */
-  public static final SqlReturnTypeInference DECIMAL_SCALE0 =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          RelDataType type1 = opBinding.getOperandType(0);
-          if (SqlTypeUtil.isDecimal(type1)) {
-            if (type1.getScale() == 0) {
-              return type1;
-            } else {
-              int p = type1.getPrecision();
-              RelDataType ret;
-              ret =
-                  opBinding.getTypeFactory().createSqlType(
-                      SqlTypeName.DECIMAL,
-                      p,
-                      0);
-              if (type1.isNullable()) {
-                ret =
-                    opBinding.getTypeFactory()
-                        .createTypeWithNullability(ret, true);
-              }
-              return ret;
-            }
-          }
-          return null;
+  public static final SqlReturnTypeInference DECIMAL_SCALE0 = opBinding -> {
+    RelDataType type1 = opBinding.getOperandType(0);
+    if (SqlTypeUtil.isDecimal(type1)) {
+      if (type1.getScale() == 0) {
+        return type1;
+      } else {
+        int p = type1.getPrecision();
+        RelDataType ret;
+        ret =
+            opBinding.getTypeFactory().createSqlType(
+                SqlTypeName.DECIMAL,
+                p,
+                0);
+        if (type1.isNullable()) {
+          ret =
+              opBinding.getTypeFactory()
+                  .createTypeWithNullability(ret, true);
         }
-      };
+        return ret;
+      }
+    }
+    return null;
+  };
   /**
    * Type-inference strategy whereby the result type of a call is
    * {@link #DECIMAL_SCALE0} with a fallback to {@link #ARG0} This rule
@@ -423,15 +409,12 @@ public abstract class ReturnTypes {
    * product of two exact numeric operands where at least one of the operands
    * is a decimal.
    */
-  public static final SqlReturnTypeInference DECIMAL_PRODUCT =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-          RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          RelDataType type1 = opBinding.getOperandType(0);
-          RelDataType type2 = opBinding.getOperandType(1);
-          return typeFactory.createDecimalProduct(type1, type2);
-        }
-      };
+  public static final SqlReturnTypeInference DECIMAL_PRODUCT = opBinding -> {
+    RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    RelDataType type1 = opBinding.getOperandType(0);
+    RelDataType type2 = opBinding.getOperandType(1);
+    return typeFactory.createDecimalProduct(type1, type2);
+  };
   /**
    * Same as {@link #DECIMAL_PRODUCT} but returns with nullability if any of
    * the operands is nullable by using
@@ -456,16 +439,12 @@ public abstract class ReturnTypes {
    * product of two exact numeric operands where at least one of the operands
    * is a decimal.
    */
-  public static final SqlReturnTypeInference DECIMAL_QUOTIENT =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          RelDataType type1 = opBinding.getOperandType(0);
-          RelDataType type2 = opBinding.getOperandType(1);
-          return typeFactory.createDecimalQuotient(type1, type2);
-        }
-      };
+  public static final SqlReturnTypeInference DECIMAL_QUOTIENT = opBinding -> {
+    RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    RelDataType type1 = opBinding.getOperandType(0);
+    RelDataType type2 = opBinding.getOperandType(1);
+    return typeFactory.createDecimalQuotient(type1, type2);
+  };
   /**
    * Same as {@link #DECIMAL_QUOTIENT} but returns with nullability if any of
    * the operands is nullable by using
@@ -500,42 +479,38 @@ public abstract class ReturnTypes {
    *
    * @see Glossary#SQL2003 SQL:2003 Part 2 Section 6.26
    */
-  public static final SqlReturnTypeInference DECIMAL_SUM =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          RelDataType type1 = opBinding.getOperandType(0);
-          RelDataType type2 = opBinding.getOperandType(1);
-          if (SqlTypeUtil.isExactNumeric(type1)
-              && SqlTypeUtil.isExactNumeric(type2)) {
-            if (SqlTypeUtil.isDecimal(type1)
-                || SqlTypeUtil.isDecimal(type2)) {
-              int p1 = type1.getPrecision();
-              int p2 = type2.getPrecision();
-              int s1 = type1.getScale();
-              int s2 = type2.getScale();
-
-              final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-              int scale = Math.max(s1, s2);
-              final RelDataTypeSystem typeSystem = typeFactory.getTypeSystem();
-              assert scale <= typeSystem.getMaxNumericScale();
-              int precision = Math.max(p1 - s1, p2 - s2) + scale + 1;
-              precision =
-                  Math.min(
-                      precision,
-                      typeSystem.getMaxNumericPrecision());
-              assert precision > 0;
-
-              return typeFactory.createSqlType(
-                  SqlTypeName.DECIMAL,
-                  precision,
-                  scale);
-            }
-          }
-
-          return null;
-        }
-      };
+  public static final SqlReturnTypeInference DECIMAL_SUM = opBinding -> {
+    RelDataType type1 = opBinding.getOperandType(0);
+    RelDataType type2 = opBinding.getOperandType(1);
+    if (SqlTypeUtil.isExactNumeric(type1)
+        && SqlTypeUtil.isExactNumeric(type2)) {
+      if (SqlTypeUtil.isDecimal(type1)
+          || SqlTypeUtil.isDecimal(type2)) {
+        int p1 = type1.getPrecision();
+        int p2 = type2.getPrecision();
+        int s1 = type1.getScale();
+        int s2 = type2.getScale();
+
+        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+        int scale = Math.max(s1, s2);
+        final RelDataTypeSystem typeSystem = typeFactory.getTypeSystem();
+        assert scale <= typeSystem.getMaxNumericScale();
+        int precision = Math.max(p1 - s1, p2 - s2) + scale + 1;
+        precision =
+            Math.min(
+                precision,
+                typeSystem.getMaxNumericPrecision());
+        assert precision > 0;
+
+        return typeFactory.createSqlType(
+            SqlTypeName.DECIMAL,
+            precision,
+            scale);
+      }
+    }
+
+    return null;
+  };
   /**
    * Same as {@link #DECIMAL_SUM} but returns with nullability if any
    * of the operands is nullable by using
@@ -571,75 +546,73 @@ public abstract class ReturnTypes {
    * </ul>
    */
   public static final SqlReturnTypeInference DYADIC_STRING_SUM_PRECISION =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataType argType0 = opBinding.getOperandType(0);
-          final RelDataType argType1 = opBinding.getOperandType(1);
-
-          final boolean containsAnyType =
-              (argType0.getSqlTypeName() == SqlTypeName.ANY)
-                  || (argType1.getSqlTypeName() == SqlTypeName.ANY);
-
-          if (!containsAnyType
-              && !(SqlTypeUtil.inCharOrBinaryFamilies(argType0)
-                  && SqlTypeUtil.inCharOrBinaryFamilies(argType1))) {
-            Preconditions.checkArgument(
-                SqlTypeUtil.sameNamedType(argType0, argType1));
-          }
-          SqlCollation pickedCollation = null;
-          if (!containsAnyType
-              && SqlTypeUtil.inCharFamily(argType0)) {
-            if (!SqlTypeUtil.isCharTypeComparable(
-                opBinding.collectOperandTypes().subList(0, 2))) {
-              throw opBinding.newError(
-                  RESOURCE.typeNotComparable(
-                      argType0.getFullTypeString(),
-                      argType1.getFullTypeString()));
-            }
-
-            pickedCollation =
-                SqlCollation.getCoercibilityDyadicOperator(
-                    argType0.getCollation(), argType1.getCollation());
-            assert null != pickedCollation;
+      opBinding -> {
+        final RelDataType argType0 = opBinding.getOperandType(0);
+        final RelDataType argType1 = opBinding.getOperandType(1);
+
+        final boolean containsAnyType =
+            (argType0.getSqlTypeName() == SqlTypeName.ANY)
+                || (argType1.getSqlTypeName() == SqlTypeName.ANY);
+
+        if (!containsAnyType
+            && !(SqlTypeUtil.inCharOrBinaryFamilies(argType0)
+            && SqlTypeUtil.inCharOrBinaryFamilies(argType1))) {
+          Preconditions.checkArgument(
+              SqlTypeUtil.sameNamedType(argType0, argType1));
+        }
+        SqlCollation pickedCollation = null;
+        if (!containsAnyType
+            && SqlTypeUtil.inCharFamily(argType0)) {
+          if (!SqlTypeUtil.isCharTypeComparable(
+              opBinding.collectOperandTypes().subList(0, 2))) {
+            throw opBinding.newError(
+                RESOURCE.typeNotComparable(
+                    argType0.getFullTypeString(),
+                    argType1.getFullTypeString()));
           }
 
-          // Determine whether result is variable-length
-          SqlTypeName typeName =
-              argType0.getSqlTypeName();
-          if (SqlTypeUtil.isBoundedVariableWidth(argType1)) {
-            typeName = argType1.getSqlTypeName();
-          }
+          pickedCollation =
+              SqlCollation.getCoercibilityDyadicOperator(
+                  argType0.getCollation(), argType1.getCollation());
+          assert null != pickedCollation;
+        }
 
-          RelDataType ret;
-          int typePrecision;
-          final long x =
-              (long) argType0.getPrecision() + (long) argType1.getPrecision();
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          final RelDataTypeSystem typeSystem = typeFactory.getTypeSystem();
-          if (argType0.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED
-              || argType1.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED
-              || x > typeSystem.getMaxPrecision(typeName)) {
-            typePrecision = RelDataType.PRECISION_NOT_SPECIFIED;
-          } else {
-            typePrecision = (int) x;
-          }
+        // Determine whether result is variable-length
+        SqlTypeName typeName =
+            argType0.getSqlTypeName();
+        if (SqlTypeUtil.isBoundedVariableWidth(argType1)) {
+          typeName = argType1.getSqlTypeName();
+        }
+
+        RelDataType ret;
+        int typePrecision;
+        final long x =
+            (long) argType0.getPrecision() + (long) argType1.getPrecision();
+        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+        final RelDataTypeSystem typeSystem = typeFactory.getTypeSystem();
+        if (argType0.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED
+            || argType1.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED
+            || x > typeSystem.getMaxPrecision(typeName)) {
+          typePrecision = RelDataType.PRECISION_NOT_SPECIFIED;
+        } else {
+          typePrecision = (int) x;
+        }
 
-          ret = typeFactory.createSqlType(typeName, typePrecision);
-          if (null != pickedCollation) {
-            RelDataType pickedType;
-            if (argType0.getCollation().equals(pickedCollation)) {
-              pickedType = argType0;
-            } else if (argType1.getCollation().equals(pickedCollation)) {
-              pickedType = argType1;
-            } else {
-              throw new AssertionError("should never come here");
-            }
-            ret =
-                typeFactory.createTypeWithCharsetAndCollation(ret,
-                    pickedType.getCharset(), pickedType.getCollation());
+        ret = typeFactory.createSqlType(typeName, typePrecision);
+        if (null != pickedCollation) {
+          RelDataType pickedType;
+          if (argType0.getCollation().equals(pickedCollation)) {
+            pickedType = argType0;
+          } else if (argType1.getCollation().equals(pickedCollation)) {
+            pickedType = argType1;
+          } else {
+            throw new AssertionError("should never come here");
           }
-          return ret;
+          ret =
+              typeFactory.createTypeWithCharsetAndCollation(ret,
+                  pickedType.getCharset(), pickedType.getCollation());
         }
+        return ret;
       };
 
   /**
@@ -663,88 +636,72 @@ public abstract class ReturnTypes {
    * as a {@link org.apache.calcite.sql.validate.SqlValidatorNamespace}, and
    * therefore the result type of the call is the type of that namespace.
    */
-  public static final SqlReturnTypeInference SCOPE =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          SqlCallBinding callBinding = (SqlCallBinding) opBinding;
-          return callBinding.getValidator().getNamespace(
-              callBinding.getCall()).getRowType();
-        }
-      };
+  public static final SqlReturnTypeInference SCOPE = opBinding -> {
+    SqlCallBinding callBinding = (SqlCallBinding) opBinding;
+    return callBinding.getValidator().getNamespace(
+        callBinding.getCall()).getRowType();
+  };
 
   /**
    * Returns a multiset of column #0 of a multiset. For example, given
    * <code>RECORD(x INTEGER, y DATE) MULTISET</code>, returns <code>INTEGER
    * MULTISET</code>.
    */
-  public static final SqlReturnTypeInference MULTISET_PROJECT0 =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          assert opBinding.getOperandCount() == 1;
-          final RelDataType recordMultisetType =
-              opBinding.getOperandType(0);
-          RelDataType multisetType =
-              recordMultisetType.getComponentType();
-          assert multisetType != null : "expected a multiset type: "
-              + recordMultisetType;
-          final List<RelDataTypeField> fields =
-              multisetType.getFieldList();
-          assert fields.size() > 0;
-          final RelDataType firstColType = fields.get(0).getType();
-          return opBinding.getTypeFactory().createMultisetType(
-              firstColType,
-              -1);
-        }
-      };
+  public static final SqlReturnTypeInference MULTISET_PROJECT0 = opBinding -> {
+    assert opBinding.getOperandCount() == 1;
+    final RelDataType recordMultisetType =
+        opBinding.getOperandType(0);
+    RelDataType multisetType =
+        recordMultisetType.getComponentType();
+    assert multisetType != null : "expected a multiset type: "
+        + recordMultisetType;
+    final List<RelDataTypeField> fields =
+        multisetType.getFieldList();
+    assert fields.size() > 0;
+    final RelDataType firstColType = fields.get(0).getType();
+    return opBinding.getTypeFactory().createMultisetType(
+        firstColType,
+        -1);
+  };
   /**
    * Returns a multiset of the first column of a multiset. For example, given
    * <code>INTEGER MULTISET</code>, returns <code>RECORD(x INTEGER)
    * MULTISET</code>.
    */
-  public static final SqlReturnTypeInference MULTISET_RECORD =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          assert opBinding.getOperandCount() == 1;
-          final RelDataType multisetType = opBinding.getOperandType(0);
-          RelDataType componentType = multisetType.getComponentType();
-          assert componentType != null : "expected a multiset type: "
-              + multisetType;
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          final RelDataType type = typeFactory.builder()
-              .add(SqlUtil.deriveAliasFromOrdinal(0), componentType).build();
-          return typeFactory.createMultisetType(type, -1);
-        }
-      };
+  public static final SqlReturnTypeInference MULTISET_RECORD = opBinding -> {
+    assert opBinding.getOperandCount() == 1;
+    final RelDataType multisetType = opBinding.getOperandType(0);
+    RelDataType componentType = multisetType.getComponentType();
+    assert componentType != null : "expected a multiset type: "
+        + multisetType;
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    final RelDataType type = typeFactory.builder()
+        .add(SqlUtil.deriveAliasFromOrdinal(0), componentType).build();
+    return typeFactory.createMultisetType(type, -1);
+  };
   /**
    * Returns the field type of a structured type which has only one field. For
    * example, given {@code RECORD(x INTEGER)} returns {@code INTEGER}.
    */
-  public static final SqlReturnTypeInference RECORD_TO_SCALAR =
-      new SqlReturnTypeInference() {
-        public RelDataType inferReturnType(
-            SqlOperatorBinding opBinding) {
-          assert opBinding.getOperandCount() == 1;
+  public static final SqlReturnTypeInference RECORD_TO_SCALAR = opBinding -> {
+    assert opBinding.getOperandCount() == 1;
 
-          final RelDataType recordType = opBinding.getOperandType(0);
+    final RelDataType recordType = opBinding.getOperandType(0);
 
-          boolean isStruct = recordType.isStruct();
-          int fieldCount = recordType.getFieldCount();
+    boolean isStruct = recordType.isStruct();
+    int fieldCount = recordType.getFieldCount();
 
-          assert isStruct && (fieldCount == 1);
+    assert isStruct && (fieldCount == 1);
 
-          RelDataTypeField fieldType = recordType.getFieldList().get(0);
-          assert fieldType != null
-              : "expected a record type with one field: "
-              + recordType;
-          final RelDataType firstColType = fieldType.getType();
-          return opBinding.getTypeFactory().createTypeWithNullability(
-              firstColType,
-              true);
-        }
-      };
+    RelDataTypeField fieldType = recordType.getFieldList().get(0);
+    assert fieldType != null
+        : "expected a record type with one field: "
+        + recordType;
+    final RelDataType firstColType = fieldType.getType();
+    return opBinding.getTypeFactory().createTypeWithNullability(
+        firstColType,
+        true);
+  };
 
   /**
    * Type-inference strategy for SUM aggregate function inferred from the
@@ -753,20 +710,16 @@ public abstract class ReturnTypes {
    * with the default implementation of RelDataTypeSystem, s has the same
    * type name as x.
    */
-  public static final SqlReturnTypeInference AGG_SUM =
-      new SqlReturnTypeInference() {
-        @Override public RelDataType
-        inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          final RelDataType type = typeFactory.getTypeSystem()
-              .deriveSumType(typeFactory, opBinding.getOperandType(0));
-          if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
-            return typeFactory.createTypeWithNullability(type, true);
-          } else {
-            return type;
-          }
-        }
-      };
+  public static final SqlReturnTypeInference AGG_SUM = opBinding -> {
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    final RelDataType type = typeFactory.getTypeSystem()
+        .deriveSumType(typeFactory, opBinding.getOperandType(0));
+    if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
+      return typeFactory.createTypeWithNullability(type, true);
+    } else {
+      return type;
+    }
+  };
 
   /**
    * Type-inference strategy for $SUM0 aggregate function inferred from the
@@ -775,72 +728,55 @@ public abstract class ReturnTypes {
    * x.
    */
   public static final SqlReturnTypeInference AGG_SUM_EMPTY_IS_ZERO =
-      new SqlReturnTypeInference() {
-        @Override public RelDataType
-        inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          final RelDataType sumType = typeFactory.getTypeSystem()
-              .deriveSumType(typeFactory, opBinding.getOperandType(0));
-          // SUM0 should not return null.
-          return typeFactory.createTypeWithNullability(sumType, false);
-        }
+      opBinding -> {
+        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+        final RelDataType sumType = typeFactory.getTypeSystem()
+            .deriveSumType(typeFactory, opBinding.getOperandType(0));
+        // SUM0 should not return null.
+        return typeFactory.createTypeWithNullability(sumType, false);
       };
 
   /**
    * Type-inference strategy for the {@code CUME_DIST} and {@code PERCENT_RANK}
    * aggregate functions.
    */
-  public static final SqlReturnTypeInference FRACTIONAL_RANK =
-      new SqlReturnTypeInference() {
-        @Override public RelDataType
-        inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          return typeFactory.getTypeSystem().deriveFractionalRankType(typeFactory);
-        }
-      };
+  public static final SqlReturnTypeInference FRACTIONAL_RANK = opBinding -> {
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    return typeFactory.getTypeSystem().deriveFractionalRankType(typeFactory);
+  };
 
   /**
    * Type-inference strategy for the {@code NTILE}, {@code RANK},
    * {@code DENSE_RANK}, and {@code ROW_NUMBER} aggregate functions.
    */
-  public static final SqlReturnTypeInference RANK =
-      new SqlReturnTypeInference() {
-        @Override public RelDataType
-        inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          return typeFactory.getTypeSystem().deriveRankType(typeFactory);
-        }
-      };
-
-  public static final SqlReturnTypeInference AVG_AGG_FUNCTION =
-      new SqlReturnTypeInference() {
-        @Override public RelDataType
-        inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          final RelDataType relDataType = typeFactory.getTypeSystem().deriveAvgAggType(
-              typeFactory, opBinding.getOperandType(0));
-          if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
-            return typeFactory.createTypeWithNullability(relDataType, true);
-          } else {
-            return relDataType;
-          }
-        }
-      };
-
-  public static final SqlReturnTypeInference COVAR_FUNCTION =
-      new SqlReturnTypeInference() {
-        @Override public RelDataType
-        inferReturnType(SqlOperatorBinding opBinding) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          final RelDataType relDataType = typeFactory.getTypeSystem().deriveCovarType(
-              typeFactory, opBinding.getOperandType(0), opBinding.getOperandType(1));
-          if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
-            return typeFactory.createTypeWithNullability(relDataType, true);
-          } else {
-            return relDataType;
-          }
-        }
-      };
+  public static final SqlReturnTypeInference RANK = opBinding -> {
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    return typeFactory.getTypeSystem().deriveRankType(typeFactory);
+  };
+
+  public static final SqlReturnTypeInference AVG_AGG_FUNCTION = opBinding -> {
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    final RelDataType relDataType =
+        typeFactory.getTypeSystem().deriveAvgAggType(typeFactory,
+            opBinding.getOperandType(0));
+    if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
+      return typeFactory.createTypeWithNullability(relDataType, true);
+    } else {
+      return relDataType;
+    }
+  };
+
+  public static final SqlReturnTypeInference COVAR_FUNCTION = opBinding -> {
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    final RelDataType relDataType =
+        typeFactory.getTypeSystem().deriveCovarType(typeFactory,
+            opBinding.getOperandType(0), opBinding.getOperandType(1));
+    if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
+      return typeFactory.createTypeWithNullability(relDataType, true);
+    } else {
+      return relDataType;
+    }
+  };
 }
 
 // End ReturnTypes.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/SqlTypeAssignmentRules.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeAssignmentRules.java b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeAssignmentRules.java
index 038ead3..77f11fa 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeAssignmentRules.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeAssignmentRules.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.sql.type;
 
-import com.google.common.base.Preconditions;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
@@ -28,9 +27,9 @@ import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import javax.annotation.Nonnull;
 
 /**
  * Rules that determine whether a type is assignable from another type.
@@ -371,8 +370,8 @@ public class SqlTypeAssignmentRules {
   public boolean canCastFrom(
       SqlTypeName to,
       SqlTypeName from) {
-    Preconditions.checkNotNull(to);
-    Preconditions.checkNotNull(from);
+    Objects.requireNonNull(to);
+    Objects.requireNonNull(from);
 
     if (to == SqlTypeName.NULL) {
       return false;
@@ -400,13 +399,8 @@ public class SqlTypeAssignmentRules {
     Builder() {
       this.map = new HashMap<>();
       this.sets =
-          CacheBuilder.newBuilder().build(
-              new CacheLoader<Set<SqlTypeName>, ImmutableSet<SqlTypeName>>() {
-                public ImmutableSet<SqlTypeName> load(
-                    @Nonnull Set<SqlTypeName> key) {
-                  return Sets.immutableEnumSet(key);
-                }
-              });
+          CacheBuilder.newBuilder()
+              .build(CacheLoader.from(set -> Sets.immutableEnumSet(set)));
     }
 
     /** Creates a Builder as a copy of another Builder. */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
index 0ff8525..81efd2b 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
@@ -22,9 +22,8 @@ import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.sql.SqlOperatorBinding;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 /**
  * SqlTypeTransforms defines a number of reusable instances of
@@ -44,78 +43,53 @@ public abstract class SqlTypeTransforms {
    * nullable
    */
   public static final SqlTypeTransform TO_NULLABLE =
-      new SqlTypeTransform() {
-        public RelDataType transformType(
-            SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          return SqlTypeUtil.makeNullableIfOperandsAre(
-              opBinding.getTypeFactory(),
+      (opBinding, typeToTransform) ->
+          SqlTypeUtil.makeNullableIfOperandsAre(opBinding.getTypeFactory(),
               opBinding.collectOperandTypes(),
-              Preconditions.checkNotNull(typeToTransform));
-        }
-      };
+              Objects.requireNonNull(typeToTransform));
 
   /**
    * Parameter type-inference transform strategy where a derived type is
    * transformed into the same type, but nullable if and only if all of a call's
    * operands are nullable.
    */
-  public static final SqlTypeTransform TO_NULLABLE_ALL =
-      new SqlTypeTransform() {
-        public RelDataType transformType(SqlOperatorBinding opBinding,
-            RelDataType type) {
-          final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
-          return typeFactory.createTypeWithNullability(type,
-              SqlTypeUtil.allNullable(opBinding.collectOperandTypes()));
-        }
-      };
+  public static final SqlTypeTransform TO_NULLABLE_ALL = (opBinding, type) -> {
+    final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+    return typeFactory.createTypeWithNullability(type,
+        SqlTypeUtil.allNullable(opBinding.collectOperandTypes()));
+  };
 
   /**
    * Parameter type-inference transform strategy where a derived type is
    * transformed into the same type but not nullable.
    */
   public static final SqlTypeTransform TO_NOT_NULLABLE =
-      new SqlTypeTransform() {
-        public RelDataType transformType(
-            SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          return opBinding.getTypeFactory().createTypeWithNullability(
-              Preconditions.checkNotNull(typeToTransform),
-              false);
-        }
-      };
+      (opBinding, typeToTransform) ->
+          opBinding.getTypeFactory().createTypeWithNullability(
+              Objects.requireNonNull(typeToTransform), false);
 
   /**
    * Parameter type-inference transform strategy where a derived type is
    * transformed into the same type with nulls allowed.
    */
   public static final SqlTypeTransform FORCE_NULLABLE =
-      new SqlTypeTransform() {
-        public RelDataType transformType(
-            SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          return opBinding.getTypeFactory().createTypeWithNullability(
-              Preconditions.checkNotNull(typeToTransform),
-              true);
-        }
-      };
+      (opBinding, typeToTransform) ->
+          opBinding.getTypeFactory().createTypeWithNullability(
+              Objects.requireNonNull(typeToTransform), true);
 
   /**
    * Type-inference strategy whereby the result is NOT NULL if any of
    * the arguments is NOT NULL; otherwise the type is unchanged.
    */
   public static final SqlTypeTransform LEAST_NULLABLE =
-      new SqlTypeTransform() {
-        public RelDataType transformType(SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          for (RelDataType type : opBinding.collectOperandTypes()) {
-            if (!type.isNullable()) {
-              return opBinding.getTypeFactory()
-                  .createTypeWithNullability(typeToTransform, false);
-            }
+      (opBinding, typeToTransform) -> {
+        for (RelDataType type : opBinding.collectOperandTypes()) {
+          if (!type.isNullable()) {
+            return opBinding.getTypeFactory()
+                .createTypeWithNullability(typeToTransform, false);
           }
-          return typeToTransform;
         }
+        return typeToTransform;
       };
 
   /**
@@ -176,13 +150,7 @@ public abstract class SqlTypeTransforms {
    * @see MultisetSqlType#getComponentType
    */
   public static final SqlTypeTransform TO_MULTISET_ELEMENT_TYPE =
-      new SqlTypeTransform() {
-        public RelDataType transformType(
-            SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          return typeToTransform.getComponentType();
-        }
-      };
+      (opBinding, typeToTransform) -> typeToTransform.getComponentType();
 
   /**
    * Parameter type-inference transform strategy that wraps a given type
@@ -191,13 +159,8 @@ public abstract class SqlTypeTransforms {
    * @see org.apache.calcite.rel.type.RelDataTypeFactory#createMultisetType(RelDataType, long)
    */
   public static final SqlTypeTransform TO_MULTISET =
-      new SqlTypeTransform() {
-        public RelDataType transformType(SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          return opBinding.getTypeFactory().createMultisetType(typeToTransform,
-              -1);
-        }
-      };
+      (opBinding, typeToTransform) ->
+          opBinding.getTypeFactory().createMultisetType(typeToTransform, -1);
 
   /**
    * Parameter type-inference transform strategy where a derived type must be
@@ -205,15 +168,10 @@ public abstract class SqlTypeTransforms {
    * of that field.
    */
   public static final SqlTypeTransform ONLY_COLUMN =
-      new SqlTypeTransform() {
-        public RelDataType transformType(
-            SqlOperatorBinding opBinding,
-            RelDataType typeToTransform) {
-          final List<RelDataTypeField> fields =
-              typeToTransform.getFieldList();
-          assert fields.size() == 1;
-          return fields.get(0).getType();
-        }
+      (opBinding, typeToTransform) -> {
+        final List<RelDataTypeField> fields = typeToTransform.getFieldList();
+        assert fields.size() == 1;
+        return fields.get(0).getType();
       };
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java
index 5b3ddab..c774c61 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java
@@ -36,9 +36,7 @@ import org.apache.calcite.util.NumberUtil;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
 import java.nio.charset.Charset;
@@ -46,6 +44,7 @@ import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -66,7 +65,7 @@ public abstract class SqlTypeUtil {
     assert argTypes.size() >= 2;
 
     // Filter out ANY elements.
-    List<RelDataType> argTypes2 = Lists.newArrayList();
+    List<RelDataType> argTypes2 = new ArrayList<>();
     for (RelDataType t : argTypes) {
       if (!isAny(t)) {
         argTypes2.add(t);
@@ -202,7 +201,7 @@ public abstract class SqlTypeUtil {
       final RelDataTypeFactory typeFactory,
       final List<RelDataType> argTypes,
       RelDataType type) {
-    Preconditions.checkNotNull(type);
+    Objects.requireNonNull(type);
     if (containsNullable(argTypes)) {
       type = typeFactory.createTypeWithNullability(type, true);
     }
@@ -1183,8 +1182,8 @@ public abstract class SqlTypeUtil {
   public static RelDataType createEmptyStructType(
       RelDataTypeFactory typeFactory) {
     return typeFactory.createStructType(
-        ImmutableList.<RelDataType>of(),
-        ImmutableList.<String>of());
+        ImmutableList.of(),
+        ImmutableList.of());
   }
 
   /** Returns whether a type is flat. It is not flat if it is a record type that

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/util/SqlShuttle.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/util/SqlShuttle.java b/core/src/main/java/org/apache/calcite/sql/util/SqlShuttle.java
index c4e6f67..064883b 100644
--- a/core/src/main/java/org/apache/calcite/sql/util/SqlShuttle.java
+++ b/core/src/main/java/org/apache/calcite/sql/util/SqlShuttle.java
@@ -108,7 +108,7 @@ public class SqlShuttle extends SqlBasicVisitor<SqlNode> {
       this.call = call;
       this.update = false;
       final List<SqlNode> operands = call.getOperandList();
-      this.clonedOperands = operands.toArray(new SqlNode[operands.size()]);
+      this.clonedOperands = operands.toArray(new SqlNode[0]);
       this.alwaysCopy = alwaysCopy;
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java b/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
index cf45da2..a00a523 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
@@ -209,7 +209,7 @@ class AggChecker extends SqlBasicVisitor<Void> {
 
     // Visit the operands (only expressions).
     call.getOperator()
-        .acceptCall(this, call, true, ArgHandlerImpl.<Void>instance());
+        .acceptCall(this, call, true, ArgHandlerImpl.instance());
 
     // Restore scope.
     scopes.pop();

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/AggVisitor.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AggVisitor.java b/core/src/main/java/org/apache/calcite/sql/validate/AggVisitor.java
index 3bbd16d..44dfcfa 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/AggVisitor.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/AggVisitor.java
@@ -25,8 +25,7 @@ import org.apache.calcite.sql.SqlSyntax;
 import org.apache.calcite.sql.fun.SqlAbstractGroupFunction;
 import org.apache.calcite.sql.util.SqlBasicVisitor;
 
-import com.google.common.collect.Lists;
-
+import java.util.ArrayList;
 import java.util.List;
 
 /** Visitor that can find aggregate and windowed aggregate functions.
@@ -82,7 +81,7 @@ abstract class AggVisitor extends SqlBasicVisitor<Void> {
     if (operator instanceof SqlFunction) {
       final SqlFunction sqlFunction = (SqlFunction) operator;
       if (sqlFunction.getFunctionType().isUserDefinedNotSpecificFunction()) {
-        final List<SqlOperator> list = Lists.newArrayList();
+        final List<SqlOperator> list = new ArrayList<>();
         opTab.lookupOperatorOverloads(sqlFunction.getSqlIdentifier(),
             sqlFunction.getFunctionType(), SqlSyntax.FUNCTION, list);
         for (SqlOperator operator2 : list) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java b/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
index 5df9374..5c23e1d 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
@@ -27,7 +27,6 @@ import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Supplier;
 import com.google.common.base.Suppliers;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -37,6 +36,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Supplier;
 
 import static org.apache.calcite.sql.SqlUtil.stripAs;
 
@@ -58,18 +58,15 @@ public class AggregatingSelectScope
   private List<SqlNode> temporaryGroupExprList;
 
   public final Supplier<Resolved> resolved =
-      Suppliers.memoize(
-          new Supplier<Resolved>() {
-            public Resolved get() {
-              assert temporaryGroupExprList == null;
-              temporaryGroupExprList = new ArrayList<>();
-              try {
-                return resolve();
-              } finally {
-                temporaryGroupExprList = null;
-              }
-            }
-          });
+      Suppliers.memoize(() -> {
+        assert temporaryGroupExprList == null;
+        temporaryGroupExprList = new ArrayList<>();
+        try {
+          return resolve();
+        } finally {
+          temporaryGroupExprList = null;
+        }
+      })::get;
 
   //~ Constructors -----------------------------------------------------------
 
@@ -149,18 +146,18 @@ public class AggregatingSelectScope
       for (SqlNode selectItem : selectScope.getExpandedSelectList()) {
         groupExprs.add(stripAs(selectItem));
       }
-      return Pair.of(ImmutableList.<SqlNode>of(), groupExprs.build());
+      return Pair.of(ImmutableList.of(), groupExprs.build());
     } else if (select.getGroup() != null) {
       if (temporaryGroupExprList != null) {
         // we are in the middle of resolving
-        return Pair.of(ImmutableList.<SqlNode>of(),
+        return Pair.of(ImmutableList.of(),
             ImmutableList.copyOf(temporaryGroupExprList));
       } else {
         final Resolved resolved = this.resolved.get();
         return Pair.of(resolved.extraExprList, resolved.groupExprList);
       }
     } else {
-      return Pair.of(ImmutableList.<SqlNode>of(), ImmutableList.<SqlNode>of());
+      return Pair.of(ImmutableList.of(), ImmutableList.of());
     }
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/CatalogScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/CatalogScope.java b/core/src/main/java/org/apache/calcite/sql/validate/CatalogScope.java
index 1420123..44cee30 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/CatalogScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/CatalogScope.java
@@ -17,13 +17,11 @@
 package org.apache.calcite.sql.validate;
 
 import org.apache.calcite.linq4j.Linq4j;
-import org.apache.calcite.linq4j.function.Function1;
-import org.apache.calcite.linq4j.function.Predicate1;
 import org.apache.calcite.sql.SqlNode;
 
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
 
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
@@ -51,20 +49,10 @@ class CatalogScope extends DelegatingScope {
     this.schemaNames =
         Linq4j.asEnumerable(
             validator.getCatalogReader()
-                .getAllSchemaObjectNames(ImmutableList.<String>of()))
-            .where(
-                new Predicate1<SqlMoniker>() {
-                  public boolean apply(SqlMoniker input) {
-                    return input.getType() == SqlMonikerType.SCHEMA;
-                  }
-                })
-            .select(
-                new Function1<SqlMoniker, List<String>>() {
-                  public List<String> apply(SqlMoniker input) {
-                    return input.getFullyQualifiedNames();
-                  }
-                })
-            .into(Sets.<List<String>>newHashSet());
+                .getAllSchemaObjectNames(ImmutableList.of()))
+            .where(input -> input.getType() == SqlMonikerType.SCHEMA)
+            .select(SqlMoniker::getFullyQualifiedNames)
+            .into(new HashSet<>());
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/DelegatingScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/DelegatingScope.java b/core/src/main/java/org/apache/calcite/sql/validate/DelegatingScope.java
index b1b01d2..cf5d9d2 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/DelegatingScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/DelegatingScope.java
@@ -462,7 +462,7 @@ public abstract class DelegatingScope implements SqlValidatorScope {
                 return kind;
               }
             };
-        Collections.sort(resolved.resolves, c);
+        resolved.resolves.sort(c);
         if (c.compare(resolved.resolves.get(0), resolved.resolves.get(1)) == 0) {
           throw validator.newValidationError(suffix,
               RESOURCE.columnAmbiguous(suffix.toString()));

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/IdentifierNamespace.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/IdentifierNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/IdentifierNamespace.java
index e3395db..8546742 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/IdentifierNamespace.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/IdentifierNamespace.java
@@ -25,12 +25,12 @@ import org.apache.calcite.sql.SqlNodeList;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 import javax.annotation.Nullable;
 
 import static org.apache.calcite.util.Static.RESOURCE;
@@ -74,7 +74,7 @@ public class IdentifierNamespace extends AbstractNamespace {
     super(validator, enclosingNode);
     this.id = id;
     this.extendList = extendList;
-    this.parentScope = Preconditions.checkNotNull(parentScope);
+    this.parentScope = Objects.requireNonNull(parentScope);
   }
 
   IdentifierNamespace(SqlValidatorImpl validator, SqlNode node,
@@ -174,7 +174,7 @@ public class IdentifierNamespace extends AbstractNamespace {
   }
 
   public RelDataType validateImpl(RelDataType targetRowType) {
-    resolvedNamespace = Preconditions.checkNotNull(resolveImpl(id));
+    resolvedNamespace = Objects.requireNonNull(resolveImpl(id));
     if (resolvedNamespace instanceof TableNamespace) {
       SqlValidatorTable table = resolvedNamespace.getTable();
       if (validator.shouldExpandIdentifiers()) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/ListScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/ListScope.java b/core/src/main/java/org/apache/calcite/sql/validate/ListScope.java
index 3537e01..741481e 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/ListScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/ListScope.java
@@ -23,7 +23,6 @@ import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
@@ -32,6 +31,7 @@ import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -57,7 +57,7 @@ public abstract class ListScope extends DelegatingScope {
 
   @Override public void addChild(SqlValidatorNamespace ns, String alias,
       boolean nullable) {
-    Preconditions.checkNotNull(alias);
+    Objects.requireNonNull(alias);
     children.add(new ScopeChild(children.size(), alias, ns, nullable));
   }
 
@@ -67,7 +67,7 @@ public abstract class ListScope extends DelegatingScope {
    * @return list of child namespaces
    */
   public List<SqlValidatorNamespace> getChildren() {
-    return Lists.transform(children, ScopeChild.NAMESPACE_FN);
+    return Lists.transform(children, scopeChild -> scopeChild.namespace);
   }
 
   /**
@@ -76,7 +76,7 @@ public abstract class ListScope extends DelegatingScope {
    * @return list of child namespaces
    */
   List<String> getChildNames() {
-    return Lists.transform(children, ScopeChild.NAME_FN);
+    return Lists.transform(children, scopeChild -> scopeChild.name);
   }
 
   private ScopeChild findChild(List<String> names,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SchemaNamespace.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SchemaNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/SchemaNamespace.java
index ab0c4a3..4580aa9 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SchemaNamespace.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SchemaNamespace.java
@@ -21,10 +21,10 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
+import java.util.Objects;
 
 /** Namespace based on a schema.
  *
@@ -37,7 +37,7 @@ class SchemaNamespace extends AbstractNamespace {
   /** Creates a SchemaNamespace. */
   SchemaNamespace(SqlValidatorImpl validator, ImmutableList<String> names) {
     super(validator, null);
-    this.names = Preconditions.checkNotNull(names);
+    this.names = Objects.requireNonNull(names);
   }
 
   protected RelDataType validateImpl(RelDataType targetRowType) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/ScopeChild.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/ScopeChild.java b/core/src/main/java/org/apache/calcite/sql/validate/ScopeChild.java
index 2b210b4..b04f0e5 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/ScopeChild.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/ScopeChild.java
@@ -16,7 +16,6 @@
  */
 package org.apache.calcite.sql.validate;
 
-import com.google.common.base.Function;
 
 /** One of the inputs of a {@link SqlValidatorScope}.
  *
@@ -29,20 +28,6 @@ class ScopeChild {
   final SqlValidatorNamespace namespace;
   final boolean nullable;
 
-  static final Function<ScopeChild, SqlValidatorNamespace> NAMESPACE_FN =
-      new Function<ScopeChild, SqlValidatorNamespace>() {
-        public SqlValidatorNamespace apply(ScopeChild input) {
-          return input.namespace;
-        }
-      };
-
-  static final Function<ScopeChild, String> NAME_FN =
-      new Function<ScopeChild, String>() {
-        public String apply(ScopeChild input) {
-          return input.name;
-        }
-      };
-
   /** Creates a ScopeChild.
    *
    * @param ordinal Ordinal of child within parent scope

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlIdentifierMoniker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlIdentifierMoniker.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlIdentifierMoniker.java
index 29a75e0..39c8b8c 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlIdentifierMoniker.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlIdentifierMoniker.java
@@ -18,9 +18,8 @@ package org.apache.calcite.sql.validate;
 
 import org.apache.calcite.sql.SqlIdentifier;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 /**
  * An implementation of {@link SqlMoniker} that encapsulates the normalized name
@@ -37,7 +36,7 @@ public class SqlIdentifierMoniker implements SqlMoniker {
    * Creates an SqlIdentifierMoniker.
    */
   public SqlIdentifierMoniker(SqlIdentifier id) {
-    this.id = Preconditions.checkNotNull(id);
+    this.id = Objects.requireNonNull(id);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlMonikerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlMonikerImpl.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlMonikerImpl.java
index e2c5825..b802c4a 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlMonikerImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlMonikerImpl.java
@@ -20,7 +20,6 @@ import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 import java.util.List;
@@ -42,7 +41,7 @@ public class SqlMonikerImpl implements SqlMoniker {
    */
   public SqlMonikerImpl(List<String> names, SqlMonikerType type) {
     this.names = ImmutableList.copyOf(names);
-    this.type = Preconditions.checkNotNull(type);
+    this.type = Objects.requireNonNull(type);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedAggFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedAggFunction.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedAggFunction.java
index 68c954f..0cf8c0f 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedAggFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedAggFunction.java
@@ -33,7 +33,6 @@ import org.apache.calcite.sql.type.SqlReturnTypeInference;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
@@ -76,12 +75,7 @@ public class SqlUserDefinedAggFunction extends SqlAggFunction {
   }
 
   private List<RelDataType> toSql(List<RelDataType> types) {
-    return Lists.transform(types,
-        new com.google.common.base.Function<RelDataType, RelDataType>() {
-          public RelDataType apply(RelDataType type) {
-            return toSql(type);
-          }
-        });
+    return Lists.transform(types, this::toSql);
   }
 
   private RelDataType toSql(RelDataType type) {
@@ -98,11 +92,7 @@ public class SqlUserDefinedAggFunction extends SqlAggFunction {
   public List<RelDataType> getParameterTypes(
       final RelDataTypeFactory typeFactory) {
     return Lists.transform(function.getParameters(),
-        new Function<FunctionParameter, RelDataType>() {
-          public RelDataType apply(FunctionParameter input) {
-            return input.getType(typeFactory);
-          }
-        });
+        parameter -> parameter.getType(typeFactory));
   }
 
   @SuppressWarnings("deprecation")

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedFunction.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedFunction.java
index cc3ed3f..0c2c796 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedFunction.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedFunction.java
@@ -75,7 +75,8 @@ public class SqlUserDefinedFunction extends SqlFunction {
   }
 
   @Override public List<String> getParamNames() {
-    return Lists.transform(function.getParameters(), FunctionParameter.NAME_FN);
+    return Lists.transform(function.getParameters(),
+        FunctionParameter::getName);
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java
index 4f191ac..153ad2c 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java
@@ -21,7 +21,6 @@ import org.apache.calcite.linq4j.tree.BlockBuilder;
 import org.apache.calcite.linq4j.tree.Expression;
 import org.apache.calcite.linq4j.tree.Expressions;
 import org.apache.calcite.linq4j.tree.FunctionExpression;
-import org.apache.calcite.linq4j.tree.ParameterExpression;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeFactoryImpl;
@@ -45,13 +44,13 @@ import org.apache.calcite.util.NlsString;
 import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Lists;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 
 /**
  * User-defined table macro.
@@ -69,14 +68,14 @@ public class SqlUserDefinedTableMacro extends SqlFunction {
       TableMacro tableMacro) {
     super(Util.last(opName.names), opName, SqlKind.OTHER_FUNCTION,
         returnTypeInference, operandTypeInference, operandTypeChecker,
-        Preconditions.checkNotNull(paramTypes),
+        Objects.requireNonNull(paramTypes),
         SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION);
     this.tableMacro = tableMacro;
   }
 
   @Override public List<String> getParamNames() {
     return Lists.transform(tableMacro.getParameters(),
-        FunctionParameter.NAME_FN);
+        FunctionParameter::getName);
   }
 
   /** Returns the table in this UDF, or null if there is no table. */
@@ -133,7 +132,7 @@ public class SqlUserDefinedTableMacro extends SqlFunction {
   private static Object getValue(SqlNode right) throws NonLiteralException {
     switch (right.getKind()) {
     case ARRAY_VALUE_CONSTRUCTOR:
-      final List<Object> list = Lists.newArrayList();
+      final List<Object> list = new ArrayList<>();
       for (SqlNode o : ((SqlCall) right).getOperandList()) {
         list.add(getValue(o));
       }
@@ -188,8 +187,7 @@ public class SqlUserDefinedTableMacro extends SqlFunction {
         RexToLixTranslator.convert(Expressions.constant(o), clazz);
     bb.add(Expressions.return_(null, expr));
     final FunctionExpression convert =
-        Expressions.lambda(bb.toBlock(),
-            Collections.<ParameterExpression>emptyList());
+        Expressions.lambda(bb.toBlock(), Collections.emptyList());
     return convert.compile().dynamicInvoke();
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
index 0dd9308..71b4b76 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
@@ -102,10 +102,7 @@ import org.apache.calcite.util.Util;
 import org.apache.calcite.util.trace.CalciteTrace;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
@@ -130,7 +127,9 @@ import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
+import java.util.function.Supplier;
 
 import static org.apache.calcite.sql.SqlUtil.stripAs;
 import static org.apache.calcite.util.Static.RESOURCE;
@@ -298,10 +297,10 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       SqlValidatorCatalogReader catalogReader,
       RelDataTypeFactory typeFactory,
       SqlConformance conformance) {
-    this.opTab = Preconditions.checkNotNull(opTab);
-    this.catalogReader = Preconditions.checkNotNull(catalogReader);
-    this.typeFactory = Preconditions.checkNotNull(typeFactory);
-    this.conformance = Preconditions.checkNotNull(conformance);
+    this.opTab = Objects.requireNonNull(opTab);
+    this.catalogReader = Objects.requireNonNull(catalogReader);
+    this.typeFactory = Objects.requireNonNull(typeFactory);
+    this.conformance = Objects.requireNonNull(conformance);
 
     unknownType = typeFactory.createUnknownType();
     booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
@@ -533,7 +532,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
         }
       }
       // If NATURAL JOIN or USING is present, move key fields to the front of
-      // the list.
+      // the list, per standard SQL. Disabled if there are dynamic fields.
       if (!hasDynamicStruct || Bug.CALCITE_2400_FIXED) {
         new Permute(scope.getNode().getFrom(), 0).permute(selectItems, fields);
       }
@@ -1583,8 +1582,8 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
    */
   @SuppressWarnings("deprecation")
   public final void setValidatedNodeType(SqlNode node, RelDataType type) {
-    Preconditions.checkNotNull(type);
-    Preconditions.checkNotNull(node);
+    Objects.requireNonNull(type);
+    Objects.requireNonNull(node);
     if (type.equals(unknownType)) {
       // don't set anything until we know what it is, and don't overwrite
       // a known type with the unknown type
@@ -1600,8 +1599,8 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
   public RelDataType deriveType(
       SqlValidatorScope scope,
       SqlNode expr) {
-    Preconditions.checkNotNull(scope);
-    Preconditions.checkNotNull(expr);
+    Objects.requireNonNull(scope);
+    Objects.requireNonNull(expr);
 
     // if we already know the type, no need to re-derive
     RelDataType type = nodeToTypeMap.get(expr);
@@ -1628,9 +1627,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       SqlNode operand) {
     DeriveTypeVisitor v = new DeriveTypeVisitor(scope);
     final RelDataType type = operand.accept(v);
-    // After Guava 17, use Verify.verifyNotNull for Preconditions.checkNotNull
-    Bug.upgrade("guava-17");
-    return Preconditions.checkNotNull(scope.nullifyType(operand, type));
+    return Objects.requireNonNull(scope.nullifyType(operand, type));
   }
 
   public RelDataType deriveConstructorType(
@@ -1854,7 +1851,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
   }
 
   public void setDefaultNullCollation(NullCollation nullCollation) {
-    this.nullCollation = Preconditions.checkNotNull(nullCollation);
+    this.nullCollation = Objects.requireNonNull(nullCollation);
   }
 
   public NullCollation getDefaultNullCollation() {
@@ -2356,8 +2353,8 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       String alias,
       boolean forceNullable,
       boolean checkUpdate) {
-    Preconditions.checkNotNull(node);
-    Preconditions.checkNotNull(enclosingNode);
+    Objects.requireNonNull(node);
+    Objects.requireNonNull(enclosingNode);
     Preconditions.checkArgument(usingScope == null || alias != null);
 
     SqlCall call;
@@ -3011,7 +3008,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       SqlNode node,
       RelDataType targetRowType,
       SqlValidatorScope scope) {
-    Preconditions.checkNotNull(targetRowType);
+    Objects.requireNonNull(targetRowType);
     switch (node.getKind()) {
     case AS:
       validateFrom(
@@ -3252,12 +3249,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     final SelectScope fromScope = (SelectScope) getFromScope(select);
     List<String> names = fromScope.getChildNames();
     if (!catalogReader.nameMatcher().isCaseSensitive()) {
-      names = Lists.transform(names,
-          new Function<String, String>() {
-            public String apply(String s) {
-              return s.toUpperCase(Locale.ROOT);
-            }
-          });
+      names = Lists.transform(names, s -> s.toUpperCase(Locale.ROOT));
     }
     final int duplicateAliasOrdinal = Util.firstDuplicate(names);
     if (duplicateAliasOrdinal >= 0) {
@@ -3581,7 +3573,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
 
         if (supportsModalityCount == 0) {
           if (fail) {
-            String inputs = Joiner.on(", ").join(scope.getChildNames());
+            String inputs = String.join(", ", scope.getChildNames());
             throw newValidationError(select,
                 Static.RESOURCE.cannotStreamResultsForNonStreamingInputs(inputs));
           } else {
@@ -3791,7 +3783,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       }
     }
     final SqlValidatorScope orderScope = getOrderScope(select);
-    Preconditions.checkNotNull(orderScope);
+    Objects.requireNonNull(orderScope);
 
     List<SqlNode> expandList = new ArrayList<>();
     for (SqlNode orderItem : orderList) {
@@ -4009,7 +4001,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     // Validate SELECT list. Expand terms of the form "*" or "TABLE.*".
     final SqlValidatorScope selectScope = getSelectScope(select);
     final List<SqlNode> expandedSelectItems = new ArrayList<>();
-    final Set<String> aliases = Sets.newHashSet();
+    final Set<String> aliases = new HashSet<>();
     final List<Map.Entry<String, RelDataType>> fieldList = new ArrayList<>();
 
     for (int i = 0; i < selectItems.size(); i++) {
@@ -5173,7 +5165,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       // "LOCALTIME", which would have been handled as a
       // SqlIdentifier.)
       throw handleUnresolvedFunction(call, (SqlFunction) operator,
-          ImmutableList.<RelDataType>of(), null);
+          ImmutableList.of(), null);
     }
 
     SqlValidatorScope operandScope = scope.getOperandScope(call);
@@ -5361,7 +5353,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     InsertNamespace(SqlValidatorImpl validator, SqlInsert node,
         SqlNode enclosingNode, SqlValidatorScope parentScope) {
       super(validator, node.getTargetTable(), enclosingNode, parentScope);
-      this.node = Preconditions.checkNotNull(node);
+      this.node = Objects.requireNonNull(node);
     }
 
     public SqlInsert getNode() {
@@ -5378,7 +5370,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     UpdateNamespace(SqlValidatorImpl validator, SqlUpdate node,
         SqlNode enclosingNode, SqlValidatorScope parentScope) {
       super(validator, node.getTargetTable(), enclosingNode, parentScope);
-      this.node = Preconditions.checkNotNull(node);
+      this.node = Objects.requireNonNull(node);
     }
 
     public SqlUpdate getNode() {
@@ -5395,7 +5387,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     DeleteNamespace(SqlValidatorImpl validator, SqlDelete node,
         SqlNode enclosingNode, SqlValidatorScope parentScope) {
       super(validator, node.getTargetTable(), enclosingNode, parentScope);
-      this.node = Preconditions.checkNotNull(node);
+      this.node = Objects.requireNonNull(node);
     }
 
     public SqlDelete getNode() {
@@ -5412,7 +5404,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     MergeNamespace(SqlValidatorImpl validator, SqlMerge node,
         SqlNode enclosingNode, SqlValidatorScope parentScope) {
       super(validator, node.getTargetTable(), enclosingNode, parentScope);
-      this.node = Preconditions.checkNotNull(node);
+      this.node = Objects.requireNonNull(node);
     }
 
     public SqlMerge getNode() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorScope.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorScope.java
index 21c1a5a..98a32dc 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorScope.java
@@ -26,8 +26,6 @@ import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.sql.SqlWindow;
 import org.apache.calcite.util.Pair;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
@@ -36,6 +34,7 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Name-resolution scope. Represents any position in a parse tree than an
@@ -241,12 +240,7 @@ public interface SqlValidatorScope {
 
     /** Returns a list ["step1", "step2"]. */
     List<String> stepNames() {
-      return Lists.transform(steps(),
-          new Function<Step, String>() {
-            public String apply(Step input) {
-              return input.name;
-            }
-          });
+      return Lists.transform(steps(), input -> input.name);
     }
 
     protected void build(ImmutableList.Builder<Step> paths) {
@@ -271,11 +265,11 @@ public interface SqlValidatorScope {
 
     Step(Path parent, RelDataType rowType, int i, String name,
         StructKind kind) {
-      this.parent = Preconditions.checkNotNull(parent);
+      this.parent = Objects.requireNonNull(parent);
       this.rowType = rowType; // may be null
       this.i = i;
       this.name = name;
-      this.kind = Preconditions.checkNotNull(kind);
+      this.kind = Objects.requireNonNull(kind);
     }
 
     @Override public int stepCount() {
@@ -332,12 +326,12 @@ public interface SqlValidatorScope {
 
     Resolve(SqlValidatorNamespace namespace, boolean nullable,
         SqlValidatorScope scope, Path path, List<String> remainingNames) {
-      this.namespace = Preconditions.checkNotNull(namespace);
+      this.namespace = Objects.requireNonNull(namespace);
       this.nullable = nullable;
       this.scope = scope;
       assert !(scope instanceof TableScope);
-      this.path = Preconditions.checkNotNull(path);
-      this.remainingNames = remainingNames == null ? ImmutableList.<String>of()
+      this.path = Objects.requireNonNull(path);
+      this.remainingNames = remainingNames == null ? ImmutableList.of()
           : ImmutableList.copyOf(remainingNames);
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
index 092daf9..87b8f15 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
@@ -49,12 +49,10 @@ import org.apache.calcite.util.Pair;
 import org.apache.calcite.util.Util;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
 
 import java.nio.charset.Charset;
 import java.util.ArrayList;
@@ -108,7 +106,7 @@ public class SqlValidatorUtil {
         final SqlValidatorTable validatorTable = tableNamespace.getTable();
         final RelDataTypeFactory typeFactory = catalogReader.getTypeFactory();
         final List<RelDataTypeField> extendedFields = dmlNamespace.extendList == null
-            ? ImmutableList.<RelDataTypeField>of()
+            ? ImmutableList.of()
             : getExtendedColumns(typeFactory, validatorTable, dmlNamespace.extendList);
         return getRelOptTable(
             tableNamespace, catalogReader, datasetName, usedDataset, extendedFields);
@@ -218,9 +216,8 @@ public class SqlValidatorUtil {
       RelDataType sourceRowType,
       Map<Integer, RelDataTypeField> indexToField) {
     ImmutableBitSet source = ImmutableBitSet.of(
-        Lists.transform(
-            sourceRowType.getFieldList(),
-            new RelDataTypeField.ToFieldIndex()));
+        Lists.transform(sourceRowType.getFieldList(),
+            RelDataTypeField::getIndex));
     ImmutableBitSet target =
         ImmutableBitSet.of(indexToField.keySet());
     return source.intersect(target);
@@ -268,11 +265,7 @@ public class SqlValidatorUtil {
   static void checkIdentifierListForDuplicates(List<SqlNode> columnList,
       SqlValidatorImpl.ValidationErrorFunction validationErrorFunction) {
     final List<List<String>> names = Lists.transform(columnList,
-        new Function<SqlNode, List<String>>() {
-          public List<String> apply(SqlNode o) {
-            return ((SqlIdentifier) o).names;
-          }
-        });
+        o -> ((SqlIdentifier) o).names);
     final int i = Util.firstDuplicate(names);
     if (i >= 0) {
       throw validationErrorFunction.apply(columnList.get(i),
@@ -444,7 +437,7 @@ public class SqlValidatorUtil {
       Suggester suggester,
       boolean caseSensitive) {
     final Set<String> used = caseSensitive
-        ? new LinkedHashSet<String>()
+        ? new LinkedHashSet<>()
         : new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
     int changeCount = 0;
     final List<String> newNameList = new ArrayList<>();
@@ -539,7 +532,7 @@ public class SqlValidatorUtil {
     // doing a contains() on a list can be expensive.
     final Set<String> uniqueNameList =
         typeFactory.getTypeSystem().isSchemaCaseSensitive()
-            ? new HashSet<String>()
+            ? new HashSet<>()
             : new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
     addFields(systemFieldList, typeList, nameList, uniqueNameList);
     addFields(leftType.getFieldList(), typeList, nameList, uniqueNameList);
@@ -717,7 +710,7 @@ public class SqlValidatorUtil {
    * {@code topBuilder}. To find the grouping sets of the query, we will take
    * the cartesian product of the group sets. */
   public static void analyzeGroupItem(SqlValidatorScope scope,
-                                      GroupAnalyzer groupAnalyzer,
+      GroupAnalyzer groupAnalyzer,
       ImmutableList.Builder<ImmutableList<ImmutableBitSet>> topBuilder,
       SqlNode groupExpr) {
     final ImmutableList.Builder<ImmutableBitSet> builder;
@@ -811,7 +804,7 @@ public class SqlValidatorUtil {
    * is grouping. */
   private static List<ImmutableBitSet> analyzeGroupTuple(SqlValidatorScope scope,
        GroupAnalyzer groupAnalyzer, List<SqlNode> operandList) {
-    List<ImmutableBitSet> list = Lists.newArrayList();
+    List<ImmutableBitSet> list = new ArrayList<>();
     for (SqlNode operand : operandList) {
       list.add(
           analyzeGroupExpr(scope, groupAnalyzer, operand));
@@ -915,7 +908,7 @@ public class SqlValidatorUtil {
   @VisibleForTesting
   public static ImmutableList<ImmutableBitSet> rollup(
       List<ImmutableBitSet> bitSets) {
-    Set<ImmutableBitSet> builder = Sets.newLinkedHashSet();
+    Set<ImmutableBitSet> builder = new LinkedHashSet<>();
     for (;;) {
       final ImmutableBitSet union = ImmutableBitSet.union(bitSets);
       builder.add(union);
@@ -940,11 +933,11 @@ public class SqlValidatorUtil {
       List<ImmutableBitSet> bitSets) {
     // Given the bit sets [{1}, {2, 3}, {5}],
     // form the lists [[{1}, {}], [{2, 3}, {}], [{5}, {}]].
-    final Set<List<ImmutableBitSet>> builder = Sets.newLinkedHashSet();
+    final Set<List<ImmutableBitSet>> builder = new LinkedHashSet<>();
     for (ImmutableBitSet bitSet : bitSets) {
       builder.add(Arrays.asList(bitSet, ImmutableBitSet.of()));
     }
-    Set<ImmutableBitSet> flattenedBitSets = Sets.newLinkedHashSet();
+    Set<ImmutableBitSet> flattenedBitSets = new LinkedHashSet<>();
     for (List<ImmutableBitSet> o : Linq4j.product(builder)) {
       flattenedBitSets.add(ImmutableBitSet.union(o));
     }
@@ -1080,7 +1073,7 @@ public class SqlValidatorUtil {
   private static List<SqlValidatorNamespace> children(SqlValidatorScope scope) {
     return scope instanceof ListScope
         ? ((ListScope) scope).getChildren()
-        : ImmutableList.<SqlValidatorNamespace>of();
+        : ImmutableList.of();
   }
 
   /**
@@ -1168,18 +1161,11 @@ public class SqlValidatorUtil {
   }
 
   public static final Suggester EXPR_SUGGESTER =
-      new Suggester() {
-        public String apply(String original, int attempt, int size) {
-          return Util.first(original, "EXPR$") + attempt;
-        }
-      };
+      (original, attempt, size) -> Util.first(original, "EXPR$") + attempt;
 
   public static final Suggester F_SUGGESTER =
-      new Suggester() {
-        public String apply(String original, int attempt, int size) {
-          return Util.first(original, "$f") + Math.max(size, attempt);
-        }
-      };
+      (original, attempt, size) -> Util.first(original, "$f")
+          + Math.max(size, attempt);
 
   /** Builds a list of GROUP BY expressions. */
   static class GroupAnalyzer {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/TableNamespace.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/TableNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/TableNamespace.java
index 558ffa4..1417bdf 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/TableNamespace.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/TableNamespace.java
@@ -20,7 +20,6 @@ import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeField;
-import org.apache.calcite.runtime.PredicateImpl;
 import org.apache.calcite.schema.ExtensibleTable;
 import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.ModifiableViewTable;
@@ -29,13 +28,12 @@ import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlNodeList;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 import static org.apache.calcite.util.Static.RESOURCE;
 
@@ -48,12 +46,12 @@ class TableNamespace extends AbstractNamespace {
   private TableNamespace(SqlValidatorImpl validator, SqlValidatorTable table,
       List<RelDataTypeField> fields) {
     super(validator, null);
-    this.table = Preconditions.checkNotNull(table);
+    this.table = Objects.requireNonNull(table);
     this.extendedFields = ImmutableList.copyOf(fields);
   }
 
   TableNamespace(SqlValidatorImpl validator, SqlValidatorTable table) {
-    this(validator, table, ImmutableList.<RelDataTypeField>of());
+    this(validator, table, ImmutableList.of());
   }
 
   protected RelDataType validateImpl(RelDataType targetRowType) {
@@ -108,8 +106,7 @@ class TableNamespace extends AbstractNamespace {
           ((RelOptTable) table).extend(extendedFields);
       final SqlValidatorTable validatorTable =
           relOptTable.unwrap(SqlValidatorTable.class);
-      return new TableNamespace(
-          validator, validatorTable, ImmutableList.<RelDataTypeField>of());
+      return new TableNamespace(validator, validatorTable, ImmutableList.of());
     }
     return new TableNamespace(validator, table, extendedFields);
   }
@@ -151,17 +148,11 @@ class TableNamespace extends AbstractNamespace {
 
         if (!extType.equals(baseType)) {
           // Get the extended column node that failed validation.
-          final Predicate<SqlNode> nameMatches = new PredicateImpl<SqlNode>() {
-            @Override public boolean test(SqlNode sqlNode) {
-              if (sqlNode instanceof SqlIdentifier) {
-                final SqlIdentifier identifier = (SqlIdentifier) sqlNode;
-                return Util.last(identifier.names).equals(extendedField.getName());
-              }
-              return false;
-            }
-          };
           final SqlNode extColNode =
-              Iterables.find(extendList.getList(), nameMatches);
+              Iterables.find(extendList.getList(),
+                  sqlNode -> sqlNode instanceof SqlIdentifier
+                      && Util.last(((SqlIdentifier) sqlNode).names).equals(
+                          extendedField.getName()));
 
           throw validator.getValidationErrorFunction().apply(extColNode,
               RESOURCE.typeNotAssignable(

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/TableScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/TableScope.java b/core/src/main/java/org/apache/calcite/sql/validate/TableScope.java
index 89171c2..b43b1ee 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/TableScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/TableScope.java
@@ -19,7 +19,7 @@ package org.apache.calcite.sql.validate;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlSelect;
 
-import com.google.common.base.Preconditions;
+import java.util.Objects;
 
 /**
  * The name-resolution scope of a LATERAL TABLE clause.
@@ -40,8 +40,8 @@ class TableScope extends ListScope {
    * @param parent  Parent scope
    */
   TableScope(SqlValidatorScope parent, SqlNode node) {
-    super(Preconditions.checkNotNull(parent));
-    this.node = Preconditions.checkNotNull(node);
+    super(Objects.requireNonNull(parent));
+    this.node = Objects.requireNonNull(node);
   }
 
   //~ Methods ----------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/core/src/main/java/org/apache/calcite/sql/validate/UnnestNamespace.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/UnnestNamespace.java b/core/src/main/java/org/apache/calcite/sql/validate/UnnestNamespace.java
index 2f6c918..c946da8 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/UnnestNamespace.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/UnnestNamespace.java
@@ -22,7 +22,6 @@ import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlUnnestOperator;
 
-
 /**
  * Namespace for UNNEST.
  */


[06/30] calcite git commit: [CALCITE-2259] Allow Java 8 syntax

Posted by jh...@apache.org.
http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidExpressions.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidExpressions.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidExpressions.java
index bae6a4d..74d9c9c 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidExpressions.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidExpressions.java
@@ -26,7 +26,6 @@ import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.type.SqlTypeFamily;
 import org.apache.calcite.sql.type.SqlTypeName;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.io.BaseEncoding;
@@ -36,8 +35,8 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.TimeZone;
-
 import javax.annotation.Nullable;
 
 /**
@@ -189,13 +188,15 @@ public class DruidExpressions {
   }
 
   public static String functionCall(final String functionName, final List<String> args) {
-    Preconditions.checkNotNull(functionName, "druid functionName");
-    Preconditions.checkNotNull(args, "args");
+    Objects.requireNonNull(functionName, "druid functionName");
+    Objects.requireNonNull(args, "args");
 
     final StringBuilder builder = new StringBuilder(functionName);
     builder.append("(");
     for (int i = 0; i < args.size(); i++) {
-      final String arg = Preconditions.checkNotNull(args.get(i), "arg #%s", i);
+      int finalI = i;
+      final String arg = Objects.requireNonNull(args.get(i),
+          () -> "arg #" + finalI);
       builder.append(arg);
       if (i < args.size() - 1) {
         builder.append(",");
@@ -206,12 +207,14 @@ public class DruidExpressions {
   }
 
   public static String nAryOperatorCall(final String druidOperator, final List<String> args) {
-    Preconditions.checkNotNull(druidOperator, "druid operator missing");
-    Preconditions.checkNotNull(args, "args");
+    Objects.requireNonNull(druidOperator, "druid operator missing");
+    Objects.requireNonNull(args, "args");
     final StringBuilder builder = new StringBuilder();
     builder.append("(");
     for (int i = 0; i < args.size(); i++) {
-      final String arg = Preconditions.checkNotNull(args.get(i), "arg #%s", i);
+      int finalI = i;
+      final String arg = Objects.requireNonNull(args.get(i),
+          () -> "arg #" + finalI);
       builder.append(arg);
       if (i < args.size() - 1) {
         builder.append(druidOperator);
@@ -250,8 +253,8 @@ public class DruidExpressions {
       final String granularity,
       final String origin,
       final TimeZone timeZone) {
-    Preconditions.checkNotNull(input, "input");
-    Preconditions.checkNotNull(granularity, "granularity");
+    Objects.requireNonNull(input, "input");
+    Objects.requireNonNull(granularity, "granularity");
     return DruidExpressions.functionCall(
         "timestamp_floor",
         ImmutableList.of(input,
@@ -265,8 +268,8 @@ public class DruidExpressions {
       final String granularity,
       final String origin,
       final TimeZone timeZone) {
-    Preconditions.checkNotNull(input, "input");
-    Preconditions.checkNotNull(granularity, "granularity");
+    Objects.requireNonNull(input, "input");
+    Objects.requireNonNull(granularity, "granularity");
     return DruidExpressions.functionCall(
         "timestamp_ceil",
         ImmutableList.of(input,

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidJsonFilter.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidJsonFilter.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidJsonFilter.java
index cca9d6b..678be98 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidJsonFilter.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidJsonFilter.java
@@ -28,19 +28,17 @@ import org.apache.calcite.util.Pair;
 
 import com.fasterxml.jackson.core.JsonGenerator;
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 
 import java.io.IOException;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
-
+import java.util.Objects;
 import javax.annotation.Nullable;
 
-
 /**
  * Filter element of a Druid "groupBy" or "topN" query.
  */
@@ -386,7 +384,7 @@ abstract class DruidJsonFilter implements DruidJson {
     case OR:
     case NOT:
       final RexCall call = (RexCall) rexNode;
-      final List<DruidJsonFilter> jsonFilters = Lists.newArrayList();
+      final List<DruidJsonFilter> jsonFilters = new ArrayList<>();
       for (final RexNode e : call.getOperands()) {
         final DruidJsonFilter druidFilter = toDruidFilters(e, rowType, druidQuery);
         if (druidFilter == null) {
@@ -442,7 +440,7 @@ abstract class DruidJsonFilter implements DruidJson {
 
     JsonExpressionFilter(String expression) {
       super(Type.EXPRESSION);
-      this.expression = Preconditions.checkNotNull(expression);
+      this.expression = Objects.requireNonNull(expression);
     }
 
     @Override public void write(JsonGenerator generator) throws IOException {
@@ -609,7 +607,7 @@ abstract class DruidJsonFilter implements DruidJson {
 
   public static DruidJsonFilter getSelectorFilter(String column, String value,
       ExtractionFunction extractionFunction) {
-    Preconditions.checkNotNull(column);
+    Objects.requireNonNull(column);
     return new JsonSelector(column, value, extractionFunction);
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidQuery.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidQuery.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidQuery.java
index 611c722..cb69449 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidQuery.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidQuery.java
@@ -67,9 +67,6 @@ import org.apache.calcite.util.Util;
 
 import com.fasterxml.jackson.core.JsonFactory;
 import com.fasterxml.jackson.core.JsonGenerator;
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -91,6 +88,7 @@ import java.util.Set;
 import java.util.TimeZone;
 import java.util.regex.Pattern;
 
+import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 
 /**
@@ -188,8 +186,8 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
     this.druidTable = druidTable;
     this.intervals = ImmutableList.copyOf(intervals);
     this.rels = ImmutableList.copyOf(rels);
-    this.converterOperatorMap = Preconditions.checkNotNull(converterOperatorMap, "Operator map "
-        + "can not be null");
+    this.converterOperatorMap = Objects.requireNonNull(converterOperatorMap,
+        "Operator map can not be null");
     assert isValid(Litmus.THROW, null);
   }
 
@@ -798,7 +796,7 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
         }
       }
     }
-    return Pair.<List<String>, List<VirtualColumn>>of(projectedColumnsBuilder.build(),
+    return Pair.of(projectedColumnsBuilder.build(),
         virtualColumnsBuilder.build());
   }
 
@@ -1001,9 +999,7 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
       }
       final ScanQuery scanQuery = new ScanQuery(druidTable.dataSource, intervals, jsonFilter,
           virtualColumnList, scanColumnNames, fetch);
-      return new QuerySpec(QueryType.SCAN,
-          Preconditions.checkNotNull(scanQuery.toQuery(), "Can not plan Scan Druid Query"),
-          scanColumnNames);
+      return new QuerySpec(QueryType.SCAN, scanQuery.toQuery(), scanColumnNames);
     }
 
     // At this Stage we have a valid Aggregate thus Query is one of Timeseries, TopN, or GroupBy
@@ -1053,11 +1049,7 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
       // this is an index of existing columns coming out aggregate layer. Will use this index to:
       // filter out any project down the road that doesn't change values e.g inputRef/identity cast
       Map<String, String> existingProjects = Maps
-          .uniqueIndex(aggregateStageFieldNames, new Function<String, String>() {
-            @Override public String apply(@Nullable String input) {
-              return DruidExpressions.fromColumn(input);
-            }
-          });
+          .uniqueIndex(aggregateStageFieldNames, DruidExpressions::fromColumn);
       for (Pair<RexNode, String> pair : postProject.getNamedProjects()) {
         final RexNode postProjectRexNode = pair.left;
         String expression = DruidExpressions
@@ -1098,15 +1090,12 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
         // Case we have transformed the group by time to druid timeseries with Granularity.
         // Need to replace the name of the column with druid timestamp field name.
         final List<String> timeseriesFieldNames =
-            Lists.transform(queryOutputFieldNames,
-                new Function<String, String>() {
-                  @Override public String apply(@Nullable String input) {
-                    if (timeExtractColumn.equals(input)) {
-                      return "timestamp";
-                    }
-                    return input;
-                  }
-                });
+            Lists.transform(queryOutputFieldNames, input -> {
+              if (timeExtractColumn.equals(input)) {
+                return "timestamp";
+              }
+              return input;
+            });
         return new QuerySpec(QueryType.TIMESERIES, timeSeriesQueryString, timeseriesFieldNames);
       }
       return new QuerySpec(QueryType.TIMESERIES, timeSeriesQueryString, queryOutputFieldNames);
@@ -1350,7 +1339,7 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
       this.fetchLimit = fetchLimit;
     }
 
-    public String toQuery() {
+    @Nonnull public String toQuery() {
       final StringWriter sw = new StringWriter();
       try {
         final JsonFactory factory = new JsonFactory();
@@ -1548,8 +1537,8 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
 
     QuerySpec(QueryType queryType, String queryString,
         List<String> fieldNames) {
-      this.queryType = Preconditions.checkNotNull(queryType);
-      this.queryString = Preconditions.checkNotNull(queryString);
+      this.queryType = Objects.requireNonNull(queryType);
+      this.queryString = Objects.requireNonNull(queryString);
       this.fieldNames = ImmutableList.copyOf(fieldNames);
     }
 
@@ -1799,11 +1788,8 @@ public class DruidQuery extends AbstractRelNode implements BindableRel {
    * @return index of the timestamp ref or -1 if not present
    */
   protected int getTimestampFieldIndex() {
-    return Iterables.indexOf(this.getRowType().getFieldList(), new Predicate<RelDataTypeField>() {
-      @Override public boolean apply(@Nullable RelDataTypeField input) {
-        return druidTable.timestampFieldName.equals(input.getName());
-      }
-    });
+    return Iterables.indexOf(this.getRowType().getFieldList(),
+        input -> druidTable.timestampFieldName.equals(input.getName()));
   }
 }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidRules.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidRules.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidRules.java
index 83d4fce..f6b4efe 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidRules.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidRules.java
@@ -36,11 +36,9 @@ import org.apache.calcite.rel.rules.FilterAggregateTransposeRule;
 import org.apache.calcite.rel.rules.FilterProjectTransposeRule;
 import org.apache.calcite.rel.rules.ProjectFilterTransposeRule;
 import org.apache.calcite.rel.rules.ProjectSortTransposeRule;
-import org.apache.calcite.rel.rules.PushProjector;
 import org.apache.calcite.rel.rules.SortProjectTransposeRule;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
-import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexExecutor;
@@ -61,9 +59,7 @@ import org.apache.calcite.util.trace.CalciteTrace;
 import org.apache.commons.lang3.tuple.ImmutableTriple;
 import org.apache.commons.lang3.tuple.Triple;
 
-import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 
 import org.joda.time.Interval;
@@ -75,8 +71,6 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
-import javax.annotation.Nullable;
-
 /**
  * Rules and relational operators for {@link DruidQuery}.
  */
@@ -176,17 +170,14 @@ public class DruidRules {
       }
 
       // Timestamp
-      int timestampFieldIdx = Iterables
-          .indexOf(query.getRowType().getFieldList(), new Predicate<RelDataTypeField>() {
-            @Override public boolean apply(@Nullable RelDataTypeField input) {
-              return query.druidTable.timestampFieldName.equals(input.getName());
-            }
-          });
+      int timestampFieldIdx =
+          query.getRowType().getFieldNames()
+              .indexOf(query.druidTable.timestampFieldName);
       RelNode newDruidQuery = query;
       final Triple<List<RexNode>, List<RexNode>, List<RexNode>> triple =
           splitFilters(rexBuilder, query, validPreds, nonValidPreds, timestampFieldIdx);
       if (triple.getLeft().isEmpty() && triple.getMiddle().isEmpty()) {
-        //it sucks, nothing to push
+        // it sucks, nothing to push
         return;
       }
       final List<RexNode> residualPreds = new ArrayList<>(triple.getRight());
@@ -815,7 +806,7 @@ public class DruidRules {
           operand(Project.class,
               operand(Filter.class,
                   operand(DruidQuery.class, none()))),
-          PushProjector.ExprCondition.FALSE,
+              expr -> false,
           relBuilderFactory);
     }
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidSchema.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidSchema.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidSchema.java
index c8b6419..03d8210 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidSchema.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidSchema.java
@@ -21,7 +21,6 @@ import org.apache.calcite.schema.impl.AbstractSchema;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.Compatible;
 
-import com.google.common.base.Preconditions;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.collect.ImmutableMap;
@@ -32,8 +31,8 @@ import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
-import javax.annotation.Nonnull;
 
 /**
  * Schema mapped onto a Druid instance.
@@ -55,8 +54,8 @@ public class DruidSchema extends AbstractSchema {
    */
   public DruidSchema(String url, String coordinatorUrl,
       boolean discoverTables) {
-    this.url = Preconditions.checkNotNull(url);
-    this.coordinatorUrl = Preconditions.checkNotNull(coordinatorUrl);
+    this.url = Objects.requireNonNull(url);
+    this.coordinatorUrl = Objects.requireNonNull(coordinatorUrl);
     this.discoverTables = discoverTables;
   }
 
@@ -70,26 +69,26 @@ public class DruidSchema extends AbstractSchema {
       Set<String> tableNames = connection.tableNames();
 
       tableMap = Compatible.INSTANCE.asMap(
-              ImmutableSet.copyOf(tableNames),
-              CacheBuilder.newBuilder()
-                .build(new CacheLoader<String, Table>() {
-                  @Override public Table load(@Nonnull String tableName) throws Exception {
-                    final Map<String, SqlTypeName> fieldMap = new LinkedHashMap<>();
-                    final Set<String> metricNameSet = new LinkedHashSet<>();
-                    final Map<String, List<ComplexMetric>> complexMetrics = new HashMap<>();
-
-                    connection.metadata(tableName, DruidTable.DEFAULT_TIMESTAMP_COLUMN,
-                            null, fieldMap, metricNameSet, complexMetrics);
-
-                    return DruidTable.create(DruidSchema.this, tableName, null,
-                            fieldMap, metricNameSet, DruidTable.DEFAULT_TIMESTAMP_COLUMN,
-                            complexMetrics);
-                  }
-                }));
+          ImmutableSet.copyOf(tableNames),
+          CacheBuilder.newBuilder()
+              .build(CacheLoader.from(name -> table(name, connection))));
     }
 
     return tableMap;
   }
+
+  private Table table(String tableName, DruidConnectionImpl connection) {
+    final Map<String, SqlTypeName> fieldMap = new LinkedHashMap<>();
+    final Set<String> metricNameSet = new LinkedHashSet<>();
+    final Map<String, List<ComplexMetric>> complexMetrics = new HashMap<>();
+
+    connection.metadata(tableName, DruidTable.DEFAULT_TIMESTAMP_COLUMN,
+        null, fieldMap, metricNameSet, complexMetrics);
+
+    return DruidTable.create(DruidSchema.this, tableName, null,
+        fieldMap, metricNameSet, DruidTable.DEFAULT_TIMESTAMP_COLUMN,
+        complexMetrics);
+  }
 }
 
 // End DruidSchema.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/DruidTable.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidTable.java b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidTable.java
index 10e0466..1c402c0 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/DruidTable.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/DruidTable.java
@@ -49,6 +49,7 @@ import org.joda.time.chrono.ISOChronology;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -84,16 +85,16 @@ public class DruidTable extends AbstractTable implements TranslatableTable {
       RelProtoDataType protoRowType, Set<String> metricFieldNames,
       String timestampFieldName, List<Interval> intervals,
       Map<String, List<ComplexMetric>> complexMetrics, Map<String, SqlTypeName> allFields) {
-    this.timestampFieldName = Preconditions.checkNotNull(timestampFieldName);
-    this.schema = Preconditions.checkNotNull(schema);
-    this.dataSource = Preconditions.checkNotNull(dataSource);
+    this.timestampFieldName = Objects.requireNonNull(timestampFieldName);
+    this.schema = Objects.requireNonNull(schema);
+    this.dataSource = Objects.requireNonNull(dataSource);
     this.protoRowType = protoRowType;
     this.metricFieldNames = ImmutableSet.copyOf(metricFieldNames);
     this.intervals = intervals != null ? ImmutableList.copyOf(intervals)
         : ImmutableList.of(DEFAULT_INTERVAL);
-    this.complexMetrics = complexMetrics == null ? ImmutableMap.<String, List<ComplexMetric>>of()
+    this.complexMetrics = complexMetrics == null ? ImmutableMap.of()
             : ImmutableMap.copyOf(complexMetrics);
-    this.allFields = allFields == null ? ImmutableMap.<String, SqlTypeName>of()
+    this.allFields = allFields == null ? ImmutableMap.of()
             : ImmutableMap.copyOf(allFields);
   }
 
@@ -179,8 +180,7 @@ public class DruidTable extends AbstractTable implements TranslatableTable {
   }
 
   @Override public boolean rolledUpColumnValidInsideAgg(String column, SqlCall call,
-                                                        SqlNode parent,
-                                                        CalciteConnectionConfig config) {
+      SqlNode parent, CalciteConnectionConfig config) {
     assert isRolledUp(column);
     // Our rolled up columns are only allowed in COUNT(DISTINCT ...) aggregate functions.
     // We only allow this when approximate results are acceptable.
@@ -245,7 +245,7 @@ public class DruidTable extends AbstractTable implements TranslatableTable {
     final TableScan scan = LogicalTableScan.create(cluster, relOptTable);
     return DruidQuery.create(cluster,
         cluster.traitSetOf(BindableConvention.INSTANCE), relOptTable, this,
-        ImmutableList.<RelNode>of(scan));
+        ImmutableList.of(scan));
   }
 
   public boolean isMetric(String name) {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/ExtractionDimensionSpec.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/ExtractionDimensionSpec.java b/druid/src/main/java/org/apache/calcite/adapter/druid/ExtractionDimensionSpec.java
index 0aece36..8f65a59 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/ExtractionDimensionSpec.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/ExtractionDimensionSpec.java
@@ -17,9 +17,9 @@
 package org.apache.calcite.adapter.druid;
 
 import com.fasterxml.jackson.core.JsonGenerator;
-import com.google.common.base.Preconditions;
 
 import java.io.IOException;
+import java.util.Objects;
 
 import javax.annotation.Nullable;
 
@@ -45,8 +45,8 @@ public class ExtractionDimensionSpec implements DimensionSpec {
 
   public ExtractionDimensionSpec(String dimension, ExtractionFunction extractionFunction,
       String outputName, DruidType outputType) {
-    this.dimension = Preconditions.checkNotNull(dimension);
-    this.extractionFunction = Preconditions.checkNotNull(extractionFunction);
+    this.dimension = Objects.requireNonNull(dimension);
+    this.extractionFunction = Objects.requireNonNull(extractionFunction);
     this.outputName = outputName;
     this.outputType = outputType == null ? DruidType.STRING : outputType;
   }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/FloorOperatorConversion.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/FloorOperatorConversion.java b/druid/src/main/java/org/apache/calcite/adapter/druid/FloorOperatorConversion.java
index 187fa66..d775535 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/FloorOperatorConversion.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/FloorOperatorConversion.java
@@ -28,7 +28,6 @@ import java.util.TimeZone;
 
 import javax.annotation.Nullable;
 
-
 /**
  * DruidSqlOperatorConverter implementation that handles Floor operations conversions
  */

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/Granularities.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/Granularities.java b/druid/src/main/java/org/apache/calcite/adapter/druid/Granularities.java
index 2015075..5bf8b07 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/Granularities.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/Granularities.java
@@ -19,9 +19,9 @@ package org.apache.calcite.adapter.druid;
 import org.apache.calcite.avatica.util.TimeUnitRange;
 
 import com.fasterxml.jackson.core.JsonGenerator;
-import com.google.common.base.Preconditions;
 
 import java.io.IOException;
+import java.util.Objects;
 import javax.annotation.Nonnull;
 
 import static org.apache.calcite.adapter.druid.DruidQuery.writeFieldIf;
@@ -88,9 +88,9 @@ public class Granularities {
     private final String timeZone;
 
     private PeriodGranularity(Type type, String period, String timeZone) {
-      this.type = Preconditions.checkNotNull(type);
-      this.period = Preconditions.checkNotNull(period);
-      this.timeZone = Preconditions.checkNotNull(timeZone);
+      this.type = Objects.requireNonNull(type);
+      this.period = Objects.requireNonNull(period);
+      this.timeZone = Objects.requireNonNull(timeZone);
     }
 
     @Override public void write(JsonGenerator generator) throws IOException {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/NaryOperatorConverter.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/NaryOperatorConverter.java b/druid/src/main/java/org/apache/calcite/adapter/druid/NaryOperatorConverter.java
index 961454b..df30920 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/NaryOperatorConverter.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/NaryOperatorConverter.java
@@ -21,9 +21,8 @@ import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.sql.SqlOperator;
 
-import com.google.common.base.Preconditions;
-
 import java.util.List;
+import java.util.Objects;
 
 import javax.annotation.Nullable;
 
@@ -35,8 +34,8 @@ public class NaryOperatorConverter implements DruidSqlOperatorConverter {
   private final String druidOperatorName;
 
   public NaryOperatorConverter(SqlOperator operator, String druidOperatorName) {
-    this.operator = Preconditions.checkNotNull(operator);
-    this.druidOperatorName = Preconditions.checkNotNull(druidOperatorName);
+    this.operator = Objects.requireNonNull(operator);
+    this.druidOperatorName = Objects.requireNonNull(druidOperatorName);
   }
 
   @Override public SqlOperator calciteOperator() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/main/java/org/apache/calcite/adapter/druid/VirtualColumn.java
----------------------------------------------------------------------
diff --git a/druid/src/main/java/org/apache/calcite/adapter/druid/VirtualColumn.java b/druid/src/main/java/org/apache/calcite/adapter/druid/VirtualColumn.java
index 7348cec..3ac1ace 100644
--- a/druid/src/main/java/org/apache/calcite/adapter/druid/VirtualColumn.java
+++ b/druid/src/main/java/org/apache/calcite/adapter/druid/VirtualColumn.java
@@ -17,10 +17,10 @@
 package org.apache.calcite.adapter.druid;
 
 import com.fasterxml.jackson.core.JsonGenerator;
-import com.google.common.base.Preconditions;
 
 import java.io.IOException;
 import java.util.Locale;
+import java.util.Objects;
 
 import static org.apache.calcite.adapter.druid.DruidQuery.writeFieldIf;
 
@@ -36,8 +36,8 @@ public class VirtualColumn implements DruidJson {
   private final DruidType outputType;
 
   public VirtualColumn(String name, String expression, DruidType outputType) {
-    this.name = Preconditions.checkNotNull(name);
-    this.expression = Preconditions.checkNotNull(expression);
+    this.name = Objects.requireNonNull(name);
+    this.expression = Objects.requireNonNull(expression);
     this.outputType = outputType == null ? DruidType.FLOAT : outputType;
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/test/java/org/apache/calcite/adapter/druid/DruidQueryFilterTest.java
----------------------------------------------------------------------
diff --git a/druid/src/test/java/org/apache/calcite/adapter/druid/DruidQueryFilterTest.java b/druid/src/test/java/org/apache/calcite/adapter/druid/DruidQueryFilterTest.java
index 16e1f59..6b5b520 100644
--- a/druid/src/test/java/org/apache/calcite/adapter/druid/DruidQueryFilterTest.java
+++ b/druid/src/test/java/org/apache/calcite/adapter/druid/DruidQueryFilterTest.java
@@ -58,7 +58,7 @@ public class DruidQueryFilterTest {
     Mockito.when(druidQuery.getDruidTable())
         .thenReturn(
             new DruidTable(Mockito.mock(DruidSchema.class), "dataSource", null,
-                ImmutableSet.<String>of(), "timestamp", null, null,
+                ImmutableSet.of(), "timestamp", null, null,
                 null
             ));
   }
@@ -118,7 +118,7 @@ public class DruidQueryFilterTest {
     final RexBuilder rexBuilder = new RexBuilder(typeFactory);
     final DruidTable druidTable =
         new DruidTable(Mockito.mock(DruidSchema.class), "dataSource", null,
-            ImmutableSet.<String>of(), "timestamp", null, null,
+            ImmutableSet.of(), "timestamp", null, null,
                 null);
     final RelDataType varcharType =
         typeFactory.createSqlType(SqlTypeName.VARCHAR);

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT.java
----------------------------------------------------------------------
diff --git a/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT.java b/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT.java
index 817142f..074ad2a 100644
--- a/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT.java
+++ b/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT.java
@@ -20,16 +20,13 @@ import org.apache.calcite.adapter.druid.DruidQuery;
 import org.apache.calcite.adapter.druid.DruidSchema;
 import org.apache.calcite.config.CalciteConnectionConfig;
 import org.apache.calcite.config.CalciteConnectionProperty;
-import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.prepare.CalcitePrepareImpl;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.schema.impl.AbstractSchema;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.type.SqlTypeName;
-import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -38,11 +35,11 @@ import com.google.common.collect.Multimap;
 import org.junit.Test;
 
 import java.net.URL;
-import java.sql.Connection;
 import java.sql.DatabaseMetaData;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.List;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.containsString;
 import static org.hamcrest.CoreMatchers.is;
@@ -111,18 +108,15 @@ public class DruidAdapterIT {
     return ENABLED;
   }
 
-  /** Returns a function that checks that a particular Druid query is
+  /** Returns a consumer that checks that a particular Druid query is
    * generated to implement a query. */
-  private static Function<List, Void> druidChecker(final String... lines) {
-    return new Function<List, Void>() {
-      public Void apply(List list) {
-        assertThat(list.size(), is(1));
-        DruidQuery.QuerySpec querySpec = (DruidQuery.QuerySpec) list.get(0);
-        for (String line : lines) {
-          final String s = line.replace('\'', '"');
-          assertThat(querySpec.getQueryString(null, -1), containsString(s));
-        }
-        return null;
+  private static Consumer<List> druidChecker(final String... lines) {
+    return list -> {
+      assertThat(list.size(), is(1));
+      DruidQuery.QuerySpec querySpec = (DruidQuery.QuerySpec) list.get(0);
+      for (String line : lines) {
+        final String s = line.replace('\'', '"');
+        assertThat(querySpec.getQueryString(null, -1), containsString(s));
       }
     };
   }
@@ -383,31 +377,29 @@ public class DruidAdapterIT {
 
   @Test public void testMetadataColumns() throws Exception {
     sql("values 1")
-        .withConnection(
-            new Function<Connection, Void>() {
-              public Void apply(Connection c) {
-                try {
-                  final DatabaseMetaData metaData = c.getMetaData();
-                  final ResultSet r =
-                      metaData.getColumns(null, null, "foodmart", null);
-                  Multimap<String, Boolean> map = ArrayListMultimap.create();
-                  while (r.next()) {
-                    map.put(r.getString("TYPE_NAME"), true);
-                  }
-                  System.out.println(map);
-                  // 1 timestamp, 2 float measure, 1 int measure, 88 dimensions
-                  assertThat(map.keySet().size(), is(4));
-                  assertThat(map.values().size(), is(92));
-                  assertThat(map.get("TIMESTAMP_WITH_LOCAL_TIME_ZONE(0) NOT NULL").size(), is(1));
-                  assertThat(map.get("DOUBLE").size(), is(2));
-                  assertThat(map.get("BIGINT").size(), is(1));
-                  assertThat(map.get(VARCHAR_TYPE).size(), is(88));
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                return null;
-              }
-            });
+        .withConnection(c -> {
+          try {
+            final DatabaseMetaData metaData = c.getMetaData();
+            final ResultSet r =
+                metaData.getColumns(null, null, "foodmart", null);
+            Multimap<String, Boolean> map = ArrayListMultimap.create();
+            while (r.next()) {
+              map.put(r.getString("TYPE_NAME"), true);
+            }
+            if (CalcitePrepareImpl.DEBUG) {
+              System.out.println(map);
+            }
+            // 1 timestamp, 2 float measure, 1 int measure, 88 dimensions
+            assertThat(map.keySet().size(), is(4));
+            assertThat(map.values().size(), is(92));
+            assertThat(map.get("TIMESTAMP_WITH_LOCAL_TIME_ZONE(0) NOT NULL").size(), is(1));
+            assertThat(map.get("DOUBLE").size(), is(2));
+            assertThat(map.get("BIGINT").size(), is(1));
+            assertThat(map.get(VARCHAR_TYPE).size(), is(88));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testSelectDistinct() {
@@ -502,19 +494,16 @@ public class DruidAdapterIT {
   @Test public void testSelectCount() {
     final String sql = "select count(*) as c from \"foodmart\"";
     sql(sql)
-        .returns(new Function<ResultSet, Void>() {
-          public Void apply(ResultSet input) {
-            try {
-              assertThat(input.next(), is(true));
-              assertThat(input.getInt(1), is(86829));
-              assertThat(input.getLong(1), is(86829L));
-              assertThat(input.getString(1), is("86829"));
-              assertThat(input.wasNull(), is(false));
-              assertThat(input.next(), is(false));
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
+        .returns(input -> {
+          try {
+            assertThat(input.next(), is(true));
+            assertThat(input.getInt(1), is(86829));
+            assertThat(input.getLong(1), is(86829L));
+            assertThat(input.getString(1), is("86829"));
+            assertThat(input.wasNull(), is(false));
+            assertThat(input.next(), is(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
           }
         });
   }
@@ -798,22 +787,18 @@ public class DruidAdapterIT {
         + "'resultFormat':'compactedList'";
     sql(sql)
         .limit(4)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet resultSet) {
-                try {
-                  for (int i = 0; i < 4; i++) {
-                    assertTrue(resultSet.next());
-                    assertThat(resultSet.getString("product_name"),
-                        is("Fort West Dried Apricots"));
-                  }
-                  assertFalse(resultSet.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            })
+        .returns(resultSet -> {
+          try {
+            for (int i = 0; i < 4; i++) {
+              assertTrue(resultSet.next());
+              assertThat(resultSet.getString("product_name"),
+                  is("Fort West Dried Apricots"));
+            }
+            assertFalse(resultSet.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        })
         .queryContains(druidChecker(druidQuery));
   }
 
@@ -831,22 +816,18 @@ public class DruidAdapterIT {
         + "'resultFormat':'compactedList'";
     sql(sql)
         .limit(4)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet resultSet) {
-                try {
-                  for (int i = 0; i < 4; i++) {
-                    assertTrue(resultSet.next());
-                    assertThat(resultSet.getString("product_name"),
-                        is("Fort West Dried Apricots"));
-                  }
-                  assertFalse(resultSet.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            })
+        .returns(resultSet -> {
+          try {
+            for (int i = 0; i < 4; i++) {
+              assertTrue(resultSet.next());
+              assertThat(resultSet.getString("product_name"),
+                  is("Fort West Dried Apricots"));
+            }
+            assertFalse(resultSet.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        })
         .queryContains(druidChecker(druidQuery));
   }
 
@@ -881,22 +862,18 @@ public class DruidAdapterIT {
 
     sql(sql)
         .limit(4)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet resultSet) {
-                try {
-                  for (int i = 0; i < 4; i++) {
-                    assertTrue(resultSet.next());
-                    assertThat(resultSet.getString("product_name"),
-                        is("Fort West Dried Apricots"));
-                  }
-                  assertFalse(resultSet.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            })
+        .returns(resultSet -> {
+          try {
+            for (int i = 0; i < 4; i++) {
+              assertTrue(resultSet.next());
+              assertThat(resultSet.getString("product_name"),
+                  is("Fort West Dried Apricots"));
+            }
+            assertFalse(resultSet.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        })
         .queryContains(druidChecker(druidQuery, druidFilter, druidQuery2));
   }
 
@@ -2001,43 +1978,39 @@ public class DruidAdapterIT {
     String druidQuery = "'filter':{'type':'bound','dimension':'product_id',"
         + "'upper':'10','upperStrict':true,'ordering':'numeric'}";
     sql("?")
-        .withRel(new Function<RelBuilder, RelNode>() {
-          public RelNode apply(RelBuilder b) {
-            // select product_id
-            // from foodmart.foodmart
-            // where product_id < cast(10 as varchar)
-            final RelDataType intType =
-                b.getTypeFactory().createSqlType(SqlTypeName.INTEGER);
-            return b.scan("foodmart", "foodmart")
-                .filter(
-                    b.call(SqlStdOperatorTable.LESS_THAN,
-                        b.getRexBuilder().makeCall(intType,
-                            SqlStdOperatorTable.CAST,
-                            ImmutableList.<RexNode>of(b.field("product_id"))),
-                        b.getRexBuilder().makeCall(intType,
-                            SqlStdOperatorTable.CAST,
-                            ImmutableList.of(b.literal("10")))))
-                .project(b.field("product_id"))
-                .build();
-          }
+        .withRel(b -> {
+          // select product_id
+          // from foodmart.foodmart
+          // where product_id < cast(10 as varchar)
+          final RelDataType intType =
+              b.getTypeFactory().createSqlType(SqlTypeName.INTEGER);
+          return b.scan("foodmart", "foodmart")
+              .filter(
+                  b.call(SqlStdOperatorTable.LESS_THAN,
+                      b.getRexBuilder().makeCall(intType,
+                          SqlStdOperatorTable.CAST,
+                          ImmutableList.of(b.field("product_id"))),
+                      b.getRexBuilder().makeCall(intType,
+                          SqlStdOperatorTable.CAST,
+                          ImmutableList.of(b.literal("10")))))
+              .project(b.field("product_id"))
+              .build();
         })
         .queryContains(druidChecker(druidQuery));
   }
 
   @Test public void testPushFieldEqualsLiteral() {
     sql("?")
-        .withRel(new Function<RelBuilder, RelNode>() {
-          public RelNode apply(RelBuilder b) {
-            // select count(*) as c
-            // from foodmart.foodmart
-            // where product_id = 'id'
-            return b.scan("foodmart", "foodmart")
-                .filter(
-                    b.call(SqlStdOperatorTable.EQUALS, b.field("product_id"),
-                        b.literal("id")))
-                .aggregate(b.groupKey(), b.countStar("c"))
-                .build();
-          }
+        .withRel(b -> {
+          // select count(*) as c
+          // from foodmart.foodmart
+          // where product_id = 'id'
+          return b.scan("foodmart", "foodmart")
+              .filter(
+                  b.call(SqlStdOperatorTable.EQUALS, b.field("product_id"),
+                      b.literal("id")))
+              .aggregate(b.groupKey(), b.countStar("c"))
+              .build();
         })
         // Should return one row, "c=0"; logged
         // [CALCITE-1775] "GROUP BY ()" on empty relation should return 1 row

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT2.java
----------------------------------------------------------------------
diff --git a/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT2.java b/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT2.java
index 97e9cc4..d256d81 100644
--- a/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT2.java
+++ b/druid/src/test/java/org/apache/calcite/test/DruidAdapterIT2.java
@@ -20,16 +20,13 @@ import org.apache.calcite.adapter.druid.DruidQuery;
 import org.apache.calcite.adapter.druid.DruidSchema;
 import org.apache.calcite.config.CalciteConnectionConfig;
 import org.apache.calcite.config.CalciteConnectionProperty;
-import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.prepare.CalcitePrepareImpl;
 import org.apache.calcite.rel.type.RelDataType;
-import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.schema.impl.AbstractSchema;
 import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.type.SqlTypeName;
-import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.Util;
 
-import com.google.common.base.Function;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -38,11 +35,11 @@ import com.google.common.collect.Multimap;
 import org.junit.Test;
 
 import java.net.URL;
-import java.sql.Connection;
 import java.sql.DatabaseMetaData;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.List;
+import java.util.function.Consumer;
 
 import static org.hamcrest.CoreMatchers.containsString;
 import static org.hamcrest.CoreMatchers.is;
@@ -97,16 +94,13 @@ public class DruidAdapterIT2 {
 
   /** Returns a function that checks that a particular Druid query is
    * generated to implement a query. */
-  private static Function<List, Void> druidChecker(final String... lines) {
-    return new Function<List, Void>() {
-      public Void apply(List list) {
-        assertThat(list.size(), is(1));
-        DruidQuery.QuerySpec querySpec = (DruidQuery.QuerySpec) list.get(0);
-        for (String line : lines) {
-          final String s = line.replace('\'', '"');
-          assertThat(querySpec.getQueryString(null, -1), containsString(s));
-        }
-        return null;
+  private static Consumer<List> druidChecker(final String... lines) {
+    return list -> {
+      assertThat(list.size(), is(1));
+      DruidQuery.QuerySpec querySpec = (DruidQuery.QuerySpec) list.get(0);
+      for (String line : lines) {
+        final String s = line.replace('\'', '"');
+        assertThat(querySpec.getQueryString(null, -1), containsString(s));
       }
     };
   }
@@ -143,31 +137,29 @@ public class DruidAdapterIT2 {
 
   @Test public void testMetadataColumns() throws Exception {
     sql("values 1")
-        .withConnection(
-            new Function<Connection, Void>() {
-              public Void apply(Connection c) {
-                try {
-                  final DatabaseMetaData metaData = c.getMetaData();
-                  final ResultSet r =
-                      metaData.getColumns(null, null, "foodmart", null);
-                  Multimap<String, Boolean> map = ArrayListMultimap.create();
-                  while (r.next()) {
-                    map.put(r.getString("TYPE_NAME"), true);
-                  }
-                  System.out.println(map);
-                  // 1 timestamp, 2 float measure, 1 int measure, 88 dimensions
-                  assertThat(map.keySet().size(), is(4));
-                  assertThat(map.values().size(), is(92));
-                  assertThat(map.get("TIMESTAMP(0) NOT NULL").size(), is(1));
-                  assertThat(map.get("DOUBLE").size(), is(2));
-                  assertThat(map.get("BIGINT").size(), is(1));
-                  assertThat(map.get(VARCHAR_TYPE).size(), is(88));
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-                return null;
-              }
-            });
+        .withConnection(c -> {
+          try {
+            final DatabaseMetaData metaData = c.getMetaData();
+            final ResultSet r =
+                metaData.getColumns(null, null, "foodmart", null);
+            Multimap<String, Boolean> map = ArrayListMultimap.create();
+            while (r.next()) {
+              map.put(r.getString("TYPE_NAME"), true);
+            }
+            if (CalcitePrepareImpl.DEBUG) {
+              System.out.println(map);
+            }
+            // 1 timestamp, 2 float measure, 1 int measure, 88 dimensions
+            assertThat(map.keySet().size(), is(4));
+            assertThat(map.values().size(), is(92));
+            assertThat(map.get("TIMESTAMP(0) NOT NULL").size(), is(1));
+            assertThat(map.get("DOUBLE").size(), is(2));
+            assertThat(map.get("BIGINT").size(), is(1));
+            assertThat(map.get(VARCHAR_TYPE).size(), is(88));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        });
   }
 
   @Test public void testSelectDistinct() {
@@ -262,19 +254,16 @@ public class DruidAdapterIT2 {
   @Test public void testSelectCount() {
     final String sql = "select count(*) as c from \"foodmart\"";
     sql(sql)
-        .returns(new Function<ResultSet, Void>() {
-          public Void apply(ResultSet input) {
-            try {
-              assertThat(input.next(), is(true));
-              assertThat(input.getInt(1), is(86829));
-              assertThat(input.getLong(1), is(86829L));
-              assertThat(input.getString(1), is("86829"));
-              assertThat(input.wasNull(), is(false));
-              assertThat(input.next(), is(false));
-              return null;
-            } catch (SQLException e) {
-              throw new RuntimeException(e);
-            }
+        .returns(input -> {
+          try {
+            assertThat(input.next(), is(true));
+            assertThat(input.getInt(1), is(86829));
+            assertThat(input.getLong(1), is(86829L));
+            assertThat(input.getString(1), is("86829"));
+            assertThat(input.wasNull(), is(false));
+            assertThat(input.next(), is(false));
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
           }
         });
   }
@@ -555,22 +544,18 @@ public class DruidAdapterIT2 {
         + "'resultFormat':'compactedList'";
     sql(sql)
         .limit(4)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet resultSet) {
-                try {
-                  for (int i = 0; i < 4; i++) {
-                    assertTrue(resultSet.next());
-                    assertThat(resultSet.getString("product_name"),
-                        is("Fort West Dried Apricots"));
-                  }
-                  assertFalse(resultSet.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            })
+        .returns(resultSet -> {
+          try {
+            for (int i = 0; i < 4; i++) {
+              assertTrue(resultSet.next());
+              assertThat(resultSet.getString("product_name"),
+                  is("Fort West Dried Apricots"));
+            }
+            assertFalse(resultSet.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        })
         .queryContains(druidChecker(druidQuery));
   }
 
@@ -588,22 +573,18 @@ public class DruidAdapterIT2 {
         + "'resultFormat':'compactedList'";
     sql(sql)
         .limit(4)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet resultSet) {
-                try {
-                  for (int i = 0; i < 4; i++) {
-                    assertTrue(resultSet.next());
-                    assertThat(resultSet.getString("product_name"),
-                        is("Fort West Dried Apricots"));
-                  }
-                  assertFalse(resultSet.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            })
+        .returns(resultSet -> {
+          try {
+            for (int i = 0; i < 4; i++) {
+              assertTrue(resultSet.next());
+              assertThat(resultSet.getString("product_name"),
+                  is("Fort West Dried Apricots"));
+            }
+            assertFalse(resultSet.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        })
         .queryContains(druidChecker(druidQuery));
   }
 
@@ -638,22 +619,18 @@ public class DruidAdapterIT2 {
 
     sql(sql)
         .limit(4)
-        .returns(
-            new Function<ResultSet, Void>() {
-              public Void apply(ResultSet resultSet) {
-                try {
-                  for (int i = 0; i < 4; i++) {
-                    assertTrue(resultSet.next());
-                    assertThat(resultSet.getString("product_name"),
-                        is("Fort West Dried Apricots"));
-                  }
-                  assertFalse(resultSet.next());
-                  return null;
-                } catch (SQLException e) {
-                  throw new RuntimeException(e);
-                }
-              }
-            })
+        .returns(resultSet -> {
+          try {
+            for (int i = 0; i < 4; i++) {
+              assertTrue(resultSet.next());
+              assertThat(resultSet.getString("product_name"),
+                  is("Fort West Dried Apricots"));
+            }
+            assertFalse(resultSet.next());
+          } catch (SQLException e) {
+            throw new RuntimeException(e);
+          }
+        })
         .queryContains(druidChecker(druidQuery, druidFilter, druidQuery2));
   }
 
@@ -1739,43 +1716,39 @@ public class DruidAdapterIT2 {
     String druidQuery = "'filter':{'type':'bound','dimension':'product_id',"
         + "'upper':'10','upperStrict':true,'ordering':'numeric'}";
     sql("?")
-        .withRel(new Function<RelBuilder, RelNode>() {
-          public RelNode apply(RelBuilder b) {
-            // select product_id
-            // from foodmart.foodmart
-            // where product_id < cast(10 as varchar)
-            final RelDataType intType =
-                b.getTypeFactory().createSqlType(SqlTypeName.INTEGER);
-            return b.scan("foodmart", "foodmart")
-                .filter(
-                    b.call(SqlStdOperatorTable.LESS_THAN,
-                        b.getRexBuilder().makeCall(intType,
-                            SqlStdOperatorTable.CAST,
-                            ImmutableList.<RexNode>of(b.field("product_id"))),
-                        b.getRexBuilder().makeCall(intType,
-                            SqlStdOperatorTable.CAST,
-                            ImmutableList.of(b.literal("10")))))
-                .project(b.field("product_id"))
-                .build();
-          }
+        .withRel(b -> {
+          // select product_id
+          // from foodmart.foodmart
+          // where product_id < cast(10 as varchar)
+          final RelDataType intType =
+              b.getTypeFactory().createSqlType(SqlTypeName.INTEGER);
+          return b.scan("foodmart", "foodmart")
+              .filter(
+                  b.call(SqlStdOperatorTable.LESS_THAN,
+                      b.getRexBuilder().makeCall(intType,
+                          SqlStdOperatorTable.CAST,
+                          ImmutableList.of(b.field("product_id"))),
+                      b.getRexBuilder().makeCall(intType,
+                          SqlStdOperatorTable.CAST,
+                          ImmutableList.of(b.literal("10")))))
+              .project(b.field("product_id"))
+              .build();
         })
         .queryContains(druidChecker(druidQuery));
   }
 
   @Test public void testPushFieldEqualsLiteral() {
     sql("?")
-        .withRel(new Function<RelBuilder, RelNode>() {
-          public RelNode apply(RelBuilder b) {
-            // select count(*) as c
-            // from foodmart.foodmart
-            // where product_id = 'id'
-            return b.scan("foodmart", "foodmart")
-                .filter(
-                    b.call(SqlStdOperatorTable.EQUALS, b.field("product_id"),
-                        b.literal("id")))
-                .aggregate(b.groupKey(), b.countStar("c"))
-                .build();
-          }
+        .withRel(b -> {
+          // select count(*) as c
+          // from foodmart.foodmart
+          // where product_id = 'id'
+          return b.scan("foodmart", "foodmart")
+              .filter(
+                  b.call(SqlStdOperatorTable.EQUALS, b.field("product_id"),
+                      b.literal("id")))
+              .aggregate(b.groupKey(), b.countStar("c"))
+              .build();
         })
         // Should return one row, "c=0"; logged
         // [CALCITE-1775] "GROUP BY ()" on empty relation should return 1 row

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/pom.xml
----------------------------------------------------------------------
diff --git a/elasticsearch2/pom.xml b/elasticsearch2/pom.xml
index 6fbee03..a017f7a 100644
--- a/elasticsearch2/pom.xml
+++ b/elasticsearch2/pom.xml
@@ -84,10 +84,6 @@ limitations under the License.
       <version>${hppc.version}</version>
     </dependency>
     <dependency>
-      <groupId>com.google.code.findbugs</groupId>
-      <artifactId>jsr305</artifactId>
-    </dependency>
-    <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
     </dependency>

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Enumerator.java
----------------------------------------------------------------------
diff --git a/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Enumerator.java b/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Enumerator.java
index 62aa197..54e4357 100644
--- a/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Enumerator.java
+++ b/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Enumerator.java
@@ -73,22 +73,16 @@ public class Elasticsearch2Enumerator implements Enumerator<Object> {
   }
 
   private static Function1<SearchHit, Map> mapGetter() {
-    return new Function1<SearchHit, Map>() {
-      public Map apply(SearchHit searchHitFields) {
-        return (Map) searchHitFields.fields();
-      }
-    };
+    return searchHitFields -> (Map) searchHitFields.fields();
   }
 
   private static Function1<SearchHit, Object> singletonGetter(final String fieldName,
       final Class fieldClass) {
-    return new Function1<SearchHit, Object>() {
-      public Object apply(SearchHit searchHitFields) {
-        if (searchHitFields.fields().isEmpty()) {
-          return convert(searchHitFields.getSource(), fieldClass);
-        } else {
-          return convert(searchHitFields.getFields(), fieldClass);
-        }
+    return searchHitFields -> {
+      if (searchHitFields.fields().isEmpty()) {
+        return convert(searchHitFields.getSource(), fieldClass);
+      } else {
+        return convert(searchHitFields.getFields(), fieldClass);
       }
     };
   }
@@ -103,23 +97,21 @@ public class Elasticsearch2Enumerator implements Enumerator<Object> {
    */
   private static Function1<SearchHit, Object[]> listGetter(
       final List<Map.Entry<String, Class>> fields) {
-    return new Function1<SearchHit, Object[]>() {
-      public Object[] apply(SearchHit hit) {
-        Object[] objects = new Object[fields.size()];
-        for (int i = 0; i < fields.size(); i++) {
-          final Map.Entry<String, Class> field = fields.get(i);
-          final String name = field.getKey();
-          if (hit.fields().isEmpty()) {
-            objects[i] = convert(hit.getSource().get(name), field.getValue());
-          } else if (hit.fields().containsKey(name)) {
-            objects[i] = convert(hit.field(name).getValue(), field.getValue());
-          } else {
-            throw new IllegalStateException(
-                String.format(Locale.ROOT, "No result for %s", field));
-          }
+    return hit -> {
+      Object[] objects = new Object[fields.size()];
+      for (int i = 0; i < fields.size(); i++) {
+        final Map.Entry<String, Class> field = fields.get(i);
+        final String name = field.getKey();
+        if (hit.fields().isEmpty()) {
+          objects[i] = convert(hit.getSource().get(name), field.getValue());
+        } else if (hit.fields().containsKey(name)) {
+          objects[i] = convert(hit.field(name).getValue(), field.getValue());
+        } else {
+          throw new IllegalStateException(
+              String.format(Locale.ROOT, "No result for %s", field));
         }
-        return objects;
       }
+      return objects;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Schema.java
----------------------------------------------------------------------
diff --git a/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Schema.java b/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Schema.java
index f02a668..6d464c8 100644
--- a/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Schema.java
+++ b/elasticsearch2/src/main/java/org/apache/calcite/adapter/elasticsearch2/Elasticsearch2Schema.java
@@ -21,10 +21,7 @@ import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.AbstractSchema;
 
 import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
-
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
@@ -44,6 +41,7 @@ import java.net.InetSocketAddress;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Schema mapped onto an index of ELASTICSEARCH types.
@@ -98,8 +96,8 @@ public class Elasticsearch2Schema extends AbstractSchema
    */
   @VisibleForTesting
   Elasticsearch2Schema(Client client, String index) {
-    this.client = Preconditions.checkNotNull(client, "client");
-    this.index = Preconditions.checkNotNull(index, "index");
+    this.client = Objects.requireNonNull(client, "client");
+    this.index = Objects.requireNonNull(index, "index");
   }
 
   @Override protected Map<String, Table> getTableMap() {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchNode.java
----------------------------------------------------------------------
diff --git a/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchNode.java b/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchNode.java
index d7e3464..de150be 100644
--- a/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchNode.java
+++ b/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchNode.java
@@ -34,6 +34,7 @@ import java.io.File;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.Objects;
 
 /**
  * Represents a single Elasticsearch node that can run embedded in a java application.
@@ -45,7 +46,7 @@ class EmbeddedElasticsearchNode implements AutoCloseable {
   private volatile boolean  isStarted;
 
   private EmbeddedElasticsearchNode(LocalNode node) {
-    this.node = Preconditions.checkNotNull(node, "node");
+    this.node = Objects.requireNonNull(node, "node");
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchPolicy.java
----------------------------------------------------------------------
diff --git a/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchPolicy.java b/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchPolicy.java
index 6b25ecf..654d693 100644
--- a/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchPolicy.java
+++ b/elasticsearch2/src/test/java/org/apache/calcite/adapter/elasticsearch2/EmbeddedElasticsearchPolicy.java
@@ -16,12 +16,12 @@
  */
 package org.apache.calcite.adapter.elasticsearch2;
 
-import com.google.common.base.Preconditions;
-
 import org.elasticsearch.client.Client;
 import org.elasticsearch.common.transport.TransportAddress;
 import org.junit.rules.ExternalResource;
 
+import java.util.Objects;
+
 /**
  * Junit rule that is used to initialize a single Elasticsearch node for tests.
  *
@@ -56,7 +56,7 @@ class EmbeddedElasticsearchPolicy extends ExternalResource {
   private final EmbeddedElasticsearchNode node;
 
   private EmbeddedElasticsearchPolicy(EmbeddedElasticsearchNode resource) {
-    this.node = Preconditions.checkNotNull(resource, "resource");
+    this.node = Objects.requireNonNull(resource, "resource");
   }
 
   @Override protected void before() throws Throwable {

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/src/test/java/org/apache/calcite/test/Elasticsearch2AdapterIT.java
----------------------------------------------------------------------
diff --git a/elasticsearch2/src/test/java/org/apache/calcite/test/Elasticsearch2AdapterIT.java b/elasticsearch2/src/test/java/org/apache/calcite/test/Elasticsearch2AdapterIT.java
new file mode 100644
index 0000000..f385d1d
--- /dev/null
+++ b/elasticsearch2/src/test/java/org/apache/calcite/test/Elasticsearch2AdapterIT.java
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.test;
+
+import org.apache.calcite.util.Util;
+
+import com.google.common.collect.ImmutableMap;
+
+import org.junit.Test;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+/**
+ * Tests for the {@code org.apache.calcite.adapter.elasticsearch2} package.
+ *
+ * <p>Before calling this test, you need to populate Elasticsearch, as follows:
+ *
+ * <blockquote><code>
+ * git clone https://github.com/vlsi/calcite-test-dataset<br>
+ * cd calcite-test-dataset<br>
+ * mvn install
+ * </code></blockquote>
+ *
+ * <p>This will create a virtual machine with Elasticsearch and the "zips" test
+ * dataset.
+ */
+public class Elasticsearch2AdapterIT {
+  /**
+   * Whether to run Elasticsearch tests. Enabled by default, however test is only
+   * included if "it" profile is activated ({@code -Pit}). To disable,
+   * specify {@code -Dcalcite.test.elasticsearch=false} on the Java command line.
+   */
+  private static final boolean ENABLED = Util.getBooleanProperty("calcite.test.elasticsearch",
+      true);
+
+  /** Connection factory based on the "zips-es" model. */
+  private static final ImmutableMap<String, String> ZIPS = ImmutableMap.of("model",
+      Elasticsearch2AdapterIT.class.getResource("/elasticsearch-zips-model.json").getPath());
+
+  /** Whether to run this test. */
+  private boolean enabled() {
+    return ENABLED;
+  }
+
+  /** Returns a function that checks that a particular Elasticsearch pipeline is
+   * generated to implement a query. */
+  private static Consumer<List> elasticsearchChecker(final String... strings) {
+    return actual -> {
+      Object[] actualArray = actual == null || actual.isEmpty() ? null
+          : ((List) actual.get(0)).toArray();
+      CalciteAssert.assertArrayEqual("expected Elasticsearch query not found", strings,
+          actualArray);
+    };
+  }
+
+  @Test public void testSort() {
+    final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
+        + "  ElasticsearchSort(sort0=[$4], dir0=[ASC])\n"
+        + "    ElasticsearchProject(city=[CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], longitude=[CAST(ITEM(ITEM($0, 'loc'), 0)):FLOAT], latitude=[CAST(ITEM(ITEM($0, 'loc'), 1)):FLOAT], pop=[CAST(ITEM($0, 'pop')):INTEGER], state=[CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], id=[CAST(ITEM($0, 'id')):VARCHAR(5) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"])\n"
+        + "      ElasticsearchTableScan(table=[[elasticsearch_raw, zips]])";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select * from zips order by \"state\"")
+        .returnsCount(10)
+        .explainContains(explain);
+  }
+
+  @Test public void testSortLimit() {
+    final String sql = "select \"state\", \"id\" from zips\n"
+        + "order by \"state\", \"id\" offset 2 rows fetch next 3 rows only";
+    CalciteAssert.that()
+        .with(ZIPS)
+        .query(sql)
+        .returnsUnordered("state=AK; id=99503",
+            "state=AK; id=99504",
+            "state=AK; id=99505")
+        .queryContains(
+            elasticsearchChecker(
+                "\"fields\" : [\"state\", \"id\"], \"script_fields\": {}",
+                "\"sort\": [ {\"state\": \"asc\"}, {\"id\": \"asc\"}]",
+                "\"from\": 2",
+                "\"size\": 3"));
+  }
+
+  @Test public void testOffsetLimit() {
+    final String sql = "select \"state\", \"id\" from zips\n"
+        + "offset 2 fetch next 3 rows only";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .runs()
+        .queryContains(
+            elasticsearchChecker(
+                "\"from\": 2",
+                "\"size\": 3",
+                "\"fields\" : [\"state\", \"id\"], \"script_fields\": {}"));
+  }
+
+  @Test public void testLimit() {
+    final String sql = "select \"state\", \"id\" from zips\n"
+        + "fetch next 3 rows only";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .runs()
+        .queryContains(
+            elasticsearchChecker(
+                "\"size\": 3",
+                "\"fields\" : [\"state\", \"id\"], \"script_fields\": {}"));
+  }
+
+  @Test public void testFilterSort() {
+    final String sql = "select * from zips\n"
+        + "where \"city\" = 'SPRINGFIELD' and \"id\" >= '70000'\n"
+        + "order by \"state\", \"id\"";
+    final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
+        + "  ElasticsearchSort(sort0=[$4], sort1=[$5], dir0=[ASC], dir1=[ASC])\n"
+        + "    ElasticsearchProject(city=[CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], longitude=[CAST(ITEM(ITEM($0, 'loc'), 0)):FLOAT], latitude=[CAST(ITEM(ITEM($0, 'loc'), 1)):FLOAT], pop=[CAST(ITEM($0, 'pop')):INTEGER], state=[CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], id=[CAST(ITEM($0, 'id')):VARCHAR(5) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"])\n"
+        + "      ElasticsearchFilter(condition=[AND(=(CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\", 'SPRINGFIELD'), >=(CAST(ITEM($0, 'id')):VARCHAR(5) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\", '70000'))])\n"
+        + "        ElasticsearchTableScan(table=[[elasticsearch_raw, zips]])";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .returnsOrdered(
+            "city=SPRINGFIELD; longitude=-92.54567; latitude=35.274879; pop=752; state=AR; id=72157",
+            "city=SPRINGFIELD; longitude=-102.617322; latitude=37.406727; pop=1992; state=CO; id=81073",
+            "city=SPRINGFIELD; longitude=-90.577479; latitude=30.415738; pop=5597; state=LA; id=70462",
+            "city=SPRINGFIELD; longitude=-123.015259; latitude=44.06106; pop=32384; state=OR; id=97477",
+            "city=SPRINGFIELD; longitude=-122.917108; latitude=44.056056; pop=27521; state=OR; id=97478")
+        .queryContains(
+            elasticsearchChecker("\"query\" : {\"constant_score\":{\"filter\":{\"bool\":"
+                    + "{\"must\":[{\"term\":{\"city\":\"springfield\"}},{\"range\":{\"id\":{\"gte\":\"70000\"}}}]}}}}",
+                "\"fields\" : [\"city\", \"pop\", \"state\", \"id\"], \"script_fields\": {\"longitude\":{\"script\":\"_source.loc[0]\"}, \"latitude\":{\"script\":\"_source.loc[1]\"}}",
+                "\"sort\": [ {\"state\": \"asc\"}, {\"id\": \"asc\"}]"))
+        .explainContains(explain);
+  }
+
+  @Test public void testFilterSortDesc() {
+    final String sql = "select * from zips\n"
+        + "where \"pop\" BETWEEN 20000 AND 20100\n"
+        + "order by \"state\" desc, \"pop\"";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .limit(4)
+        .returnsOrdered(
+            "city=SHERIDAN; longitude=-106.964795; latitude=44.78486; pop=20025; state=WY; id=82801",
+            "city=MOUNTLAKE TERRAC; longitude=-122.304036; latitude=47.793061; pop=20059; state=WA; id=98043",
+            "city=FALMOUTH; longitude=-77.404537; latitude=38.314557; pop=20039; state=VA; id=22405",
+            "city=FORT WORTH; longitude=-97.318409; latitude=32.725551; pop=20012; state=TX; id=76104");
+  }
+
+  @Test public void testFilterRedundant() {
+    final String sql = "select * from zips\n"
+        + "where \"state\" > 'CA' and \"state\" < 'AZ' and \"state\" = 'OK'";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .runs()
+        .queryContains(
+            elasticsearchChecker(""
+                + "\"query\" : {\"constant_score\":{\"filter\":{\"bool\":"
+                + "{\"must\":[{\"term\":{\"state\":\"ok\"}}]}}}}",
+                "\"fields\" : [\"city\", \"pop\", \"state\", \"id\"], \"script_fields\": {\"longitude\":{\"script\":\"_source.loc[0]\"}, \"latitude\":{\"script\":\"_source.loc[1]\"}}"));
+  }
+
+  @Test public void testInPlan() {
+    final String[] searches = {
+        "\"query\" : {\"constant_score\":{\"filter\":{\"bool\":{\"should\":"
+          + "[{\"bool\":{\"must\":[{\"term\":{\"pop\":20012}}]}},{\"bool\":{\"must\":[{\"term\":"
+          + "{\"pop\":15590}}]}}]}}}}",
+        "\"fields\" : [\"city\", \"pop\", \"state\", \"id\"], \"script_fields\": {\"longitude\":{\"script\":\"_source.loc[0]\"}, \"latitude\":{\"script\":\"_source.loc[1]\"}}"
+    };
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select * from zips where \"pop\" in (20012, 15590)")
+        .returnsUnordered(
+            "city=COVINA; longitude=-117.884285; latitude=34.08596; pop=15590; state=CA; id=91723",
+            "city=ARLINGTON; longitude=-97.091987; latitude=32.654752; pop=15590; state=TX; id=76018",
+            "city=CROFTON; longitude=-76.680166; latitude=39.011163; pop=15590; state=MD; id=21114",
+            "city=FORT WORTH; longitude=-97.318409; latitude=32.725551; pop=20012; state=TX; id=76104",
+            "city=DINUBA; longitude=-119.39087; latitude=36.534931; pop=20012; state=CA; id=93618")
+        .queryContains(elasticsearchChecker(searches));
+  }
+
+  @Test public void testZips() {
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips")
+        .returnsCount(10);
+  }
+
+  @Test public void testProject() {
+    final String sql = "select \"state\", \"city\", 0 as \"zero\"\n"
+        + "from zips\n"
+        + "order by \"state\", \"city\"";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query(sql)
+        .limit(2)
+        .returnsUnordered("state=AK; city=ELMENDORF AFB; zero=0",
+            "state=AK; city=EIELSON AFB; zero=0")
+        .queryContains(
+            elasticsearchChecker("\"sort\": [ {\"state\": \"asc\"}, {\"city\": \"asc\"}]",
+                "\"fields\" : [\"state\", \"city\"], \"script_fields\": {\"zero\":{\"script\": \"0\"}}"));
+  }
+
+  @Test public void testFilter() {
+    final String explain = "PLAN=ElasticsearchToEnumerableConverter\n"
+        + "  ElasticsearchProject(state=[CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"], city=[CAST(ITEM($0, 'city')):VARCHAR(20) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\"])\n"
+        + "    ElasticsearchFilter(condition=[=(CAST(ITEM($0, 'state')):VARCHAR(2) CHARACTER SET \"ISO-8859-1\" COLLATE \"ISO-8859-1$en_US$primary\", 'CA')])\n"
+        + "      ElasticsearchTableScan(table=[[elasticsearch_raw, zips]])";
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips where \"state\" = 'CA'")
+        .limit(2)
+        .returnsUnordered("state=CA; city=LOS ANGELES",
+            "state=CA; city=LOS ANGELES")
+        .explainContains(explain);
+  }
+
+  @Test public void testFilterReversed() {
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips where 'WI' < \"state\"")
+        .limit(2)
+        .returnsUnordered("state=WV; city=WELCH",
+            "state=WV; city=HANOVER");
+    CalciteAssert.that()
+        .enable(enabled())
+        .with(ZIPS)
+        .query("select \"state\", \"city\" from zips where \"state\" > 'WI'")
+        .limit(2)
+        .returnsUnordered("state=WV; city=WELCH",
+            "state=WV; city=HANOVER");
+  }
+}
+
+// End Elasticsearch2AdapterIT.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch2/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
----------------------------------------------------------------------
diff --git a/elasticsearch2/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java b/elasticsearch2/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
index d897dfb..be236ed 100644
--- a/elasticsearch2/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
+++ b/elasticsearch2/src/test/java/org/apache/calcite/test/ElasticsearchChecker.java
@@ -16,11 +16,8 @@
  */
 package org.apache.calcite.test;
 
-import com.google.common.base.Function;
-
 import java.util.List;
-
-import javax.annotation.Nullable;
+import java.util.function.Consumer;
 
 /**
  * Utility methods for Elasticsearch tests.
@@ -29,23 +26,18 @@ public class ElasticsearchChecker {
 
   private ElasticsearchChecker() {}
 
-
   /** Returns a function that checks that a particular Elasticsearch pipeline is
    * generated to implement a query.
    *
    * @param strings list of expected queries
    * @return function to perform the check
    */
-  public static Function<List, Void> elasticsearchChecker(final String... strings) {
-    return new Function<List, Void>() {
-      @Nullable
-      @Override public Void apply(@Nullable List actual) {
-        Object[] actualArray = actual == null || actual.isEmpty() ? null
-            : ((List) actual.get(0)).toArray();
-        CalciteAssert.assertArrayEqual("expected Elasticsearch query not found", strings,
-            actualArray);
-        return null;
-      }
+  public static Consumer<List> elasticsearchChecker(final String... strings) {
+    return actual -> {
+      Object[] actualArray = actual == null || actual.isEmpty() ? null
+          : ((List) actual.get(0)).toArray();
+      CalciteAssert.assertArrayEqual("expected Elasticsearch query not found", strings,
+          actualArray);
     };
   }
 }

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/pom.xml
----------------------------------------------------------------------
diff --git a/elasticsearch5/pom.xml b/elasticsearch5/pom.xml
index 0fe9df9..9525cd5 100644
--- a/elasticsearch5/pom.xml
+++ b/elasticsearch5/pom.xml
@@ -112,10 +112,6 @@ limitations under the License.
       <version>${hppc.version}</version>
     </dependency>
     <dependency>
-      <groupId>com.google.code.findbugs</groupId>
-      <artifactId>jsr305</artifactId>
-    </dependency>
-    <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
     </dependency>

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Enumerator.java
----------------------------------------------------------------------
diff --git a/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Enumerator.java b/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Enumerator.java
index 4ebb626..104840a 100644
--- a/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Enumerator.java
+++ b/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Enumerator.java
@@ -72,22 +72,16 @@ public class Elasticsearch5Enumerator implements Enumerator<Object> {
   }
 
   private static Function1<SearchHit, Map> mapGetter() {
-    return new Function1<SearchHit, Map>() {
-      public Map apply(SearchHit searchHitFields) {
-        return (Map) searchHitFields.getFields();
-      }
-    };
+    return searchHitFields -> (Map) searchHitFields.getFields();
   }
 
   private static Function1<SearchHit, Object> singletonGetter(final String fieldName,
       final Class fieldClass) {
-    return new Function1<SearchHit, Object>() {
-      public Object apply(SearchHit searchHitFields) {
-        if (searchHitFields.getFields().isEmpty()) {
-          return convert(searchHitFields.getSource(), fieldClass);
-        } else {
-          return convert(searchHitFields.getFields(), fieldClass);
-        }
+    return searchHitFields -> {
+      if (searchHitFields.getFields().isEmpty()) {
+        return convert(searchHitFields.getSource(), fieldClass);
+      } else {
+        return convert(searchHitFields.getFields(), fieldClass);
       }
     };
   }
@@ -101,22 +95,20 @@ public class Elasticsearch5Enumerator implements Enumerator<Object> {
    */
   private static Function1<SearchHit, Object[]> listGetter(
       final List<Map.Entry<String, Class>> fields) {
-    return new Function1<SearchHit, Object[]>() {
-      public Object[] apply(SearchHit searchHitFields) {
-        Object[] objects = new Object[fields.size()];
-        for (int i = 0; i < fields.size(); i++) {
-          final Map.Entry<String, Class> field = fields.get(i);
-          final String name = field.getKey();
-          if (searchHitFields.getFields().isEmpty()) {
-            objects[i] = convert(searchHitFields.getSource().get(name),
-                field.getValue());
-          } else {
-            objects[i] = convert(searchHitFields.getField(name).getValue(),
-                field.getValue());
-          }
+    return searchHitFields -> {
+      Object[] objects = new Object[fields.size()];
+      for (int i = 0; i < fields.size(); i++) {
+        final Map.Entry<String, Class> field = fields.get(i);
+        final String name = field.getKey();
+        if (searchHitFields.getFields().isEmpty()) {
+          objects[i] = convert(searchHitFields.getSource().get(name),
+              field.getValue());
+        } else {
+          objects[i] = convert(searchHitFields.getField(name).getValue(),
+              field.getValue());
         }
-        return objects;
       }
+      return objects;
     };
   }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Schema.java
----------------------------------------------------------------------
diff --git a/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Schema.java b/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Schema.java
index b5e0f34..adf0fa2 100644
--- a/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Schema.java
+++ b/elasticsearch5/src/main/java/org/apache/calcite/adapter/elasticsearch5/Elasticsearch5Schema.java
@@ -21,9 +21,7 @@ import org.apache.calcite.schema.Table;
 import org.apache.calcite.schema.impl.AbstractSchema;
 
 import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
-
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
@@ -44,6 +42,7 @@ import java.net.InetSocketAddress;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 /**
  * Schema mapped onto an index of ELASTICSEARCH types.
@@ -97,8 +96,8 @@ public class Elasticsearch5Schema extends AbstractSchema
    */
   @VisibleForTesting
   Elasticsearch5Schema(Client client, String index) {
-    this.client = Preconditions.checkNotNull(client, "client");
-    this.index = Preconditions.checkNotNull(index, "index");
+    this.client = Objects.requireNonNull(client, "client");
+    this.index = Objects.requireNonNull(index, "index");
   }
 
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchNode.java
----------------------------------------------------------------------
diff --git a/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchNode.java b/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchNode.java
index cd8af9a..a28b6e0 100644
--- a/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchNode.java
+++ b/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchNode.java
@@ -34,6 +34,7 @@ import org.elasticsearch.transport.Netty3Plugin;
 import java.io.File;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.Objects;
 
 /**
  * Represents a single elastic search node which can run embedded in a java application.
@@ -45,7 +46,7 @@ class EmbeddedElasticsearchNode implements AutoCloseable {
   private volatile boolean  isStarted;
 
   private EmbeddedElasticsearchNode(Node node) {
-    this.node = Preconditions.checkNotNull(node, "node");
+    this.node = Objects.requireNonNull(node, "node");
   }
 
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/d59b639d/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchPolicy.java
----------------------------------------------------------------------
diff --git a/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchPolicy.java b/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchPolicy.java
index 6db2ddb..8cd2425 100644
--- a/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchPolicy.java
+++ b/elasticsearch5/src/test/java/org/apache/calcite/adapter/elasticsearch5/EmbeddedElasticsearchPolicy.java
@@ -16,13 +16,12 @@
  */
 package org.apache.calcite.adapter.elasticsearch5;
 
-import com.google.common.base.Preconditions;
-
 import org.elasticsearch.client.Client;
 import org.elasticsearch.common.transport.TransportAddress;
-
 import org.junit.rules.ExternalResource;
 
+import java.util.Objects;
+
 /**
  * Junit rule that is used to initialize a single Elasticsearch node for tests.
  *
@@ -56,7 +55,7 @@ class EmbeddedElasticsearchPolicy extends ExternalResource {
   private final EmbeddedElasticsearchNode node;
 
   private EmbeddedElasticsearchPolicy(EmbeddedElasticsearchNode resource) {
-    this.node = Preconditions.checkNotNull(resource, "resource");
+    this.node = Objects.requireNonNull(resource, "resource");
   }
 
   @Override protected void before() throws Throwable {