How to create a loop through LinkedHashMap<String,ArrayList<String>>? - java

Please help me to create a loop through LinkedHashMap<String,ArrayList<String>> h:
if (h.get("key1").size() == 0)
System.out.println("There is no errors in key1.");
else
System.out.println("ERROR: there are unexpected errors in key1.");
if (h.get("key2").size() == 0)
System.out.println("There is no errors in key2.");
else
System.out.println("ERROR: there are unexpected errors in key2.");
if (h.get("key3").size() == 0)
System.out.println("There is no errors in key3.");
else
System.out.println("ERROR: there are unexpected errors in key3.");
if (h.get("key4").size() == 0)
System.out.println("There is no errors in key4.\n");
else
System.out.println("ERROR: there are unexpected errors in key4.\n");

Like this?
for (String key : h.keySet())
{
System.out.println("Key: " + key);
for(String str : h.get(key))
{
System.out.println("\t" +str);
}
}
EDIT:
for (String key : h.keySet())
{
if(h.get(key).size() == 0)
{
System.out.println("There is no errors in " + key) ;
}
else
{
System.out.println("ERROR: there are unexpected errors in " + key);
}
}

Try this code:
Map<String, ArrayList<String>> a = new LinkedHashMap<String, ArrayList<String>>();
Iterator<Entry<String,ArrayList<String>>> itr = a.entrySet().iterator();
while (itr.hasNext()) {
Entry<String,ArrayList<String>> entry = itr.next();
String key = entry.getKey();
System.out.println("key: " + key);
List<String> list = entry.getValue();
System.out.println("value: " + list);
}

Another way in Java8 is with the foreach() method
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});

Related

How to display the first row of results from extracted data?

I used the following script to read a CSV file and extract suspicious data in descending order. I am trying to print out the result of the highest occurrence which is the first result showing. Should I specify it in the map script? Can I utilize println to show that?
public class Part2 {
public static void main(String[] args) {
try (Scanner csvData = new Scanner(
new File("C:\\Users\\amber\\Documents\\IN300_Dataset1.csv"))) {
List<String> list = new ArrayList<String>();
while (csvData.hasNext()) {
list.add(csvData.nextLine());
}
String[] tempArray = list.toArray(new String[1]);
String[][] csvArray = new String[tempArray.length][];
String combined_list[] = new String[tempArray.length];
String myData = null;
for(int i=0; i < tempArray.length; i++) {
if(i == 0) continue;
csvArray[i] = tempArray[i].split(",");
if(csvArray[i][4].matches("^\"[a-zA-Z].*\"")) {
continue;
}
else {
myData= csvArray[i][2] + " " +
csvArray[i][3] + " " +
csvArray[i][4] + " " +
csvArray[i][5] + " " +
csvArray[i][6];
combined_list[i] = myData;
}
}
getOccurences("Suspicious Result(s)", combined_list);
}
catch(Exception e) {
System.out.println(e);
}
}
private static void getOccurences(String message, String[] myArray) {
Map<String, Integer> map = new HashMap<>();
for (String key : myArray) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
Map<String, Integer> sortedMap =
map.entrySet().stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
printMap(message, sortedMap);
}
private static void printMap(String message, Map<String, Integer> map)
{
System.out.println();
System.out.println();
System.out.println("Printing" + message);
System.out.println();
map.forEach((key, value) -> {
if(key != null && value > 100) {
System.out.println(key + "appeared " + value + " times(s).");
}
});
}
}
Here is a sample of my results (The bold text is the result that I only want to display):
PrintingSuspicious Result(s)
00:28:00:01:00:00 02:00:00:00:45:00 0x4006 44 Ethernet IIappeared 7536 times(s).
209.99.61.21 192.168.1.24 UDP 1359 17212 > 52797 Len=1309appeared 2990 times(s).
192.168.1.24 209.99.61.21 UDP 170 52797 > 17212 Len=128appeared 2905 times(s).
209.99.61.21 192.168.1.24 UDP 1351 17212 > 52797 Len=1309appeared 2851 times(s).
If you want to display only the first result, just quit the loop after displaying the first element (you'll have to use normal for loop instead of using forEach to be able to break):
private static void printMap(String message, Map<String, Integer> map)
{
System.out.println();
System.out.println();
System.out.println("Printing" + message);
System.out.println();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey() != null && entry.getValue() > 100) {
System.out.println(entry.getKey() + "appeared " + entry.getValue() + " times(s).");
break;
}
}
}

Regex to get particular values from a string data

