Example usage for org.apache.commons.collections4.map MultiValueMap MultiValueMap

List of usage examples for org.apache.commons.collections4.map MultiValueMap MultiValueMap

Introduction

In this page you can find the example usage for org.apache.commons.collections4.map MultiValueMap MultiValueMap.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public MultiValueMap() 

Source Link

Document

Creates a MultiValueMap based on a HashMap and storing the multiple values in an ArrayList.

Usage

From source file:name.abhijitsarkar.programminginterviews.hashtables.PracticeQuestionsCh12.java

@SuppressWarnings("unchecked")
public static List<List<String>> anagrams(final List<String> dictionary) {
    final MultiMap<Integer, Integer> anagramMap = new MultiValueMap<Integer, Integer>();

    char[] arr = null;
    int hashCode = -1;

    for (int i = 0; i < dictionary.size(); ++i) {
        arr = dictionary.get(i).toCharArray();
        Arrays.sort(arr);/*from  w w w  . java 2  s .c o m*/

        hashCode = String.valueOf(arr).hashCode();

        anagramMap.put(hashCode, i);
    }

    final List<List<String>> anagrams = new ArrayList<>();
    final Set<Entry<Integer, Object>> anagramIndices = anagramMap.entrySet();
    List<Integer> aSet = null;

    for (final Object o : anagramIndices) {
        aSet = (List<Integer>) ((Entry<Integer, Object>) o).getValue();

        if (aSet.size() > 1) {
            final List<String> an = new ArrayList<>();

            for (final int i : aSet) {
                an.add(dictionary.get(i));
            }
            anagrams.add(an);
        }
    }

    return anagrams;
}

From source file:com.farhad.ngram.lang.detector.util.FileTools.java

public MultiValueMap readFile(String path) {
    //Map<String, String> corpus=new HashMap<>();
    MultiValueMap corpus = new MultiValueMap();

    try {/*from  ww  w.  java  2 s  . c om*/
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF8"));

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            //System.out.println(sCurrentLine);
            String[] parts = sCurrentLine.split(",'");

            String key = parts[0];
            String text = parts[1];
            text = text.substring(0, text.length() - 1);
            // replace spaces with _
            // text=text.replaceAll("\\s+", "_").toLowerCase();
            //replace number and punctuations with blankspace
            text = text.replaceAll("\\p{Punct}+", "");
            text = text.replaceAll("\\d+", "");
            text = text.replaceAll("\\s+", " ");
            // System.err.println(key + "| "+ text);

            corpus.put(key, text.toLowerCase());
            //                                

        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return corpus;
}

From source file:fr.cph.chicago.data.AlertData.java

/**
 * Connect to CTA API to get the alerts messages
 * /*from   w w  w .  ja  v a  2  s.  com*/
 * @return a list of alert
 * @throws ParserException
 *             a parse exception
 * @throws ConnectException
 *             a connect exception
 */
public final List<Alert> loadGeneralAlerts() throws ParserException, ConnectException {
    if (mAlerts.size() == 0) {
        MultiMap<String, String> params = new MultiValueMap<String, String>();
        CtaConnect connect = CtaConnect.getInstance();
        Xml xml = new Xml();
        String xmlResult = connect.connect(CtaRequestType.ALERTS_GENERAL, params);
        mAlerts = xml.parseAlertGeneral(xmlResult);
    }
    return mAlerts;
}

From source file:com.yahoo.elide.core.EntityBinding.java

private EntityBinding() {
    jsonApi = null;/*from  w w  w .j a  v a 2s. c o  m*/
    idField = null;
    idType = null;
    attrsDeque = null;
    attrs = null;
    relationshipsDeque = null;
    relationships = null;
    relationshipTypes = null;
    relationshipToInverse = null;
    fieldsToValues = null;
    fieldsToTypes = null;
    fieldsToTriggers = new MultiValueMap();
    aliasesToFields = null;
    accessibleObject = null;
}

From source file:com.yahoo.elide.core.EntityBinding.java

public EntityBinding(Class<?> cls, String type) {
    // Map id's, attributes, and relationships
    Collection<AccessibleObject> fieldOrMethodList = CollectionUtils.union(Arrays.asList(cls.getFields()),
            Arrays.asList(cls.getMethods()));

    jsonApi = type;/*from  w  w  w .  j av a  2  s. c  om*/
    // Initialize our maps for this entity. Duplicates are checked above.
    attrsDeque = new ConcurrentLinkedDeque<>();
    relationshipsDeque = new ConcurrentLinkedDeque<>();
    relationshipTypes = new ConcurrentHashMap<>();
    relationshipToInverse = new ConcurrentHashMap<>();
    fieldsToValues = new ConcurrentHashMap<>();
    fieldsToTypes = new ConcurrentHashMap<>();
    fieldsToTriggers = new MultiValueMap<>();
    aliasesToFields = new ConcurrentHashMap<>();
    accessibleObject = new ConcurrentHashMap<>();
    bindEntityFields(cls, type, fieldOrMethodList);
    bindAccessibleObjects(cls, fieldOrMethodList);

    attrs = dequeToList(attrsDeque);
    relationships = dequeToList(relationshipsDeque);
}

From source file:com.offbynull.peernetic.debug.visualizer.JGraphXVisualizer.java

/**
 * Creates a {@link JGraphXVisualizer} object.
 *//*from  w w  w  .  j  a  va 2  s.  c  om*/
public JGraphXVisualizer() {

    graph = new mxGraph();
    graph.setCellsEditable(false);
    graph.setAllowDanglingEdges(false);
    graph.setAllowLoops(false);
    graph.setCellsDeletable(false);
    graph.setCellsCloneable(false);
    graph.setCellsDisconnectable(false);
    graph.setDropEnabled(false);
    graph.setSplitEnabled(false);
    graph.setCellsBendable(false);
    graph.setConnectableEdges(false);
    graph.setCellsMovable(false);
    graph.setCellsResizable(false);
    graph.setAutoSizeCells(true);

    component = new mxGraphComponent(graph);
    component.setConnectable(false);

    component.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    component.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

    nodeLookupMap = new DualHashBidiMap<>();
    connToEdgeLookupMap = new MultiValueMap<>();
    edgeToConnLookupMap = new HashMap<>();
    vertexLingerTriggerMap = new HashMap<>();

    textOutputArea = new JTextArea();
    textOutputArea.setLineWrap(false);
    textOutputArea.setEditable(false);
    JScrollPane textOutputScrollPane = new JScrollPane(textOutputArea);
    textOutputScrollPane.setPreferredSize(new Dimension(0, 100));

    frame = new JFrame("Visualizer");
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, component, textOutputScrollPane);
    splitPane.setResizeWeight(1.0);

    frame.setContentPane(splitPane);

    component.addComponentListener(new ComponentAdapter() {

        @Override
        public void componentResized(ComponentEvent e) {
            zoomFit();
        }
    });

    frame.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            Recorder<A> rec = recorder.get();
            if (rec != null) {
                IOUtils.closeQuietly(rec);
            }

            VisualizerEventListener veListener = listener.get();
            if (veListener != null) {
                veListener.closed();
            }
        }
    });

    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    splitPane.setDividerLocation(0.2);
}

