Question

In: Computer Science

import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list =...

import java.util.*;
class Main
{
static ArrayList<String> list;
public static List<String> createList(ArrayList<String> arrayList)
{
list = arrayList;
return list;
}

public static void printList(ArrayList<String> arrayList)
{
System.out.println("Printing in 4 ways\n");
// 1
System.out.println(arrayList);

//2
for(String s:arrayList)
System.out.print(s+" ");
System.out.println();

//3
System.out.println(Arrays.deepToString(list.toArray()));

//4
for(int i=0;i<arrayList.size();i++)
System.out.print(arrayList.get(i)+" ");
System.out.println();
}

public static void filterList(ArrayList<String> arrayList)
{
System.out.println("Filtered in 2 ways\n");
ArrayList<String> copyArrayList = arrayList;
//1
for(int i=0;i<arrayList.size();i++)
{
if(arrayList.get(i).contains("chuck")) {
arrayList.remove(i);
i--;
}
}
System.out.println(arrayList);
//2
copyArrayList.removeIf(str -> str.contains("chunk"));
System.out.println(copyArrayList);
}

  
public static void main(String[] args) {
//Task -1
String[] array={"The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog", "how", "much", "wood", "would", "a", "woodchuck", "chuck", "if", "a", "woodchuck", "could", "chuck", "wood"};
ArrayList<String > list = new ArrayList<String>(Arrays.asList(array));
createList(list);
printList(list);
filterList(list);
}
}

This is the first Part of the Code: The rest underneath has yet to be answered.

List Performance – 25 Points

  • Generate a loop of each type (ArrayList, LinkedList)

  • For each list, iterate 100,000 times using random access to grab a random value from the list

    • You don’t need to do anything with the value

    • (hint – use math.random())

    • Time your loops and print the results

      • (hint – consider using java.time.Instant for your timing)

Map Creation – 25 Points

  • Create a method with the following signature

    • public static Map<String, String> createMap(MapType type)

    • (hint MapType should be an enum with the values HashMap and LinkedHashMap)

    • createMap should return a map with the following values

      • [ [“Hello”, “World”], [“Goodbye”, “World”], [“Pink”, “Brown”], [“Ford”, “Toyota”], [“Nittany Lions”, “Stanford”]]

Map Iteration – 25 Points

  • Create two maps, one with the HashMap flag one with the LinkedHashMap tag

  • Iterate over each list printing out the Key/Value Pairs

  • Note the different loop ordering

Expert Answer

Solutions

Expert Solution

SOURCE CODE:

*Please follow the comments to better understand the code.

**Please look at the Screenshot below and use this code to copy-paste.

***The code in the below screenshot is neatly indented for better understanding.

import java.util.*;