While executing a particular shell command am getting following output as follows and keeping this in a string variable
dat /var/france.log
exit
bluetooth_mac=45h6kuu
franceIP=testMarmiton
build_type=BFD
france_mac=F4:0E:83:35:E8:D1
seloger_mac=F4:0E:83:35:E8:D0
tdVersion=1.2
td_number=45G67j
france_mac=fjdjjjgj
logo_mac=tiuyiiy
logout
Connection to testMarmiton closed.
Disconnected channel and session
From this i have too fetch particular details like below and put htese values in a Map. How i can perform this using java.
bluetooth_mac=45h6kuu
build_type=BFD
tdVersion=1.2
seloger_mac=F4:0E:83:35:E8:D0
france_mac=fjdjjjgj
Map<String, String> details =new HashMap<String,String>();
details.put(bluetooth_mac, 45h6kuu);
details.put(build_type, BFD)
etc
etc
Solution 1
If you are using Java 8 you can use :
String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, String> result = stream
.filter(line -> line.matches("\\w+=\\w+"))
.map(line -> line.split("="))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
} catch (IOException e) {
e.printStackTrace();
}
Outputs
{franceIP=testMarmiton, bluetooth_mac=45h6kuu, logo_mac=tiuyiiy, td_number=45G67j, france_mac=fjdjjjgj, build_type=BFD}
Solution 2
It seems that you have multiple line which have the same name, in this case I would like to group by a Map<String, List<String>> :
String fileName = "shell.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, List<String>> result = stream
.filter(line -> line.matches("[^=]+=[^=]+")) // filter only the lines which contain one = signe
.map(line -> line.split("=")) // split with = sign
.collect(Collectors.groupingBy(e -> e[0], Collectors.mapping(e -> e[1], Collectors.toList())));
result.forEach((k, v) -> System.out.println(k + " : " + v));
} catch (IOException e) {
e.printStackTrace();
}
Outputs
franceIP : [testMarmiton]
bluetooth_mac : [45h6kuu]
logo_mac : [tiuyiiy]
td_number : [45G67j]
seloger_mac : [F4:0E:83:35:E8:D0]
france_mac : [F4:0E:83:35:E8:D1, fjdjjjgj]
tdVersion : [1.2]
build_type : [BFD]
public static void main(String[] args) {
String str="abc def \n"
+ "key=123 \n "
+ "pass=456 \n"
+ "not working";
String[] sarray=str.split("\\r?\\n");
for (String eachline : sarray) {
System.out.println("line " + " : " + eachline);
if(eachline.contains("="))
{
String[] sarray2=eachline.split("=");
System.out.println("key:" +sarray2[0] +":Value:"+ sarray2[1]);
}
}
System.out.println(""+sarray.length);
}
Use split("\r?\n") for new line splitting.
You could try:
Pattern re = Pattern.compile("^\\s*(.*)\\s*=(.*)$", Pattern.MULTILINE);
Matcher matcher = re.matcher(input);
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
Here's a complete example, extracting the value using regex-matching and building a HashMap (the appropriate map for key-value pairs). You can copy the whole program and run it yourself:
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class main {
public static void main(String[] args) {
String input = // Your input log
"dat /var/france.log\n" +
"\n" +
"exit\n" +
"\n" +
"root#france24:~# \n" +
"root#france24:~# dat /var/france.log\n" +
"bluetooth_mac=45h6kuu\n" +
"franceIP=testMarmiton\n" +
"build_type=BFD\n" +
"france_mac=F4:0E:83:35:E8:D1\n" +
"seloger_mac=F4:0E:83:35:E8:D0\n" +
"tdVersion=1.2\n" +
"td_number=45G67j\n" +
"france_mac=fjdjjjgj\n" +
"logo_mac=tiuyiiy\n" +
"root#france24:~# \n" +
"root#france24:~# exit\n" +
"logout\n" +
"Connection to testMarmiton closed.\n" +
"\n" +
"Disconnected channel and session";
String[] keys = {
"bluetooth_mac",
"build_type",
"tdVersion",
"seloger_mac",
"france_mac"
};
HashMap<String, String> map = new HashMap<>();
for(String key : keys){
String value = getValueOf(input, key);
if(value != null)
map.put(key, value);
}
for(String key : keys)
System.out.println(key + " = " + map.get(key));
}
public static String getValueOf(String input, String key){ //returns null if not found
String result = null;
Pattern pattern = Pattern.compile(key + "=.*+\\s");
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
result = matcher.group();
result = result.substring(result.indexOf('=') + 1, result.length() - 1);
}
return result;
}
}
Output (add more keys to the key-string if you want get more values):
bluetooth_mac = 45h6kuu
build_type = BFD
tdVersion = 1.2
seloger_mac = F4:0E:83:35:E8:D0
france_mac = F4:0E:83:35:E8:D1

