Collecting data from Vector to Map
I wrote the following piece of code and want to hear your opinion, in this snippet I have a vector called aggregateFeaturesForML which has elements of Class with 3 fields: sourceip, key, value. what I want is to collect all the key-value pairs that have the same sourceip and form a nice histogram (for each IP the keys are unique), for that purpose I collect the key-value pairs in a map called histogram and then use its toString function to print a
private HashMap > aggregator; protected Vector aggregateFeaturesForML = new Vector(); //Single result has 3 fields: IP, key, value
String previousIp = aggregateFeaturesForML.get(0).getSourceip(); if(!aggregator.containsKey(previousIp)) < aggregator.put(previousIp, new HashMap()); > HashMap histogram = new HashMap(); for(int iterator=0;iterator histogram.clear(); previousIp = ip; > histogram.put(sr.getKey(), sr.getValue()); > HashMap mapForIP = aggregator.get(previousIp); mapForIP.put(key, histogram.toString()); aggregator.put(previousIp, mapForIP);
Please Help: Putting Vector objects into HashMap
posted 20 years ago
The problem I have is about passing one Collection object into another, such as passing a Vector object into a Hashmap. I’ve tried to do this in the two files included below: VectorToHash.java and VectorToHashTest.java.
The problem specification is: I put values into a Vector object and then passed it to a Hashmap and then I want to retieve those values out. I also want to associate each Vector object passed to the Hashmap with a Key object. I’ve made an attempt to do this below in the two .java files mensioned, but I’m stuck. Although the code does compile, I need help to correct it to work as specified. Could you help me correct my code, and help me understand what problem situations would require a Vector object to be passed to a Hashmap?
Many Thanks,
Mark Yadav.
VectorToHash.java
// VectorToHash.java — the purpose of theis class is to create methods
// that allow a Vector containing Strings to be added to a HashMap.
// The Test program: VectorToHashTest then returns the vector from
// the HashMap and then extracts the values from the vector.
import java.util.*;
public class VectorToHash
// HashMap to store vector
HashMap book = new HashMap();
Vector v = new Vector();
String[] fruit = ;
Integer[] Integer[5];
// Method to add fruit to vector.
// A vector is then returned
public Vector addFruit(Vector v) for(int i = 0; i < fruit.length; i++)
v.add(fruit[i]);
return v;
>
// method to add vector to HashMap. The retuned Vector
// from the previous method is added to the HashMap
public void addVector(Vector v, HashMap m) for(int i = 0; i < 5; i++)
m.put(id[i], v);
>
>
VectorToHashTest.java
// VectorToHashTest.java Tests the VectorToHash class
import java.util.*;
class VectorToHashTest public static void main(String[] args) // Vector object
Vector b = new Vector();
Vector c = new Vector();
// HashMap object
HashMap hp = new HashMap();
//
VectorToHash vth = new VectorToHash();
c = vth.addFruit(b);
// add vector to HashMap
vth.addVector(c,hp);
//output contents of HashMap
Set keys = hp.keySet();
Iterator keyIter = keys.iterator();
while(keyIter.hasNext())
System.out.println((Integer)keyIter.next());
>
>
Как использовать классы — коллекции ArrayList, Vector и HashMap предоставляемые Java Collections Framework
В этой статье, мы узнаем о трех важных классах — коллекций ArrayList, Vector и HashMap из Collections Framework и начнем использовать их в собственном коде. Используя классы — коллекции ArrayList и Vector , мы можем хранить группу элементов, в виде простых объектов и манипулировать ими, посредством различных методов, доступных в этих классах. Классы ArrayList и Vector доступны из пакете java.util . Другой класс — коллекция доступный из пакета java.util , это HashMap , который позволяет хранить коллекцию отображений: ключ – значение. Это дает возможность получать нужное значение из коллекции, когда известен ключ. Давайте рассмотрим примеры с использованием этих классов – коллекций по очереди. Пример 1. В этом примере мы напишем простую программу с использованием класса — коллекции ArrayList Листинг 1. Код выполнения примера 1
// подключаем класс import java.util.ArrayList; public class ArrayListExample < static String[] favouriteCharacters = ; int i; public ArrayList favouritelist = new ArrayList(); // метод добавляет элементы ‘favouriteCharacters’ в ‘favouritelist’ private void includeCharacters(String[]favouriteCharacters) < for (i = 0; i < favouriteCharacters.length; i++) < // добавление элементов по одному из массива ‘favouriteCharacters’ favouritelist.add(favouriteCharacters[i]); printCharacters(i); >// добавление элементов, посредством указания позиций favouritelist.add(1, "george"); favouritelist.add(4, "Peter"); > // метод выводит элемент ‘favouritelist’ по указанной позиции private void printCharacters(int i) < System.out.println("Character " + (i + 1) + ":" + favouritelist.get(i)); >// метод выводит все элементы ‘favouritelist’ private void printCharacters() < System.out.println("\n"); for(int i=0;i> // метод возвращает размер коллекции ‘favouritelist’ private int sizeofCharactersList() < System.out.println("\n"); System.out.println("Total No of Characters in Array:" + favouriteCharacters.length); System.out.println("Total No of Characters in List:" + favouritelist.size()); return favouritelist.size(); >// метод выводит позицию элемента ‘favouritelist’ по указанному имени public void getCharacterPostion(String characterName) < System.out.println("\n"); System.out.println("The position of the character\t" + characterName + "\tis\t" + favouritelist.indexOf(characterName)); >// метод удаляет элемент ‘favouritelist’ по указанному имени public void removeCharacter(String characterName) < if(favouritelist.size()>favouriteCharacters.length) < favouritelist.remove(characterName); >else < System.out.println("\n"); System.out.println("The element\t"+favouritelist.get(favouritelist.indexOf(characterName))+"\tcannot be removed"); >> // метод удаляет элемент ‘favouritelist’ по указанной позиции public void removeCharacter(int i) < if(favouritelist.size()>favouriteCharacters.length) < favouritelist.remove(i); >else < System.out.println("The element\t"+favouritelist.get(i)+"\tcannot be removed"); >> public static void main(String args[]) < ArrayListExample example = new ArrayListExample(); example.includeCharacters(favouriteCharacters); example.printCharacters(); int size = example.sizeofCharactersList(); example.getCharacterPostion("Ron"); example.removeCharacter("Snape"); example.removeCharacter(2); example.sizeofCharactersList(); example.removeCharacter("Harry"); example.removeCharacter(4); >>
Character 1:Harry Character 2:Ron Character 3:Hermione Character 4:Snape Character 5:Dumbledore Character 6:Moody Character 7:Riddle Character 8:Fred Character1:Harry Character2:george Character3:Ron Character4:Hermione Character5:Peter Character6:Snape Character7:Dumbledore Character8:Moody Character9:Riddle Character10:Fred Total No of Characters in Array:8 Total No of Characters in List:10 The position of the character Ron is 2 Total No of Characters in Array:8 Total No of Characters in List:8 The element Harry cannot be removed The element Dumbledore cannot be removed
Давайте разберем пример приведенной программы, шаг за шагом. В этом примере, в первой же строке программы, мы импортируем класс — коллекцию ArrayList . Затем, мы по очереди инициализируем массив строк favouriteCharacters , содержащий имена людей и favouritelist — экземпляр коллекции ArrayList . Метод includeCharacters(args) может быть условно разделен на две части. В первой части метода, элементы добавляются из массива в коллекцию с помощью цикла. В этом случае, добавление элементов в ArrayList производится в том же самом порядке, в каком они расположены в массиве. Это происходит потому, что мы не определяем никаких позиций для элементов, которые добавляются в коллекцию. Но во второй части нашего метода, элементы добавляются с помощью индексации. В этом случае, добавление элементов в коллекцию производится по точно указанной позиции. При добавлении нового элемента в середину коллекции ArrayList , уже существующие в этой коллекции элементы, расположенные за указанной позицией вставки нового элемента, сдвигаются на следующие позиции от своих собственных, таким образом увеличивая размер коллекции. Когда мы взглянем на вывод вначале, мы увидим:
Total No of Characters in List: 10 Total No of Characters in Array: 8
Все потому, что помимо массива, имеющего 8 элементов, которые добавляются в ArrayList , мы явно добавляем еще 2 элемента, таким образом увеличивая размер коллекции до 10. Метод getCharacterPosition(args) принимает значение элемента(имя человека) и выводит позицию этого элемента в коллекции ArrayList . Если такого элемента нет в ArrayList , то выводится значение -1. Метод removeCharacter(args) удаляет указанное значение элемента(имя человека) из коллекции, принимая в качестве аргумента либо индекс этого элемент, либо сам элемент. В вышеприведенном коде, мы можем заметить, что размер нашей коллекции стал равен 8, вместо 10, по причине того, что мы удалили 2 элемента из коллекции. Если же размеры массива и коллекции совпадают, то метод возвращает следующие строки:
The element Harry cannot be removed The element Dumbledore cannot be removed
Выполнение метода removeCharacter(args) обусловлено только тем, что размер коллекции должен быть больше размера массива. Пример 2. В этом примере мы напишем простую программу с использованием класса — коллекции Vector Листинг 2. Код выполнения примере 2
// подключаем класс import java.util.Vector; public class VectorExample < Vector vector=new Vector(); public void addCharacterandPrint()< vector.add("Weasley"); vector.add("Potter"); for(int i=0;i> public static void main(String args[]) < VectorExample example=new VectorExample(); example.addCharacterandPrint(); >>
The characters are Weasley The characters are Potter
Вышеприведенный код, является всего лишь небольшим образцом, приведенным в качестве доказательства того, что нет большой разницы между коллекциями ArrayList и Vector . Коллекцией Vector можно манипулировать также, как и коллекцией ArrayList , используя те же методы. Пример 3. В этом примере мы напишем простую программу с использованием класса — коллекции HashMap Листинг 3. Код выполнения примера 3
// подключаем класс import java.util.HashMap; public class HashMapExample < HashMap hashMap=new HashMap(); String Books[]=; public void mapAuthors() < hashMap.put("Famous Five","Enid Blyton"); hashMap.put("Goosebumps","R.L.Stine"); hashMap.put("Nancy Drew","Carolyn Keene"); hashMap.put("The Cell","Christopher Pike"); hashMap.put("The Davinci Code","Dan Brown"); hashMap.put("Harry Potter","J.K. Rowling"); >public void getBookList() < for(int i=0;ielse < System.out.println("\nThe Imformation about the author of the book\t"+Books[i]+"\tis not available\n"); >> > public static void main(String args[]) < HashMapExample hashMapExample=new HashMapExample(); hashMapExample.mapAuthors(); hashMapExample.getBookList(); >>
Author1: Enid Blyton Famous Five Author2: R.L.Stine Goosebumps The Information about the author of the book Robinson Crusueo is not available Author4: Carolyn Keene Nancy Drew Author5: Christopher Pike The Cell Author6: Dan Brown The Davinci Code Author7: J.K. Rowling Harry Potter
Давайте разберем код программы приведенной выше, шаг за шагом. В этом примере программы, мы имеем массив строк , элементы которого — названия известных книг. Метод mapAuthors() создает отображение названий книг с их авторами. Ключами здесь являются названия книг, а значениями — авторы этих книг. Когда вызывается метод getBookList() , он выполняет итерацию массива Books и получает по очереди названия книг. Далее метод проверяет имеет ли какая-нибудь книга своего автора. Как мы можем заметить, если метод не может найти автора книги, то выводится сообщение not available . В противном случае выводится один за другим автор и его книга. Заключение: В приведенной статье, мы немного изучили классы — коллекции ArrayList , Vector , HashMap и попробовали использовать их в собственном коде. Оригинал статьи: How to use ArrayList, Vector and HashMap classes provided by Java Collections Framework
HashMap and Vector
posted 12 years ago
I am in progress to write a program that analyzes a text-input. It should print out the letters, occurence of a letter and its percentual value of all letters in the text («abba» would mean a and b have 50% each). Now I have decided to use HashMap where the letter would be the key, and the value would be a Vector holding the count of the letter and its percentage (is that even possible in a single Vector?). But I’m kinda stuck in the implementation phase, I can’t see what I’m doing wrong.
When I print out my HashMap it returns the letters (in scrambled order), and the vector which is same for all letters (what I want is just the letter, its count and a percentage). Here is what I have so far:
[edit — i moved the comment on line 22 up one line to prevent one REALLY long line]posted 12 years ago
I am not getting your precise point, but for correct results you should use double as holder of length.
Marshal
posted 12 years ago
That doesn’t look at all good. You really need to write down on a sheet of paper what you are going to do. It needs to be in words of one syllable. Then, from that you can change the algorithm into code.
You don’t need to count entries if you insist on using a List, because a List has a very easy method of counting. You can find the details in the documentation.
Why are you using Vector in the first place? Use ArrayList.
Your generics looks all confused to me; you are going on about and inserting Integers.
What does the line about setElementAt do? I find it incomprehensible.
Don’t go mixing chars and number literals. Where do you get 26 from? Are you sure you have written it correctly? Why don’t you write small a and small z? What about 97? Is that supposed to be small a? If so, write small a.
There are methods in the Character class which allow you to test whether something is a bona fide letter.
I am afraid if it were me, I would go back to the sheet of paper and start from scratch.