How to Iterate through HashMap containing Arraylist - hashmap

Can you send the implementation how to Iterate through HashMap containing ArrayList, here is my code, I created 2 ArrayLists and added to Hashmap and I need to iterate through
public class t {
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
b.add("d");
b.add("e");
b.add("r");
HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
hm.put("Tomek", a);
hm.put("KOT", b);
for (Entry<String, ArrayList<String> m : hm.entrySet()) {
// code to type....
}
}

You can use the below code to print all the elements in the lists :
hm.forEach((key, arr) -> {
arr.forEach( arrayListElement -> System.out.println(arrayListElement));
});
We are iterating through each element in map which provides us the array list element and then iterate through the list element to get the items in the list.

Related

Combine string arrays lists and pass to a new array list only if a string exists in all original lists

I have four ArrayLists and would like to combine them. New ArrayList should only contain strings that exist in all other array lists but only once. So far, I have the following code:
//Combine array lists and only keep duplicates
private ArrayList<String> getResultList(){
final ArrayList<String> filtered_list = new ArrayList<>();
Set<String> set = new HashSet<>(filtered_list);
filtered_list.addAll(getResultList1());
filtered_list.addAll(getResultList2());
filtered_list.addAll(getResultList3());
filtered_list.addAll(getResultList4());
ArrayList<String> duplicates = new ArrayList<String>();
for (String s : filtered_list) {
if (!set.add(s)) {
duplicates.add(s);
}
}
return duplicates;
}
The result I currently get, if for example I only have 1 identical string in all four arrays, is a list of three identical strings in a list. Would I need to create a loop with HashSet inside it? I haven't seen any examples of this yet. Any help would be appreciated. Thank you.
I was able to solve the problem with the following code:
//Combine array lists and only keep duplicates
private ArrayList<String> getResultList(){
final ArrayList<String> filtered_list1 = new ArrayList<>();
final ArrayList<String> filtered_list2 = new ArrayList<>();
final ArrayList<String> filtered_list = new ArrayList<>();
Set<String> set1 = new HashSet<>(filtered_list1);
Set<String> set2 = new HashSet<>(filtered_list2);
Set<String> set = new HashSet<>(filtered_list);
filtered_list1.addAll(getResultList1());
filtered_list1.addAll(getResultList2());
filtered_list2.addAll(getResultList3());
filtered_list2.addAll(getResultList4());
ArrayList<String> duplicates1 = new ArrayList<String>();
for (String s : filtered_list1) {
if (!set1.add(s)) {
duplicates1.add(s);
}
}
ArrayList<String> duplicates2 = new ArrayList<String>();
for (String s : filtered_list2) {
if (!set2.add(s)) {
duplicates2.add(s);
}
}
filtered_list.addAll(duplicates1);
filtered_list.addAll(duplicates2);
ArrayList<String> duplicates = new ArrayList<String>();
for (String s : filtered_list) {
if (!set.add(s)) {
duplicates.add(s);
}
}
return duplicates;
}
There is probably an easier way of doing this but I haven't found it.

How to duplicate main loop data within JETT?

I'm developing Excel report with hierarchy data.
Using JETT (java excel template translator) and I'd like to duplicate rows from the main loop when there are collection of collection. Here is a brief example.
public class JettTest {
#Test
public void run() throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
InputStream template = classLoader.getResourceAsStream("template.xlsx");
try (
XSSFWorkbook wb = new XSSFWorkbook(template);
FileOutputStream fos = new FileOutputStream("target/output.xlsx")
) {
Map<String, Object> params = new HashMap<>();
Parent parent1 = new Parent("parent1", Arrays.asList("child1", "child2"));
Parent parent2 = new Parent("parent2", Arrays.asList("childX", "childY"));
List<Parent> parents = Arrays.asList(parent1, parent2);
params.put("parents", parents);
ExcelTransformer transformer = new ExcelTransformer();
transformer.transform(wb, params);
wb.write(fos);
}
}
public class Parent {
private String name;
private List<String> children;
public Parent(String name, List<String> children) {
this.name = name;
this.children = children;
}
public String getName() {
return name;
}
public List<String> getChildren() {
return children;
}
}
}
Excel template is
A1 is
<jt:forEach items="${parents}" var="parent">${parent.name}
B1 is
<jt:forEach items="${parent.children}" var="child">${child}</jt:forEach></jt:forEach>
This gives me
It looks good, however, I need to duplicate parent names and get
Any ideas, please?
You'll need {parent.name} to be within the child forEach tag if you want the parent name to be displayed for each child name.
What happens if you move the child forEach tag from B1 to A1, right after the parent forEach tag?

i have a method to return a hashMap,

i called the method in the main method, but the problem is how to manuplate the values individually in the main method.
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, Integer> re = new HashMap<Integer, Integer>();
System.out.print(methodReturningTwoInts());
Set<Entry<Integer, Integer>> keySet = re.entrySet();
keySet.getClass();
for(Integer j=0; j <3;j++){
if(methodReturningTwoInts().containsKey(1)){
re.put((j+1), methodReturningTwoInts().getValues);
}
}
}
public static Map<Integer, Integer> methodReturningTwoInts()
{
Integer a = 3;
Integer b = 6;
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
result.put(1, a);
result.put(2, b);
return result;
}
}
getValues is not a valid method for maps. You can use methodReturningTwoInts().get(key) to get your corresponding value. In your case your key is (j + 1).
re.put((j+1), methodReturningTwoInts().get(j+1));

