Can i have shorten this program - java

I do not prefer giving arraylist values dynamically when running. But I need loops for ArrayList and hashTable, to shorten program.
public class HashTable2
{
public static void main(String[] args)
{
Hashtable<Integer, ArrayList<String>> hasTable1 = new Hashtable<Integer, ArrayList<String>>();
ArrayList<String> arrList1 = new ArrayList<String>();
ArrayList<String> arrList2 = new ArrayList<String>();
ArrayList<String> arrList3 = new ArrayList<String>();
ArrayList<String> arrList4 = new ArrayList<String>();
ArrayList<String> arrList5 = new ArrayList<String>();
ArrayList<String> arrList6 = new ArrayList<String>();
arrList1.add("MasoodAzar, 10000, Finance");
arrList2.add("Abu Bakr, 20000, Logistics");
arrList3.add("MuhammedRasul, 5000, Sales");
arrList4.add("SubhanQuershi, 2500, Sales");
arrList5.add("Hafiz Saeed, 25000, Purchase");
arrList6.add("Shekau, 14500, Purchase");
hasTable1.put(251, arrList1);
hasTable1.put(355, arrList2);
hasTable1.put(754, arrList3);
hasTable1.put(384, arrList4);
hasTable1.put(463, arrList5);
hasTable1.put(835, arrList6);
System.out.println(hasTable1);
}
}

You can write a function to abstract away the repetitive code:
void addEmployee(Hashtable hashTable, int id, String employeeDetails) {
ArrayList<String> employees = new ArrayList<>();
employees.add(employeeDetails);
hashTable.put(id, employees);
}
You should use HashMap rather than Hashtable -- Hashtable is synchronised, which isn't necessary here.
You should probably also represent the employees with a class, with fields fo reach of their attributes.

Related

Unique set from ArrayList of ArrayList

Hi I have an arraylist of arraylist in this format:
[[val1, val2],[val3,val4],[val1,val2],[val1,val5]]
and would like to get the unique set of arraylists:
[[val1, val2],[val3,val4],[val1,val5]]
I have tried the following:
Set<String> uniques = new HashSet<>();
for (ArrayList<String> sublist : mappedEntities) {
uniques.addAll(sublist);
}
but this merges all the values of the internal arraylist together
can use Java 8 Collection Stream Distinct,
return in Set datatype :
Set<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toSet());
if you want return in List :
List<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toList());
Why not simply put them in a Set like this?
Set<List<String>> uniques = new HashSet<>(mappedEntities);
Your mistake is that you are flattening the inner lists and putting their items in the set separately.
The issue here is that you need a Set of ArrayList Set<ArrayList<String>>, but you are using a Set of Strings Set<String> instead.
Given the list :
List<List<String>> mappedEntities = Arrays.asList(Arrays.asList("val1", "val2"),
Arrays.asList("val3", "val4"),
Arrays.asList("val1", "val2"),
Arrays.asList("val1", "val5"));
All you need to do is just declare the set and use the addAll().
Set<List<String>> mySet = new HashSet<>();
mySet.addAll(mappedEntities);
Since a set can hold only unique values, all duplicates will not be added to the set (No need to explicitly check this). You can now print it out :
mySet.forEach(System.out::println);
Or more simply, initialize the HashSet using the list mappedEntities :
Set<List<String>> mySet = new HashSet<>(mappedEntities);
I am beginner on STACKOVERFLOW but i to try solve your problem
I think you want like this..
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int n = 3;
// Here aList is an ArrayList of ArrayLists
ArrayList<ArrayList<String> > aList =
new ArrayList<ArrayList<String> >(n);
// Create n lists one by one and append to the
// master list (ArrayList of ArrayList)
ArrayList<String> a1 = new ArrayList<String>();
a1.add("1");
a1.add("2");
aList.add(a1);
ArrayList<String> a2 = new ArrayList<String>();
a2.add("11");
a2.add("22");
aList.add(a2);
ArrayList<String> a3 = new ArrayList<String>();
a3.add("1");
a3.add("2");
aList.add(a3);
Set<ArrayList<String>> uniques = new HashSet<ArrayList<String>>();
for (ArrayList<String> sublist : aList) {
uniques.add(sublist);
}
System.out.println("Your Answer");
for (ArrayList<String> x : uniques)
System.out.println(x);
}
}
try this code:
public class B {
public static void main(String[] args) throws Exception {
List<List<String>> list= Arrays.asList(
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c","d"));
Set<List<String>> uniques = new HashSet<>();
for (List<String> sublist : list) {
if(!uniques.contains(sublist))
uniques.add(sublist);
}
System.out.println(uniques);
}
}
output:
[[a, b, c], [a, b, c, d]]

forming new small lists from a combination set of two lists

I have two patterns of lists inside a big list.
[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]
To put in simple words, it is a combination of
[ [pricesList1], [DurationList1], [PricesList2], [DurationList2],... ]
I now want to create a new list with the price and corresponding duration from both lists as a pair from each set. For Example :
[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]
I have tried using List<List<Object>> and List<List<String>>. But no use. How can I do this?
I programed as following, which is wrong :
List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList = new ArrayList<List<String>>();
SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
}
}
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
}
}
Assuming the input list always has an even number of sublists and pairs of sublists have the same size, you can use a for loop iterating over the outer lists's element two by two :
List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
List<String> priceList = outerList.get(i);
List<String> durationsList = outerList.get(i+1);
for (int j=0; j<priceList.size(); j++) {
List<String> newEntry = new ArrayList<>();
newEntry.add(priceList.get(j));
newEntry.add(durationsList.get(j));
result.add(newEntry);
}
}
As commented I suggest defining your own class to store the price and duration rather than using that List<String> newEntry.

Iterating through multiple predefined ArrayLists using a method

I have defined a few ArrayLists that are already populated. I have the names of all of the ones I want to iterate through in an array 'tagArrays'. Is it possible to iterate through each of them in a similar logic to mine. I know this code is not going to work however I'm not sure how the code is supposed to look. This is my attempt:
These are already populated and are defined in main method.
ArrayList<String> KEYWORDS = new ArrayList<String>();
ArrayList<String> CUSTOMERS = new ArrayList<String>();
ArrayList<String> SYSTEM_DEPS = new ArrayList<String>();
ArrayList<String> MODULES = new ArrayList<String>();
ArrayList<String> DRIVE_DEFS = new ArrayList<String>();
ArrayList<String> PROCESS_IDS = new ArrayList<String>();
This is the logic I'm using
public void genericForEachLoop(POITextExtractor te) {
final String[] tagArrays = {"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"};
ArrayList<String> al = new ArrayList<String>();
for(int i=0; i<tagArrays.length; i++) {
System.out.println(tagArrays[i]);
al = tagArrays[i];
for (String item : al) {
if (te.getText().contains(item)) {
System.out.println(item);
}
}
}
}
I want the for each loop to be different every time e.g. once go through KEYWORDS, then go through CUSTOMERS etc.
You cannot reference variables with string values in Java.
What you try to do could be performed with reflection.
But I don't encourage it : it is less readable, more brittle/error prone and slower as the "classical" way.
As alternative you can provide a varargs of List<String> as last parameter of the method:
public void genericForEachLoop(POITextExtractor te, String[] tagArrays, List<String>... lists ) {
int i = 0;
for(List<String> list : lists) {
System.out.println(tagArrays[i]);
for (String item : list) {
if (te.getText().contains(item)) {
System.out.println(item);
}
}
i++;
}
}
And invoke it in this way :
genericForEachLoop(te,
new String[]{"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"},
KEYWORDS, CUSTOMERS,SYSTEM_DEPS,MODULES,DRIVE_DEFS,PROCESS_IDS);
I have tried following things with respect to Java 8. Below is the working example of your code, I have modified some of the code. Please check.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainClass {
public static void main(String... args) {
String[] strings = {"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"};
ArrayList<String> KEYWORDS = new ArrayList<String>();
KEYWORDS.add("goto");
ArrayList<String> CUSTOMERS = new ArrayList<String>();
CUSTOMERS.add("Royal Lotus");
ArrayList<String> SYSTEM_DEPS = new ArrayList<String>();
SYSTEM_DEPS.add("MAC BOOK");
ArrayList<String> MODULES = new ArrayList<String>();
MODULES.add("TETS MODULE");
ArrayList<String> DRIVE_DEFS = new ArrayList<String>();
DRIVE_DEFS.add("TEST DRIVE");
ArrayList<String> PROCESS_IDS = new ArrayList<String>();
PROCESS_IDS.add("-15153213");
Map<String, List<String>> mapOfLists = new HashMap<>();
mapOfLists.put("KEYWORDS", KEYWORDS);
mapOfLists.put("CUSTOMERS", CUSTOMERS);
mapOfLists.put("SYSTEM_DEPS", SYSTEM_DEPS);
mapOfLists.put("DRIVE_DEFS", DRIVE_DEFS);
mapOfLists.put("PROCESS_IDS", PROCESS_IDS);
mapOfLists.put("MODULES", MODULES);
genericForEachLoop(mapOfLists, strings);
}
public static void genericForEachLoop(Map<String, List<String>> mapOfLists, String[] listsToIterate) {
Arrays.stream(listsToIterate).forEach((listName -> mapOfLists.get(listName).stream().forEach(str -> System.out.println(str))));
}
}
I have taken out the String[] and providing it as an input to method so I can change it. Only those arrays where I want to iterate I can pass them. Further more building on top of #Eran's answer I am using the Map<String, List<String> for storing all the available ArrayLists.
Please modify the code as per your need. I have tried to use the streams and foreach methods from Java8.
Rather creating String array you can create Array of ArrayList, which will help you to iterate dynamically like below.
public static void main(String[] args)
{
ArrayList<String> KEYWORDS = new ArrayList<String>();
ArrayList<String> CUSTOMERS = new ArrayList<String>();
ArrayList<String> SYSTEM_DEPS = new ArrayList<String>();
ArrayList<String> MODULES = new ArrayList<String>();
ArrayList<String> DRIVE_DEFS = new ArrayList<String>();
ArrayList<String> PROCESS_IDS = new ArrayList<String>();
final String[] tagNames = {"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"};
final List<String> tagNameList=Arrays.asList(tagNames);
final ArrayList[] tagList = { KEYWORDS, CUSTOMERS, SYSTEM_DEPS, MODULES, DRIVE_DEFS, PROCESS_IDS };
for (ArrayList<String> list : tagList) {
for(String str :list){
if(str.contains(""))
{
}
}
}

How to remove duplicate list from hashmap which is added as values

Below is the program which has hashmap and adding list as keys. However duplicate list are being added. Now i want to remove all the duplicate list inside residing as values.
import java.util.*;
public class Test {
public static void main(String args[]) {
Map<String, List<Integer>> sample = new HashMap<String, List<Integer>>();
List first = new ArrayList();
first.add(1);
first.add(2);
first.add(3);
List second = new ArrayList();
second.add(4);
second.add(5);
second.add(6);
List third = new ArrayList();
third.add(1);
third.add(2);
third.add(3);
sample.put("first", first);
sample.put("second", second);
sample.put("third", third);
System.out.print(sample.size()); // Prints 3
// Need to Remove the duplicate lists
// Expects two keys with list first and second since third is duplicate value
// 1,23 and 4,5,6 instead of 1,2,3 4,5,6 and 1,2,3
}
}
May be this piece of code will work for you -
public static void main(String[] args) {
Map<String, List<Integer>> sample = new HashMap<String, List<Integer>>();
List first = new ArrayList();
first.add(1);
first.add(2);
first.add(3);
List second = new ArrayList();
second.add(4);
second.add(5);
second.add(6);
List third = new ArrayList();
third.add(1);
third.add(2);
third.add(3);
sample.put("first", first);
sample.put("second", second);
sample.put("third", third);
removeDuplicates(sample);
System.out.print(sample.size()); // now it will print 2
}
private static void removeDuplicates(Map<String, List<Integer>> sample) {
Collection<List<Integer>> list = sample.values();
for(Iterator<List<Integer>> itr = list.iterator(); itr.hasNext();) {
if(Collections.frequency(list, itr.next())>1) {
itr.remove();
}
}
}
This remove duplicate method will remove the duplicate values from the List.

Get items from Arraylist in Arraylist

I made this Code:
Class class{
public void main(String args[]){
ArrayList<ArrayList>list = new ArrayList<>();
ArrayList<String> Stringlist1 = new ArrayList<>();
ArrayList<String> Stringlist2 = new ArrayList<>();
Stringlist1.add("A");
Stringlist1.add("C");
Stringlist1.add("B");
Stringlist2.add("tr");
Stringlist2.add("rgd");
Stringlist2.add("sg");
}}
and i want to get the items from the inner list like:
for(ArrayList<String> ArrList: list){
ArrList.get(0)
}
pleas tell me how to do this!
ArrayList<ArrayList<String>> list = new ArrayList<>();
ArrayList<String> stringlist1 = new ArrayList<>();
ArrayList<String> stringlist2 = new ArrayList<>();
list.add(stringlist1);
list.add(stringlist2);
stringlist1.add("A");
stringlist1.add("C");
stringlist1.add("B");
stringlist2.add("tr");
stringlist2.add("rgd");
stringlist2.add("sg");
for(ArrayList<String> arrList: list){
for (String str : arrList) {
// do something
}
}
You can try something like this:
ArrayList<ArrayList<String>>list = new ArrayList<>();
//add items to StringLists
list.add(Stringlist1);
list.add(Stringlist2);
//Now access elements in your for loop
ArrayList<ArrayList<String>> list = new ArrayList<>();
ArrayList<String> stringlist1 = new ArrayList<>();
ArrayList<String> stringlist2 = new ArrayList<>();
stringlist1.add("A");
stringlist1.add("B");
stringlist1.add("C");
stringlist2.add("tr");
stringlist2.add("rgb");
stringlist2.add("sg");
list.add(stringlist1);
list.add(stringlist2);
//loop
System.out.println(list.get(0).get(0));
A nested for loop or for each loop is required.
You first need to add the sub lists to your parent list or you are not going to have access to the sub lists. Other than that, your code is mostly correct, except for not looping through each sub list.
The below code does exactly what you need so just copy it into your main function and it will work.
// create top level list
ArrayList<ArrayList<String>> list = new ArrayList<>();
// create sub lists
ArrayList<String> stringlist1 = new ArrayList<>();
ArrayList<String> stringlist2 = new ArrayList<>();
// add both sub lists to the parent list
list.add(stringlist1);
list.add(stringlist2);
// add elements to both lists
stringlist1.add("A");
stringlist1.add("C");
stringlist1.add("B");
stringlist2.add("tr");
stringlist2.add("rgd");
stringlist2.add("sg");
// loop through the top level list (will loop twice since the 2 elements are the sub lists)
for(ArrayList<String> array: list) {
System.out.println(array);
// loop through each element of each sub list
for (String str : array)
System.out.println(str);
}
Output:
[A, C, B]
A
C
B
[tr, rgd, sg]
tr
rgd
sg

Categories

Resources