From source file:fr.cph.chicago.data.BusData.java

/**
 * Load bus routes from CTA API/*w  w w  .j  av a  2 s. c  o  m*/
 * 
 * @return a list of bus route
 * @throws ParserException
 *             a parser exception
 * @throws ConnectException
 *             a connect exception
 */
public final List<BusRoute> loadBusRoutes() throws ParserException, ConnectException {
    if (mRoutes.size() == 0) {
        MultiMap<String, String> params = new MultiValueMap<String, String>();
        CtaConnect connect = CtaConnect.getInstance();
        Xml xml = new Xml();
        String xmlResult = connect.connect(CtaRequestType.BUS_ROUTES, params);
        mRoutes = xml.parseBusRoutes(xmlResult);
    }
    return mRoutes;
}

From source file:fr.cph.chicago.activity.StationActivity.java

@SuppressWarnings("unchecked")
@Override/*from  w  ww . j av a  2s.  co m*/
protected final void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ChicagoTracker.checkTrainData(this);
    if (!this.isFinishing()) {
        // Load data
        DataHolder dataHolder = DataHolder.getInstance();
        this.mTrainData = dataHolder.getTrainData();

        mIds = new HashMap<String, Integer>();

        // Load right xml
        setContentView(R.layout.activity_station);

        // Get station id from bundle extra
        if (mStationId == null) {
            mStationId = getIntent().getExtras().getInt("stationId");
        }

        // Get station from station id
        mStation = mTrainData.getStation(mStationId);

        MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
        reqParams.put("mapid", String.valueOf(mStation.getId()));
        new LoadData().execute(reqParams);

        // Call google street api to load image
        new DisplayGoogleStreetPicture().execute(mStation.getStops().get(0).getPosition());

        this.mIsFavorite = isFavorite();

        TextView textView = (TextView) findViewById(R.id.activity_bike_station_station_name);
        textView.setText(mStation.getName().toString());

        mStreetViewImage = (ImageView) findViewById(R.id.activity_bike_station_streetview_image);

        mStreetViewText = (TextView) findViewById(R.id.activity_bike_station_steetview_text);

        mMapImage = (ImageView) findViewById(R.id.activity_bike_station_map_image);

        mDirectionImage = (ImageView) findViewById(R.id.activity_bike_station_map_direction);

        mFavoritesImage = (ImageView) findViewById(R.id.activity_bike_station_favorite_star);
        if (mIsFavorite) {
            mFavoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_active));
        }
        mFavoritesImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StationActivity.this.switchFavorite();
            }
        });

        LinearLayout stopsView = (LinearLayout) findViewById(R.id.activity_bike_station_details);

        this.mParamsStop = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        Map<TrainLine, List<Stop>> stops = mStation.getStopByLines();
        CheckBox checkBox = null;
        for (Entry<TrainLine, List<Stop>> e : stops.entrySet()) {
            final TrainLine line = e.getKey();
            List<Stop> stopss = e.getValue();
            Collections.sort(stopss);
            LayoutInflater layoutInflater = (LayoutInflater) ChicagoTracker.getAppContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.activity_station_line_title, null);

            TextView lineTextView = (TextView) view.findViewById(R.id.activity_bus_station_value);
            lineTextView.setText(line.toStringWithLine());

            TextView lineColorTextView = (TextView) view.findViewById(R.id.activity_bus_color);
            lineColorTextView.setBackgroundColor(line.getColor());
            stopsView.addView(view);

            for (final Stop stop : stopss) {
                LinearLayout line2 = new LinearLayout(this);
                line2.setOrientation(LinearLayout.HORIZONTAL);
                line2.setLayoutParams(mParamsStop);

                checkBox = new CheckBox(this);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        Preferences.saveTrainFilter(mStationId, line, stop.getDirection(), isChecked);
                    }
                });
                checkBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Update timing
                        MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
                        reqParams.put("mapid", String.valueOf(mStation.getId()));
                        new LoadData().execute(reqParams);
                    }
                });
                checkBox.setChecked(Preferences.getTrainFilter(mStationId, line, stop.getDirection()));
                checkBox.setText(stop.getDirection().toString());
                checkBox.setTextColor(getResources().getColor(R.color.grey));

                line2.addView(checkBox);
                stopsView.addView(line2);

                LinearLayout line3 = new LinearLayout(this);
                line3.setOrientation(LinearLayout.VERTICAL);
                line3.setLayoutParams(mParamsStop);
                int id3 = Util.generateViewId();
                line3.setId(id3);
                mIds.put(line.toString() + "_" + stop.getDirection().toString(), id3);

                stopsView.addView(line3);
            }

        }
        getActionBar().setDisplayHomeAsUpEnabled(true);

        Util.trackScreen(this, R.string.analytics_train_details);
    }
}

From source file:fr.cph.chicago.data.BusData.java

/**
 * Load from CTA API a bus stop list/*  w w  w.j a va  2 s . com*/
 * 
 * @param stopId
 *            the stop id
 * @param bound
 *            the direction
 * @return a bus stop list
 * @throws ConnectException
 *             a connect exception
 * @throws ParserException
 *             a parser exception
 */
public final List<BusStop> loadBusStop(final String stopId, final String bound)
        throws ConnectException, ParserException {
    CtaConnect connect = CtaConnect.getInstance();
    MultiMap<String, String> param = new MultiValueMap<String, String>();
    param.put("rt", stopId);
    param.put("dir", bound);
    List<BusStop> busStops = null;
    String xmlResult = connect.connect(CtaRequestType.BUS_STOP_LIST, param);
    Xml xml = new Xml();
    busStops = xml.parseBusBounds(xmlResult);
    return busStops;
}

From source file:fr.cph.chicago.task.GlobalConnectTask.java

@Override
protected final Boolean doInBackground(final Void... connects) {
    mTrainBoolean = true;//  www .j a  v  a2s . c  o  m
    mBusBoolean = true;
    mBikeBoolean = true;
    mNetworkAvailable = Util.isNetworkAvailable();
    if (mNetworkAvailable) {
        CtaConnect ctaConnect = CtaConnect.getInstance();
        DivvyConnect divvyConnect = DivvyConnect.getInstance();
        if (mLoadTrains) {
            try {
                for (Entry<String, Object> entry : mParams.entrySet()) {
                    String key = entry.getKey();
                    if (key.equals("mapid")) {
                        Object value = entry.getValue();
                        if (value instanceof String) {
                            String xmlResult = ctaConnect.connect(mRequestType, mParams);
                            this.mTrainArrivals = mXml.parseArrivals(xmlResult, mData);
                        } else if (value instanceof List) {
                            @SuppressWarnings("unchecked")
                            List<String> list = (List<String>) value;
                            if (list.size() < 5) {
                                String xmlResult = ctaConnect.connect(mRequestType, mParams);
                                this.mTrainArrivals = mXml.parseArrivals(xmlResult, mData);
                            } else {
                                int size = list.size();
                                SparseArray<TrainArrival> tempArrivals = new SparseArray<TrainArrival>();
                                int start = 0;
                                int end = 4;
                                while (end < size + 1) {
                                    List<String> subList = list.subList(start, end);
                                    MultiMap<String, String> paramsTemp = new MultiValueMap<String, String>();
                                    for (String sub : subList) {
                                        paramsTemp.put(key, sub);
                                    }

                                    String xmlResult = ctaConnect.connect(mRequestType, paramsTemp);
                                    SparseArray<TrainArrival> temp = mXml.parseArrivals(xmlResult, mData);
                                    for (int j = 0; j < temp.size(); j++) {
                                        tempArrivals.put(temp.keyAt(j), temp.valueAt(j));
                                    }
                                    start = end;
                                    if (end + 3 >= size - 1 && end != size) {
                                        end = size;
                                    } else {
                                        end = end + 3;
                                    }
                                }
                                this.mTrainArrivals = tempArrivals;
                            }
                        }
                    }
                }

                // Apply filters
                int index = 0;
                while (index < mTrainArrivals.size()) {
                    TrainArrival arri = mTrainArrivals.valueAt(index++);
                    List<Eta> etas = arri.getEtas();
                    // Sort Eta by arriving time
                    Collections.sort(etas);
                    // Copy data into new list to be able to avoid looping on a list that we want to
                    // modify
                    List<Eta> etas2 = new ArrayList<Eta>();
                    etas2.addAll(etas);
                    int j = 0;
                    Eta eta = null;
                    Station station = null;
                    TrainLine line = null;
                    TrainDirection direction = null;
                    for (int i = 0; i < etas2.size(); i++) {
                        eta = etas2.get(i);
                        station = eta.getStation();
                        line = eta.getRouteName();
                        direction = eta.getStop().getDirection();
                        boolean toRemove = Preferences.getTrainFilter(station.getId(), line, direction);
                        if (!toRemove) {
                            etas.remove(i - j++);
                        }
                    }
                }

            } catch (ConnectException e) {
                mTrainBoolean = false;
                this.mTrackerTrainException = e;
            } catch (ParserException e) {
                mTrainBoolean = false;
                this.mTrackerTrainException = e;
            }
        }
        if (mLoadBuses) {
            try {
                List<String> rts = new ArrayList<String>();
                List<String> stpids = new ArrayList<String>();
                for (Entry<String, Object> entry : mParams2.entrySet()) {
                    String key = entry.getKey();
                    StringBuilder str = new StringBuilder();
                    int i = 0;
                    @SuppressWarnings("unchecked")
                    List<String> values = (ArrayList<String>) entry.getValue();
                    for (String v : values) {
                        str.append(v + ",");
                        if (i == 9 || i == values.size() - 1) {
                            if (key.equals("rt")) {
                                rts.add(str.toString());
                            } else if (key.equals("stpid")) {
                                stpids.add(str.toString());
                            }
                            str = new StringBuilder();
                            i = -1;
                        }
                        i++;
                    }
                }
                for (int i = 0; i < rts.size(); i++) {
                    MultiMap<String, String> para = new MultiValueMap<String, String>();
                    para.put("rt", rts.get(i));
                    para.put("stpid", stpids.get(i));
                    String xmlResult = ctaConnect.connect(mRequestType2, para);
                    this.mBusArrivals.addAll(mXml.parseBusArrivals(xmlResult));
                }
            } catch (ConnectException e) {
                mBusBoolean = false;
                this.mTrackerBusException = e;
            } catch (ParserException e) {
                mBusBoolean = false;
                this.mTrackerBusException = e;
            }
        }
        if (mLoadBikes) {
            try {
                String bikeContent = divvyConnect.connect();
                this.mBikeStations = mJson.parseStations(bikeContent);
                Collections.sort(this.mBikeStations, Util.BIKE_COMPARATOR_NAME);
            } catch (ParserException e) {
                mBikeBoolean = false;
                this.mTrackerBikeException = e;
            } catch (ConnectException e) {
                mBikeBoolean = false;
                this.mTrackerBikeException = e;
            } finally {
                if (!(mBusBoolean && mTrainBoolean)) {
                    if (mParams2.size() == 0 && mBusBoolean) {
                        mBusBoolean = false;
                    }
                    if (mParams.size() == 0 && mTrainBoolean) {
                        mTrainBoolean = false;
                    }
                }
            }
        }
        return mTrainBoolean || mBusBoolean || mBikeBoolean;
    } else {
        return mNetworkAvailable;
    }
}