NoSuchElementException error

I am trying to see if the next token in a string is equivalent to map key, and adding a message to an array list.
ArrayList<String> trace = new ArrayList<String>();
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
for(String key: expression.keySet())
if(st.nextToken() == key)
trace.add(key + "Changed from " + expression.get(key) + " to " + tokens.get(2));
expression.put(tokens.get(0),Integer.parseInt(tokens.get(2)));
tokens.clear();
}
ERROR MESSAGE
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Commander.main(Commander.java:45)
The problem is with st.nextToken() call.
You are checking st.hasMoreTokens() only once but calling st.nextToken() twice. And it is throwing the error.
During 1st while loop you are reading all the tokens:
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
Since 'all' the tokens are already read, now when you try to read the token again inside the for loop you will get the error.
if(st.nextToken() == key) {
trace.add(key + "Changed from " + expression.get(key) + " to " + tokens.get(2));
}
There is also another potential problem. You are trying to convert the 3rd token to an Integer. It might fail there as well:
// Value of tokens.get(2) is "string"
Integer.parseInt(tokens.get(2))
You will get error here also. It would be good to check if tokens.get(2) is of numeric type or not. like:
int value = 0;
if (StringUtils.isNumeric(tokens.get(2))) {
value = Integer.parseInt(tokens.get(2));
}
// Default value will be 0.
expression.put(tokens.get(0), value);
Reference: StringUtils.isNumeric()
So, the modified code will be like:
ArrayList<String> trace = new ArrayList<String>();
if(!element.startsWith("PRINT")) {
List<String> tokens = new ArrayList<String>();
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
// Size of tokens has to be more then 3, otherwise you will get another error.
if (tokens.size() >= 3) {
for(String key: expression.keySet()) {
if(tokens.get(0).equals(key)) {
// Do your other operations...
trace.add(key + "Changed from " + expression.get(key) + " to " + tokens.get(2));
}
}
// Do some more operations ...
int value = 0;
if (StringUtils.isNumeric(tokens.get(2))) {
value = Integer.parseInt(tokens.get(2));
}
// Default value will be 0.
expression.put(tokens.get(0), value);
}
tokens.clear();
}

write key and values from map to a file

With the code below, I am trying to write the key and values of the male and female map to an existing file.
But it shows the following error.
Can somebody help me please.
ERROR# Map.Entry entry = (Map.Entry) entryIter.next();
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at test.main(test.java:83)
Code
public static void main(String[] args) {
Map<String, List<String>> MaleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> FemaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(".txt"));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("Male") && (column.length == 4)) {
MaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("Female") && (column.length == 4)) {
FemaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = MaleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object maleName = key;
Object maleAge = null;
Object maleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object maleName = key;
Object maleAge = value1;
Object maleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write(maleAge + "." + maleID + "##;" + "\n"
+ " :class :" + maleName);// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Set<Entry<String, List<String>>> Fentries = FemaleMap.entrySet();
Iterator<Entry<String, List<String>>> FentryIter = Fentries.iterator();
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object Fkey = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = null;
Object femaleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(Fkey + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = value1;
Object femaleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write("map:" + femaleName + " a :Bridge;" + "\n"
+ ":property" + femaleAge + ";" + "\n"
+ ":column" + " " + femaleID + " " + ";");// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Map.Entry entry = (Map.Entry) entryIter.next(); in your second loop is breaking.
After the first while loop that iterates through the males, your iterator has reached the end of the set, and will break when you try to call next().
What you actually want to do is iterate through your females.
Change the line to iterate with your FentryIter:
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) FentryIter.next();
This is most likely the result of copy-paste code, and you need to be careful when doing this. I would recommend re-factoring your code since so much of it is duplicated.

Displaying the contents of a Map over iterator

I am trying to display the map i have created using the Iterator.
The code I am using is:
private void displayMap(Map<String, MyGroup> dg) {
Iterator it = dg.entrySet().iterator(); //line 1
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove();
}
}
Class MyGroup and it has two fields in it, named id and name.
I want to display these two values against the pair.getValue().
The problem here is Line 1 never gets executed nor it throws any exception.
Please Help.
PS: I have tried every method on this link.
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
for (Map.Entry<String, MyGroup> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
using iterator
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
Iterator<Map.Entry<String, MyGroup>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, MyGroup> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For more iteration information see this link

Categories

Resources