Philip St
Philip St

Reputation: 89

String to Hashtable

I wrote a simple program which reads IpTables log results , remove 90% of the output , and what is left is:

192.168.1.1 152
192.168.1.1 17485
192.168.1.1 5592

Where, the first column contains source IP , the second one destination Port. Those values are stored in a string. I would like to transfer the values from that string to a Hashtable, but I don't have any idea how.

Hashtable<String, String> IpDpt = new Hashtable<String, String>();

        hmIpDpt.put(IP1,DPT1);
        hmIpDpt.put(IP1,DPT2);
        hmIpDpt.put(IP1,DPT3);
        hmIpDpt.put(IP2,DPT4);

Upvotes: 1

Views: 2676

Answers (5)

Amit Kumar user3037405
Amit Kumar user3037405

Reputation: 390

Try this program.

String info = "192.168.1.1 152";
    Hashtable<String, List<String>> IpDpt = new Hashtable<String, List<String>>();
    String[] values = info.split( " " );
    String key = values[0];
    String value = values[1];
    if ( IpDpt.containsKey( key ) )
        IpDpt.get( key ).add( value );
    else
        IpDpt.put( key, new ArrayList<String>( Arrays.asList( value ) ) );

To check whether the key has at least 100 values

if(IpDpt.containsKey( key ) && IpDpt.get( key ).size() >=100) 
{ 
    // business logic here 
}

Upvotes: 2

Masudul
Masudul

Reputation: 21981

Use Guava Multimap to allow duplicate key.

  Multimap<String,String> multimap=ArrayListMultimap.create();

  //put your ips and port.

Upvotes: 0

isnot2bad
isnot2bad

Reputation: 24454

A Map cannot hold multiple values per key. So you should either use a third party library that offers something like a MultiMap, or use a Set to hold the values:

Map<String, Set<String>> ipToPortMap = new HashMap<>();

public void addEntry(String ip, String port) {
    Set<String> ports = ipToPortMap.get(ip);
    if (ports == null) {
        ports = new HashSet<>();
        ipToPortMap.put(ip, ports);
    }

    ports.add(port);
}

Now just iterate over your input (maybe using a Scanner) and call addEntry.

Upvotes: 0

benjamin.d
benjamin.d

Reputation: 2881

For every line you read, split the string on space like that:

    String line = "192.168.1.1 152";
    String[] parts = line.split(" ");
    you_map.put(parts[0], parts[1]);

That should do it.

Upvotes: 0

shreyansh jogi
shreyansh jogi

Reputation: 2102

if you transferred to hashtable then you will not have all the logs available because hashtable does not allows duplicate values and in your log there may be chances of duplicate values . so hashtable overrides values.

Upvotes: 4

Related Questions