alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (ImmutableGraph.java)

This example Java source code file (ImmutableGraph.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

abstractconfigurablegraph, adjacency, deprecated, illegalstateexception, immutablegraph, immutablemap, network, network_with_parallel_edge, nodeadjacencies, set, suppresswarnings, util

The ImmutableGraph.java Java example source code

/*
 * Copyright (C) 2014 The Guava Authors
 *
 * Licensed 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 com.google.common.graph;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.graph.GraphConstants.NETWORK_WITH_PARALLEL_EDGE;

import com.google.common.collect.ImmutableMap;
import com.google.common.graph.DirectedNodeAdjacencies.Adjacency;

import java.util.Set;

/**
 * A {@link Graph} whose relationships are constant. Instances of this class may be obtained
 * with {@link #copyOf(Graph)}.
 *
 * @author James Sexton
 * @author Joshua O'Madadhain
 * @author Omar Darwish
 * @param <N> Node parameter type
 */
public final class ImmutableGraph<N> extends AbstractConfigurableGraph {

  private ImmutableGraph(Graph<N> graph) {
    super(GraphBuilder.from(graph), getNodeConnections(graph));
  }

  /**
   * Returns an immutable copy of {@code graph}.
   */
  @SuppressWarnings("unchecked")
  public static <N> ImmutableGraph copyOf(Graph graph) {
    // TODO(b/28087289): we can remove this restriction when Graph supports parallel edges
    checkArgument(!((graph instanceof Network) && ((Network<N, ?>) graph).allowsParallelEdges()),
        NETWORK_WITH_PARALLEL_EDGE);
    return (graph instanceof ImmutableGraph)
        ? (ImmutableGraph<N>) graph
        : new ImmutableGraph<N>(graph);
  }

  /**
   * Simply returns its argument.
   *
   * @deprecated no need to use this
   */
  @Deprecated
  public static <N> ImmutableGraph copyOf(ImmutableGraph graph) {
    return checkNotNull(graph);
  }

  private static <N> ImmutableMap> getNodeConnections(Graph graph) {
    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will
    // have whatever ordering the graph's edges do, so ImmutableSortedMap is unnecessary even if the
    // input edges are sorted.
    ImmutableMap.Builder<N, NodeAdjacencies nodeConnections = ImmutableMap.builder();
    for (N node : graph.nodes()) {
      nodeConnections.put(node, nodeConnectionsOf(graph, node));
    }
    return nodeConnections.build();
  }

  private static <N> NodeAdjacencies nodeConnectionsOf(Graph graph, N node) {
    return graph.isDirected()
        ? DirectedNodeAdjacencies.ofImmutable(createAdjacencyMap(
            graph, node), graph.predecessors(node).size(), graph.successors(node).size())
        : UndirectedNodeAdjacencies.ofImmutable(graph.adjacentNodes(node));
  }

  private static <N> ImmutableMap createAdjacencyMap(Graph graph, N node) {
    Set<N> predecessors = graph.predecessors(node);
    Set<N> successors = graph.successors(node);
    ImmutableMap.Builder<N, Adjacency> nodeAdjacencies = ImmutableMap.builder();
    for (N adjacentNode : graph.adjacentNodes(node)) {
      nodeAdjacencies.put(adjacentNode,
          getAdjacency(predecessors.contains(adjacentNode), successors.contains(adjacentNode)));
    }
    return nodeAdjacencies.build();
  }

  private static Adjacency getAdjacency(boolean isPredecessor, boolean isSuccesor) {
    if (isPredecessor && isSuccesor) {
      return Adjacency.BOTH;
    } else if (isPredecessor) {
      return Adjacency.PRED;
    } else if (isSuccesor) {
      return Adjacency.SUCC;
    } else {
      throw new IllegalStateException();
    }
  }
}

Other Java examples (source code examples)

Here is a short list of links related to this Java ImmutableGraph.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.