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(""))
{
}
}
}
Related
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.
I want extract sublists of an array list based on specific pattern as mentioned below. Please advise.
ArrayList<String> Filelist=new ArrayList<String>();
Filelist.add("abc.123");
Filelist.add("abc.456");
Filelist.add("def.123");
Filelist.add("def.456");
Here I need whatever starts with the first index, say abc to be stored in separate sublist and whatever starts with def need to be stored in separate sublist. The array list will have multiple entries like these, so it has to create separate sublists accordingly.
Map<String, List<String>> filesByPrefix = Filelist.stream()
.collect(Collectors.groupingBy(s -> s.split("\\.")[0]));
or the classic java 7 way.
Map<String, List<String>> map = new HashMap<>();
for (String str : lst) {
String[] splt = str.split("\\.");
if (!map.containsKey(splt[0])) {
map.put(splt[0], new ArrayList<>());
}
map.get(splt[0]).add(str);
}
give it a try :
package main_package;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Stackkkk {
static ArrayList<ArrayList<String>> pattern_lists=new ArrayList<ArrayList<String>>();
public static void main(String[] args) {
ArrayList<String> Filelist=new ArrayList<String>();
Filelist.add("abc.123");
Filelist.add("abc.456");
Filelist.add("def.123");
Filelist.add("def.456");
Filelist.add("def.456");
Filelist.add("def.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
for(int i=0;i<Filelist.size();i++)
add_to_list(Filelist.get(i));
System.out.println("number of pattern found are :"+pattern_lists.size());
for(int i=0;i<pattern_lists.size();i++)
System.out.println("number of value in pattern "+i+" :"+pattern_lists.get(i).size());
}
public static void add_to_list(String value){
boolean pattern_found=false;
for(int i=0;i<pattern_lists.size();i++){
if(pattern_lists.get(i).get(0).startsWith(value.substring(0, 3))){
//pattern found add it to this list
pattern_lists.get(i).add(value);
pattern_found=true;
}
}
if(!pattern_found){
//create new list and add the value
ArrayList<String> new_list=new ArrayList<String>();
new_list.add(value);
pattern_lists.add(new_list);
}
}
}
I am trying to remove the duplicated strings in an ArrayList called outputList in Hadoop.
Here is my code:
List<String> newList = new ArrayList<String>();
for( String item : outputList){
if(!newList.contains(item))
newList.add(item);
else newList.add("wrong");
}
The problems is that the strings in newList are all "wrong".
Some facts:
1. The above code works well at local machine.
I can write out the strings in outputList in hadoop. Most strings in outputList are different (duplicates exist).
I tried some other method to remove duplicated items. Like using HashSet. But when I use outputList to initialize a HashSet, the obtained HashSet is empty.
The java version in Hadoop is javac 1.6.0_18
Thanks.
The following is my reducer code:
public static class EditReducer
extends Reducer<Text,Text,Text,Text> {
private Text editor2 = new Text();
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
//write the content of iterable to an array list.
List<String> editorList =new ArrayList<String>();
for (Text t:values) {
editorList.add(t.toString());
}
//if a user appears more than once in the list, add to outputList
int occ;
List<String> outputList =new ArrayList<String>();
for (int i=0;i<editorList.size();i++) {
occ= Collections.frequency(editorList, editorList.get(i));
if(occ>1) {
outputList.add(editorList.get(i));
}
}
//make outputList distinct
List<String> newList = new ArrayList<String>();
for( String item : outputList){
if(!newList.contains(item))
newList.add(item);
else newList.add("wrong");
}
for (String val : newList) {
editor2.set(val);
context.write(editor2,editor2);
}
}
}
You can create a nested for loop inside your original for loop and compare the strings that way:
List<String> newList = new ArrayList<String>();
for(String item : outputList) {
boolean contains = false;
for(String str: newList) {
if(str.equals(item)) {
contains = true;
break;
}
}
if(!contains) {
newList.add(item);
}
else {
newList.add("wrong");
}
}
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
This is a drive method for two other classes. which i posted here
https://codereview.stackexchange.com/questions/33148/book-program-with-arraylist
I need some help for the
private static ArrayList getAuthors(String authors) method. I am kind a beginner. so please help me finish this drive method. or give me some directions.
Instruction
some of the elements of the allAuthors array contain asterisks “*” between two authors names. The getAuthors method uses this asterisk as a delimiter between names to store them separately in the returned ArrayList of Strings.
import java.util.ArrayList;
public class LibraryDrive {
public static void main(String[] args) {
String[] titles = { "The Hobbit", "Acer Dumpling", "A Christmas Carol",
"Marley and Me", "Building Java Programs",
"Java, How to Program" };
String[] allAuthors = { "Tolkien, J.R.", "Doofus, Robert",
"Dickens, Charles", "Remember, SomeoneIdont",
"Reges, Stuart*Stepp, Marty", "Deitel, Paul*Deitel, Harvery" };
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
for (int i = 0; i < titles.length; i++) {
authors = getAuthors(allAuthors[i]);
Book b = new Book(titles[i], authors);
books.add(b);
authors.remove(0);
}
Library lib = new Library(books);
System.out.println(lib);
lib.sort();
System.out.println(lib);
}
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
// need help here.
return books;
}
}
try this
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
String[] splitStr = authors.split("\\*");
for (int i=0;i<splitStr.length;i++) {
books.add(splitStr[i]);
}
return books;
}
What I would suggest is to use String.split like here (but keep in mind that this method uses a regex as parameter):
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
String[] strgArray = authors.split("\\*");
books.addAll(Arrays.asList(strgArray));
return books;
}
or
private static ArrayList<String> getAuthors(String authors) {
String[] strgArray = authors.split("\\*");
ArrayList books = Arrays.asList(strgArray);
return books;
}
Try this one but actually i do not understant why you remove zero indexed element of ArrayList in for loop.
private static ArrayList<String> getAuthors(String authors) {
ArrayList<String> array = new ArrayList<String>();
String[] authorsArray = authors.split("\\*");
for(String names : authorsArray );
array.add(names);
return array;
}
Take a look at String#split method, this will help you to separate authors by asterisk. This method returns an array so you will need to check how many authors are in this array and then store each of them into the ArrayList.
Here's how you can go about doing it.
Split the authors string you're getting as the method param based on the asterisk symbol. (Using String.split(delim) method)
The resultant string[] array needs to be iterated over using a for loop and each iterated element should be added to your list. (Using List.add(elem) method)
Once done, return that list(you are already doin that).
Now that you know how to do it, you need to implement the code by yourself.