Binding hashmap with tableview (JavaFX)

I want to display HashMap contents in a JavaFX Tableview. Please find below the code I used to set the HashMap contents into the table columns. The problem I'm having is that it's displaying only one row. The for loop is iterating only 5 times: each time it is picking up the first value of the HashMap.
If I ignore the return SimpleObjectProperty line, the for loop is iterating over all the content in the HashMap.
final ObservableList<Map> data = FXCollections.observableArrayList();
data.addAll(HASHMAP);
TableColumn<Map.Entry, String> nCol = new TableColumn<Map.Entry, String>("Name");
nCol.setEditable(true);
nCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Entry, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Entry, String> p) {
Set <String> set=HASHMAP.keySet();
for (String key:HASHMAP.keySet())
{
String key1= key.toString();
return new SimpleObjectProperty<>(key.toString());
}
return null;
}
});
Table.setItems(data);
Table.getColumns().setAll(nCol,.........);
CellFactory.Callback.call() creates just one cell, not all cells in a loop
Using return from a loop breaks loop execution.
Take a look at next example, especially comments:
public class MapTableView extends Application {
#Override
public void start(Stage stage) {
// sample data
Map<String, String> map = new HashMap<>();
map.put("one", "One");
map.put("two", "Two");
map.put("three", "Three");
// use fully detailed type for Map.Entry<String, String>
TableColumn<Map.Entry<String, String>, String> column1 = new TableColumn<>("Key");
column1.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<String, String>, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p) {
// this callback returns property for just one cell, you can't use a loop here
// for first column we use key
return new SimpleStringProperty(p.getValue().getKey());
}
});
TableColumn<Map.Entry<String, String>, String> column2 = new TableColumn<>("Value");
column2.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<String, String>, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p) {
// for second column we use value
return new SimpleStringProperty(p.getValue().getValue());
}
});
ObservableList<Map.Entry<String, String>> items = FXCollections.observableArrayList(map.entrySet());
final TableView<Map.Entry<String,String>> table = new TableView<>(items);
table.getColumns().setAll(column1, column2);
Scene scene = new Scene(table, 400, 400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Sergey Grinev; I found a solution, a generic solution for this problem
public class TableCassaController<K,V> extends TableView<Map.Entry<K,V>> implements Initializable {
#FXML private TableColumn<K, V> column1;
#FXML private TableColumn<K, V> column2;
public TableCassaController(ObservableMap<K,V> map, String col1Name, String col2Name) {
System.out.println("Costruttore table");
TableColumn<Map.Entry<K, V>, K> column1 = new TableColumn<>(col1Name);
column1.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<K, V>, K>, ObservableValue<K>>() {
#Override
public ObservableValue<K> call(TableColumn.CellDataFeatures<Map.Entry<K, V>, K> p) {
// this callback returns property for just one cell, you can't use a loop here
// for first column we use key
return new SimpleObjectProperty<K>(p.getValue().getKey());
}
});
TableColumn<Map.Entry<K, V>, V> column2 = new TableColumn<>(col2Name);
column2.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<K, V>, V>, ObservableValue<V>>() {
#Override
public ObservableValue<V> call(TableColumn.CellDataFeatures<Map.Entry<K, V>, V> p) {
// for second column we use value
return new SimpleObjectProperty<V>(p.getValue().getValue());
}
});
ObservableList<Map.Entry<K, V>> items = FXCollections.observableArrayList(map.entrySet());
this.setItems(items);
this.getColumns().setAll(column1, column2);
}
Very Thanks!!! :-)

How to Add entity to Dictionary Object Initializer?

I need to pass html attributes.
It is possible to pack into one expression code some like this?
var tempDictionary = new Dictionary<string, object> {
{ "class", "ui-btn-test" },
{ "data-icon", "gear" }
}.Add("class", "selected");
or
new Dictionary<string, object> ().Add("class", "selected").Add("diabled", "diabled");
?
What you are referring to is known as method chaining. A good example of this is the StringBuilder's Append method.
StringBuilder b = new StringBuilder();
b.Append("test").Append("test");
This is possible because the Append method returns a StringBuilder object
public unsafe StringBuilder Append(string value)
But, in your case, the Add method of Dictionary<TKey, TValue> is marked void
public void Add(TKey key, TValue value)
Therefore, method chaining is not supported. However, if you really wanted to use method chaining when adding new items, you could always roll your own:
public static Dictionary<TKey, TValue> AddChain<TKey, TValue>(this Dictionary<TKey, TValue> d, TKey key, TValue value)
{
d.Add(key, value);
return d;
}
Then you could write the following code:
Dictionary<string, string> dict = new Dictionary<string, string>()
.AddChain("test1", "test1")
.AddChain("test2", "test2");

Resources