class Main
{
static ArrayList<String> list;
static HashMap<String,String> map;
public static List<String> createList(ArrayList<String> arrayList)
{
list = arrayList;
return list;
}

public static void printList(ArrayList<String> arrayList)
{
System.out.println("Printing in 4 ways\n");
// 1
System.out.println(arrayList);

//2
for(String s:arrayList)
System.out.print(s+" ");
System.out.println();

//3
System.out.println(Arrays.deepToString(list.toArray()));

//4
for(int i=0;i<arrayList.size();i++)
System.out.print(arrayList.get(i)+" ");
System.out.println();
}

public static void filterList(ArrayList<String> arrayList)
{
System.out.println("Filtered in 2 ways\n");
ArrayList<String> copyArrayList = arrayList;
//1
for(int i=0;i<arrayList.size();i++)
{
if(arrayList.get(i).contains("chuck")) {
arrayList.remove(i);
i--;
}
}
System.out.println(arrayList);
//2
copyArrayList.removeIf(str -> str.contains("chunk"));
System.out.println(copyArrayList);
}

public static void iterateArrayList(ArrayList<String> arrayList)
{
long startTime = System.nanoTime();
  
Random random = new Random();
for(int i=0;i<100000;i++)
{
//Create a random index
int index = random.nextInt(arrayList.size());
//Access the element in the list
arrayList.get(index);
}
  
long endTime = System.nanoTime();
long totalTime = (endTime - startTime)/1000000;
System.out.println("Array List Takes "+totalTime+" Milli Seconds");
}
  
public static void iterateLinkedList(LinkedList<String> linkedList)
{
long startTime = System.nanoTime();
  
Random random = new Random();
for(int i=0;i<100000;i++)
{
//Create a random index
int index = random.nextInt(linkedList.size());
//Access the element in the list
linkedList.get(index);
}
long endTime = System.nanoTime();
long totalTime = (endTime - startTime)/1000000;
System.out.println("Linked List Takes "+totalTime+" Milli Seconds");
}
  
//TASK - 4
public static Map<String, String> createMap(HashMap<String, String> hashMap)
{
map = hashMap;
return map;
}
  
static void iterateHashMap(HashMap<String, String> hashMap)
{
System.out.println("Hash MAP Iterate");
for (Map.Entry<String,String> entry : hashMap.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
  
static void iterateLinkedHashMap(LinkedHashMap<String, String> linkedHashMap)
{
System.out.println("Linked Hash MAP Iterate");
for (Map.Entry<String,String> entry : linkedHashMap.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
  
  
  
public static void main(String[] args) {
//Task -1
String[] array={"The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog", "how", "much", "wood", "would", "a", "woodchuck", "chuck", "if", "a", "woodchuck", "could", "chuck", "wood"};
ArrayList<String > list = new ArrayList<String>(Arrays.asList(array));
createList(list);
  
//TASK 2
printList(list);
filterList(list);
  
  
//Task 3
//TYPE - 1 ARRAY LIST
ArrayList<String > list1 = new ArrayList<String>(Arrays.asList(array));
iterateArrayList(list1);
  
//TYPE - 2 LINKED LIST
LinkedList<String > list2 = new LinkedList<String>(Arrays.asList(array));
iterateLinkedList(list2);
  
//TASK 4
HashMap<String, String> hash_map = new HashMap<String, String>();
hash_map.put("Hello","World");
hash_map.put("GoodBye", "World");
hash_map.put("Pink","Brown");
hash_map.put("Ford","Toyota");
hash_map.put("Nittany Lions","Stanford");
  
createMap(hash_map);
  
//TASK 5
iterateHashMap(hash_map);
  
LinkedHashMap<String, String> linked_hash_map = new LinkedHashMap<String, String>();
linked_hash_map.put("Hello","World");
linked_hash_map.put("GoodBye", "World");
linked_hash_map.put("Pink","Brown");
linked_hash_map.put("Ford","Toyota");
linked_hash_map.put("Nittany Lions","Stanford");
  
iterateLinkedHashMap(linked_hash_map);
  
  
  
}
  
}

SCREENSHOT FOR CODE:

OUTPUT:


Related Solutions

// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test...
// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test the smallest method System.out.print("smallest(1, 0, 2) -> "); System.out.println( smallest(1, 0, 2) ); // test the average method System.out.print("average(95, 85, 90) -> "); System.out.println( average(95, 84, 90) ); } // end main /* * smallest(double, double, double) -> double * * method is given 3 numbers, produces the smallest of the three * * examples: * smallest(1, 0, 2) -> 0.0 */ public static...
////Fixme(1) add a statement to import ArrayList class public class ListManipulation { public static void main(String[]...
////Fixme(1) add a statement to import ArrayList class public class ListManipulation { public static void main(String[] args) { //Fixme(2) create an ArrayList of integers and name the ArrayList list. //Fixme(3) add the following numbers to the list: 10, 15, 7, -5, 73, -11, 100, 20, 5, -1    displayList(list); System.out.println(); displayListBackwards(list);       }    public static void displayList(ArrayList<Integer> list) { for(Integer i: list) System.out.print(i + " ");    } //Fixme(4) define a method displayListBackwards, which takes an ArrayList as...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args)...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args) {             // TODO Auto-generated method stub             System.out.println("*** 1 ***");             ArrayList<Integer>list1=new ArrayList<Integer>();             for(int i=0;i<30;i++)             {                   list1.add(new Integer(i));             }             System.out.print("[");             for(int i=0;i<list1.size();i++)             {                   System.out.print(list1.get(i)+" ");             }             System.out.println("]");                           System.out.println("*** 2 ***");             ArrayList<Integer>list2=new ArrayList<Integer>();             for(int i=30;i<60;i++)             {                   list2.add(i); //Auto Boxing an Integer not need to use new Integer             }             System.out.println(list2); //toString for an ArrayList --created by the Java Programmers                           System.out.println("*** 3 ***");             ArrayList<Integer>list3=new ArrayList<Integer>();             list3.add(list1.remove(22)); //when...
import java.util.*;    public class DataAnalysis{    static Set<String> Data_NaN(Set<String> set){        Set<String> set2 =...
import java.util.*;    public class DataAnalysis{    static Set<String> Data_NaN(Set<String> set){        Set<String> set2 = new HashSet<String>();    for (String temp : set) {        temp = temp.replaceAll(        "[^0-9]", "");                  if(!(set.isEmpty())){            set2.add(temp);        }    }    return set2;               } public static void main(String args[]) { // create empty set Set<String> set = new HashSet<String>(); // {3, 25, 33, 21, 55, 43, 78,...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
------------------------------------------------------------------------------------ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input =...
------------------------------------------------------------------------------------ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int result = 0; System.out.print("Enter the first number: "); int x = input.nextInt(); System.out.print("Enter the second number: "); int y = input.nextInt(); System.out.println("operation type for + = 0"); System.out.println("operation type for - = 1"); System.out.println("operation type for * = 2"); System.out.print("Enter the operation type: "); int z = input.nextInt(); if(z==0){ result = x + y; System.out.println("The result is " + result); }else...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) {...
My code: import java.util.Random; import java.util.Scanner; public class RollDice { public static void main(String[] args) { int N; Scanner keybd = new Scanner(System.in); int[] counts = new int[12];    System.out.print("Enter the number of trials: "); N = keybd.nextInt();    Random die1 = new Random(); Random die2 = new Random(); int value1, value2, sum; for(int i = 1; i <= N; i++) { value1 = die1.nextInt(6) + 1; value2 = die2.nextInt(6) + 1; sum = value1 + value2; counts[sum-1]++; }   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT