├── ALPR ├── ALPR.java ├── License Plate Photos │ ├── ca2004.jpg │ ├── ca2005.jpg │ ├── ca2006.jpg │ ├── ca_10.jpeg │ ├── ca_12.jpeg │ ├── ca_aug2012.png │ ├── fl_1.jpeg │ ├── ny_1.jpeg │ └── tx_4.jpeg └── Training Data │ ├── letters-1 image.png │ ├── letters-2 image.png │ ├── letters-3 image.png │ └── numbers image.png ├── EscapeNestedLoops.java ├── Factorial.java ├── Image Filters └── ImageFilter.java ├── Java 8 Streams ├── JavaStreams.java ├── bands.txt └── data.txt ├── LICENSE ├── LinkedList.java ├── ListToArray.java ├── MapFunctions.java ├── MyIterator.java ├── Primes.java ├── QuickSort.java ├── README.md ├── SplitString.java ├── StringToInt.java ├── Temperature.java ├── Tree.java ├── bubbleSort.java ├── insertionSort.java ├── mergeSort.java ├── primes.txt └── selectionSort.java /ALPR/ALPR.java: -------------------------------------------------------------------------------- 1 | // Automatic License Plate Recognition (ALPR) 2 | // (c) 2023, Joe James 3 | 4 | /******************************************************************************* 5 | * This Automatic License Plate Reader program is mainly intended to 6 | * accompany my series of YouTube tutorial videos here, 7 | * https://www.youtube.com/user/joejamesusa and is mainly 8 | * intended for educational purposes. You are invited to subscribe to my 9 | * video channel, and to download and use any code in this Java 10 | * repository, according to the MIT License. Feel free to post any comments 11 | * on my YouTube channel. 12 | * 13 | * ****************************************************************************/ 14 | 15 | import java.util.*; 16 | import java.awt.*; 17 | import java.awt.image.*; 18 | import java.awt.geom.AffineTransform; 19 | import java.io.*; 20 | import javax.imageio.ImageIO; 21 | import javax.swing.*; 22 | import java.util.stream.*; 23 | import java.lang.Math; 24 | 25 | public class ALPR { 26 | // Penitentiary Gothic font, 20x43 pix = 860 pixels 27 | int[] CHARSIZE = {20, 43}; 28 | int NUMPIXELS = CHARSIZE[0] * CHARSIZE[1]; 29 | ArrayList trainLabels = new ArrayList<>(Arrays.asList("A","B","C","D","E","F","G","H","I","J","K","L","M", 30 | "N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9")); 31 | ArrayList trainData = new ArrayList<>(trainLabels.size()); 32 | 33 | public static void main(String[] args) { 34 | ALPR alpr = new ALPR(); 35 | File[] files = new File[4]; 36 | files[0] = new File("Training Data/letters-1 image.png"); 37 | files[1] = new File("Training Data/letters-2 image.png"); 38 | files[2] = new File("Training Data/letters-3 image.png"); 39 | files[3] = new File("Training Data/numbers image.png"); 40 | alpr.train(files); 41 | 42 | //File file = new File("License Plate Photos/ca_aug2012.png"); 43 | //File file = new File("License Plate Photos/ca_12.jpeg"); 44 | File file = new File("License Plate Photos/ca_10.jpeg"); 45 | //File file = new File("License Plate Photos/ca2004.jpg"); 46 | //File file = new File("License Plate Photos/ca2005.jpg"); 47 | //File file = new File("License Plate Photos/ca2006.jpg"); 48 | //File file = new File("License Plate Photos/ca_blue_1.jpeg"); 49 | //File file = new File("License Plate Photos/tx_4.jpeg"); 50 | //File file = new File("License Plate Photos/ny_1.jpeg"); 51 | //File file = new File("License Plate Photos/fl_1.jpeg"); 52 | alpr.readPlate(file); 53 | } 54 | 55 | public void readPlate(File file) { 56 | System.out.println("Loading file."); 57 | BufferedImage img = null; 58 | int height1 = 200; 59 | ArrayList testData = new ArrayList<>(); 60 | try { img = ImageIO.read(file); } 61 | catch (IOException e) { e.printStackTrace(System.out); } 62 | 63 | if (img != null) { 64 | display(img); 65 | img = toGrayScale(img); 66 | display(img); 67 | img = getScaledImage(img, height1); 68 | 69 | // Crop out top and bottom margins 70 | int[] vertBounds = getTopBottom(img); 71 | img = img.getSubimage(0, vertBounds[0], img.getWidth(), vertBounds[1]-vertBounds[0]); 72 | 73 | // Scale image to CHARSIZE height 74 | img = getScaledImage(img, CHARSIZE[1]); 75 | System.out.println(" Scaled image: " + img.getHeight() + "x" + img.getWidth()); 76 | display(img); 77 | 78 | // boost contrast 79 | img = boostContrast(img); 80 | 81 | ArrayList edges = getEdges(img); 82 | System.out.println(" Found edges: " + edges); 83 | /*display(img.getSubimage(edges.get(0)+2, 0, CHARSIZE[0], img.getHeight())); 84 | display(img.getSubimage(edges.get(1)+2, 0, CHARSIZE[0], img.getHeight())); 85 | display(img.getSubimage(edges.get(2)+2, 0, CHARSIZE[0], img.getHeight())); 86 | display(img.getSubimage(edges.get(3)+2, 0, CHARSIZE[0], img.getHeight())); 87 | display(img.getSubimage(edges.get(4)+2, 0, CHARSIZE[0], img.getHeight())); 88 | display(img.getSubimage(edges.get(5)+2, 0, CHARSIZE[0], img.getHeight())); 89 | display(img.getSubimage(edges.get(6)+2, 0, CHARSIZE[0], img.getHeight()));*/ 90 | 91 | // add character data to ArrayList for comparisons to trainData 92 | testData = imgToArray(img, testData, edges); 93 | 94 | // identify characters in testData 95 | String plateNum = identify(testData); 96 | System.out.println(plateNum); 97 | } 98 | } 99 | 100 | // receives an image of a plate, splits it into digits 101 | public void train(File[] files) { 102 | BufferedImage img = null; 103 | 104 | for (int i=0; i edges = getEdges(img); 136 | 137 | // add grayscale data for each character to training data set 138 | trainData = imgToArray(img, trainData, edges); 139 | 140 | //int[] intArray = Arrays.stream(trainData.get(trainData.size()-1)).mapToInt(Integer::intValue).toArray(); 141 | //display(intArray, CHARSIZE[0], CHARSIZE[1]); 142 | } 143 | } 144 | // add a few hard-coded chars to training data 145 | addMoreTrainingData(); 146 | 147 | System.out.println(trainData.size() + " characters loaded."); 148 | } 149 | 150 | // convert imageto grayscale 151 | public BufferedImage toGrayScale(BufferedImage img) { 152 | System.out.println(" Converting to GrayScale."); 153 | BufferedImage grayImage = new BufferedImage( 154 | img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); 155 | Graphics g = grayImage.getGraphics(); 156 | g.drawImage(img, 0, 0, null); 157 | g.dispose(); 158 | return grayImage; 159 | } 160 | 161 | // display image in a JPanel popup 162 | public void display (BufferedImage img) { 163 | //System.out.println(" Displaying image."); 164 | JFrame frame = new JFrame(); 165 | JLabel label = new JLabel(); 166 | frame = new JFrame(); 167 | frame.setSize(img.getWidth(), img.getHeight()); 168 | label.setIcon(new ImageIcon(img)); 169 | frame.getContentPane().add(label, BorderLayout.CENTER); 170 | frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 171 | frame.pack(); 172 | frame.setVisible(true); 173 | } 174 | 175 | // display image in a JPanel popup, from int array 176 | private void display(int[] pixels, int width, int height) { 177 | System.out.println(" Printing image for array length: " + pixels.length + ", " + width + "x" + height); 178 | BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); 179 | WritableRaster raster = img.getRaster(); 180 | raster.setPixels(0, 0, width, height, pixels); 181 | display(img); 182 | } 183 | 184 | // scale image 185 | private BufferedImage getScaledImage (BufferedImage img, int newHeight) { 186 | System.out.println(" Scaling image."); 187 | double scaleFactor = (double) newHeight/img.getHeight(); 188 | BufferedImage scaledImg = new BufferedImage( 189 | (int)(scaleFactor*img.getWidth()), newHeight, BufferedImage.TYPE_BYTE_GRAY); 190 | AffineTransform at = new AffineTransform(); 191 | at.scale(scaleFactor, scaleFactor); 192 | AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); 193 | return scaleOp.filter(img, scaledImg); 194 | } 195 | 196 | // convert grayscale image to BW 197 | private BufferedImage boostContrast(BufferedImage img) { 198 | // compute average pixel darkness 199 | int avg = 0; 200 | for (int y=0; yavg) 212 | p = (255<<24) | (255<<16) | (255<<8) | 255; 213 | else 214 | p = (255<<24) | (0<<16) | (0<<8) | 0; 215 | img.setRGB(x, y, p); 216 | } 217 | } 218 | return img; 219 | } 220 | 221 | private Integer[] boostContrast(Integer[] data) { 222 | // compute average pixel darkness 223 | int avg = 0; 224 | for (int i=0; iavg) 232 | data[i] = 255; 233 | else 234 | data[i] = 0; 235 | } 236 | //int[] bwChar = Arrays.stream(data).mapToInt(Integer::intValue).toArray(); 237 | //display(bwChar, CHARSIZE[0], CHARSIZE[1]); 238 | return data; 239 | } 240 | 241 | // use trainData to identify each character in testData 242 | private String identify(ArrayList testData) { 243 | System.out.println(" Identifying characters in plate."); 244 | String plateNum = ""; 245 | for (Integer[] testChar : testData) { 246 | int[] distances = new int[trainData.size()]; 247 | for (int t=0; t50; i--) { 328 | if (deltaGray[i] > 5) { 329 | vertBounds[0] = i-2; 330 | break; 331 | } 332 | } 333 | for (int i=120; i<180; i++) { 334 | if (deltaGray[i] < -5) { 335 | vertBounds[1] = i+2; 336 | break; 337 | } 338 | } 339 | System.out.println("Vert bounds: " + vertBounds[0] + " " + vertBounds[1]); 340 | return vertBounds; 341 | } 342 | 343 | // add grayscale data for each character to ArrayList 344 | private ArrayList imgToArray (BufferedImage img, ArrayList data, ArrayList edges) { 345 | for (Integer e : edges) { 346 | data.add(new Integer[NUMPIXELS]); 347 | for (int j=0; j getEdges(BufferedImage img) { 378 | System.out.println(" Getting edges between characters."); 379 | // Locate whitespace delimiters between characters (left & rt bounds for each character) 380 | int[] colSums = new int[img.getWidth()]; 381 | for (int y=0; y edges = new ArrayList<>(); 392 | int col = 0; 393 | while (col 250*CHARSIZE[1])) { 396 | whiteCols += 1; 397 | } 398 | if ((whiteCols > 1) & (col+whiteCols+CHARSIZE[0] < img.getWidth())) 399 | edges.add((int)(col + whiteCols -1)); 400 | col += whiteCols + 1; 401 | } 402 | //System.out.println(edges); 403 | 404 | return edges; 405 | } 406 | 407 | } 408 | 409 | -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ca2004.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ca2004.jpg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ca2005.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ca2005.jpg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ca2006.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ca2006.jpg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ca_10.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ca_10.jpeg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ca_12.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ca_12.jpeg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ca_aug2012.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ca_aug2012.png -------------------------------------------------------------------------------- /ALPR/License Plate Photos/fl_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/fl_1.jpeg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/ny_1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/ny_1.jpeg -------------------------------------------------------------------------------- /ALPR/License Plate Photos/tx_4.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/License Plate Photos/tx_4.jpeg -------------------------------------------------------------------------------- /ALPR/Training Data/letters-1 image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/Training Data/letters-1 image.png -------------------------------------------------------------------------------- /ALPR/Training Data/letters-2 image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/Training Data/letters-2 image.png -------------------------------------------------------------------------------- /ALPR/Training Data/letters-3 image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/Training Data/letters-3 image.png -------------------------------------------------------------------------------- /ALPR/Training Data/numbers image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowMan128/Java/bb51d07f22fb9689b71bcc81313dd67774407511/ALPR/Training Data/numbers image.png -------------------------------------------------------------------------------- /EscapeNestedLoops.java: -------------------------------------------------------------------------------- 1 | // Java - How to Break out of Nested For Loops 2 | 3 | class EscapeNestedLoops { 4 | public static void main(String[] args) { 5 | 6 | for(int x=0; x<8; x++) { 7 | for(int y=1; y<4; y++) { 8 | System.out.println(x + " " + y + " " + x*y); 9 | if(x * y > 5) 10 | break; 11 | } 12 | } 13 | 14 | System.out.println(" "); 15 | 16 | xLoop: 17 | for(int x=0; x<8; x++) { 18 | for(int y=1; y<4; y++) { 19 | System.out.println(x + " " + y + " " + x*y); 20 | if(x * y > 5) 21 | break xLoop; 22 | } 23 | } 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial { 2 | public static void main(String[] args) { 3 | Factorial factorial = new Factorial(); 4 | System.out.println(factorial.getRecursiveFactorial(6)); 5 | System.out.println(factorial.getIterativeFactorial(6)); 6 | } 7 | 8 | public int getRecursiveFactorial(int n) { 9 | if (n < 0) return -1; 10 | else if (n < 2) return 1; 11 | else return (n * getRecursiveFactorial(n-1)); 12 | } 13 | 14 | public int getIterativeFactorial(int n) { 15 | if (n < 0) return -1; 16 | int fact = 1; 17 | for (int i = 1; i <= n; i++) 18 | fact *= i; 19 | return fact; 20 | } 21 | } -------------------------------------------------------------------------------- /Image Filters/ImageFilter.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Filter Algorithms for Java BufferedImage 3 | * (c) 2023, Joe James 4 | * 5 | * This program loads an image file. It has methods to: 6 | * - display the image in a JPanel popup window; 7 | * - convert the image to grayscale; 8 | * - scale a grayscale image to a different size; 9 | * - pixelate a grayscale image; 10 | * - apply a Gaussian blur to a grayscale image; 11 | * - detect edges of a grayscale image; 12 | * - brighten a color image. 13 | * 14 | * These files are mainly intended to accompany my series of YouTube tutorial 15 | * videos here, https://www.youtube.com/user/joejamesusa and are mainly 16 | * intended for educational purposes. You are invited to subscribe to my 17 | * video channel, and to download and use any code in this Java 18 | * repository, according to the MIT License. Feel free to post any comments 19 | * on my YouTube channel. 20 | * 21 | * ****************************************************************************/ 22 | 23 | import java.util.*; 24 | import java.awt.*; 25 | import java.awt.image.*; 26 | import java.io.*; 27 | import javax.imageio.ImageIO; 28 | import javax.swing.*; 29 | import java.awt.geom.AffineTransform; 30 | 31 | public class ImageFilter { 32 | 33 | public static void main(String[] args) { 34 | File file = new File("photo.png"); 35 | //File file = new File("License Plate Photos/ca_10.jpeg"); 36 | BufferedImage img = null; 37 | 38 | try { img = ImageIO.read(file); } 39 | catch (IOException e) { e.printStackTrace(System.out); } 40 | 41 | if (img != null) { 42 | display(img); 43 | //img = brighten(img); 44 | img = toGrayScale(img); 45 | //img = toGrayScale2(img); 46 | //display(img); 47 | //img = pixelate(img); 48 | //img = pixelate2(img, 3); 49 | //img = resize(img, 150); 50 | //img = blur(img); 51 | img = blur(blur(img)); 52 | img = heavyblur(img); 53 | img = detectEdges(img); 54 | display(img); 55 | } 56 | } 57 | 58 | // display image in a JPanel popup 59 | public static void display (BufferedImage img) { 60 | System.out.println(" Displaying image."); 61 | JFrame frame = new JFrame(); 62 | JLabel label = new JLabel(); 63 | frame.setSize(img.getWidth(), img.getHeight()); 64 | label.setIcon(new ImageIcon(img)); 65 | frame.getContentPane().add(label, BorderLayout.CENTER); 66 | frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 67 | frame.pack(); 68 | frame.setVisible(true); 69 | } 70 | 71 | // convert image to grayscale 72 | public static BufferedImage toGrayScale (BufferedImage img) { 73 | System.out.println(" Converting to GrayScale."); 74 | BufferedImage grayImage = new BufferedImage( 75 | img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); 76 | Graphics g = grayImage.getGraphics(); 77 | g.drawImage(img, 0, 0, null); 78 | g.dispose(); 79 | return grayImage; 80 | } 81 | 82 | public static BufferedImage toGrayScale2 (BufferedImage img) { 83 | System.out.println(" Converting to GrayScale2."); 84 | BufferedImage grayImage = new BufferedImage( 85 | img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); 86 | int rgb=0, r=0, g=0, b=0; 87 | for (int y=0; y> 16) & 0xFF); 91 | g = ((rgb >> 8) & 0xFF); 92 | b = (rgb & 0xFF); 93 | rgb = (int)((r+g+b)/3); 94 | //rgb = (int)(0.299 * r + 0.587 * g + 0.114 * b); 95 | rgb = (255<<24) | (rgb<<16) | (rgb<<8) | rgb; 96 | grayImage.setRGB(x,y,rgb); 97 | } 98 | } 99 | return grayImage; 100 | } 101 | 102 | // apply 2x2 pixelation to a grayscale image 103 | public static BufferedImage pixelate (BufferedImage img) { 104 | BufferedImage pixImg = new BufferedImage( 105 | img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY); 106 | int pix = 0, p=0; 107 | for (int y=0; y threshold) 239 | p = (255<<24) | (255<<16) | (255<<8) | 255; 240 | else 241 | p = (255<<24) | (0<<16) | (0<<8) | 0; 242 | edgeImg.setRGB(x,y,p); 243 | } 244 | } 245 | return edgeImg; 246 | } 247 | 248 | // brighten color image by a percentage 249 | public static BufferedImage brighten (BufferedImage img, int percentage) { 250 | int r=0, g=0, b=0, rgb=0, p=0; 251 | int amount = (int)(percentage * 255 / 100); // rgb scale is 0-255, so 255 is 100% 252 | BufferedImage newImage = new BufferedImage( 253 | img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB); 254 | for (int y=0; y> 16) & 0xFF) + amount; 258 | g = ((rgb >> 8) & 0xFF) + amount; 259 | b = (rgb & 0xFF) + amount; 260 | if (r>255) r=255; 261 | if (g>255) g=255; 262 | if (b>255) b=255; 263 | p = (255<<24) | (r<<16) | (g<<8) | b; 264 | newImage.setRGB(x,y,p); 265 | } 266 | } 267 | return newImage; 268 | } 269 | 270 | } 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | -------------------------------------------------------------------------------- /Java 8 Streams/JavaStreams.java: -------------------------------------------------------------------------------- 1 | import java.lang.String; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | import java.util.stream.*; 5 | import java.util.*; 6 | import java.nio.file.*; 7 | import java.io.IOException; 8 | 9 | public class JavaStreams { 10 | public static void main(String[] args) throws IOException { 11 | // 1. Integer Stream 12 | IntStream 13 | .range(1, 10) 14 | .forEach(System.out::print); 15 | System.out.println(); 16 | 17 | // 2. Integer Stream with skip 18 | IntStream 19 | .range(1, 10) 20 | .skip(5) 21 | .forEach(x -> System.out.println(x)); 22 | System.out.println(); 23 | 24 | // 3. Integer Stream with sum 25 | System.out.println( 26 | IntStream 27 | .range(1, 5) 28 | .sum()); 29 | System.out.println(); 30 | 31 | // 4. Stream.of, sorted and findFirst 32 | Stream.of("Ava", "Aneri", "Alberto") 33 | .sorted() 34 | .findFirst() 35 | .ifPresent(System.out::println); 36 | 37 | // 5. Stream from Array, sort, filter and print 38 | String[] names = {"Al", "Ankit", "Kushal", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah"}; 39 | Arrays.stream(names) // same as Stream.of(names) 40 | .filter(x -> x.startsWith("S")) 41 | .sorted() 42 | .forEach(System.out::println); 43 | 44 | // 6. average of squares of an int array 45 | Arrays.stream(new int[] {2, 4, 6, 8, 10}) 46 | .map(x -> x * x) 47 | .average() 48 | .ifPresent(System.out::println); 49 | 50 | // 7. Stream from List, filter and print 51 | List people = Arrays.asList("Al", "Ankit", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah"); 52 | people 53 | .stream() 54 | .map(String::toLowerCase) 55 | .filter(x -> x.startsWith("a")) 56 | .forEach(System.out::println); 57 | 58 | // 8. Stream rows from text file, sort, filter, and print 59 | Stream bands = Files.lines(Paths.get("bands.txt")); 60 | bands 61 | .sorted() 62 | .filter(x -> x.length() > 13) 63 | .forEach(System.out::println); 64 | bands.close(); 65 | 66 | // 9. Stream rows from text file and save to List 67 | List bands2 = Files.lines(Paths.get("bands.txt")) 68 | .filter(x -> x.contains("jit")) 69 | .collect(Collectors.toList()); 70 | bands2.forEach(x -> System.out.println(x)); 71 | 72 | // 10. Stream rows from CSV file and count 73 | Stream rows1 = Files.lines(Paths.get("data.txt")); 74 | int rowCount = (int)rows1 75 | .map(x -> x.split(",")) 76 | .filter(x -> x.length == 3) 77 | .count(); 78 | System.out.println(rowCount + " rows."); 79 | rows1.close(); 80 | 81 | // 11. Stream rows from CSV file, parse data from rows 82 | Stream rows2 = Files.lines(Paths.get("data.txt")); 83 | rows2 84 | .map(x -> x.split(",")) 85 | .filter(x -> x.length == 3) 86 | .filter(x -> Integer.parseInt(x[1]) > 15) 87 | .forEach(x -> System.out.println(x[0] + " " + x[1] + " " + x[2])); 88 | rows2.close(); 89 | 90 | // 12. Stream rows from CSV file, store fields in HashMap 91 | Stream rows3 = Files.lines(Paths.get("data.txt")); 92 | Map map = new HashMap<>(); 93 | map = rows3 94 | .map(x -> x.split(",")) 95 | .filter(x -> x.length == 3) 96 | .filter(x -> Integer.parseInt(x[1]) > 15) 97 | .collect(Collectors.toMap( 98 | x -> x[0], 99 | x -> Integer.parseInt(x[1]))); 100 | rows3.close(); 101 | for (String key : map.keySet()) { 102 | System.out.println(key + " " + map.get(key)); 103 | } 104 | 105 | // 13. Reduction - sum 106 | double total = Stream.of(7.3, 1.5, 4.8) 107 | .reduce(0.0, (Double a, Double b) -> a + b); 108 | System.out.println("Total = " + total); 109 | 110 | // 14. Reduction - summary statistics 111 | IntSummaryStatistics summary = IntStream.of(7, 2, 19, 88, 73, 4, 10) 112 | .summaryStatistics(); 113 | System.out.println(summary); 114 | } 115 | } -------------------------------------------------------------------------------- /Java 8 Streams/bands.txt: -------------------------------------------------------------------------------- 1 | Rolling Stones 2 | Lady Gaga 3 | Jackson Browne 4 | Maroon 5 5 | Arijit Singh 6 | Elton John 7 | John Mayer 8 | CCR 9 | Eagles 10 | Pink 11 | Aerosmith 12 | Adele 13 | Taylor Swift 14 | Faye Wong 15 | Bob Seger 16 | ColdPlay 17 | Boston 18 | The Cars 19 | Cheap Trick 20 | Def Leppard 21 | Ed Sheeran 22 | Dire Straits 23 | Train 24 | Tom Petty 25 | Jack Johnson 26 | Jimmy Buffett 27 | Mumford and Sons 28 | Phil Collins 29 | Rod Stewart 30 | The Script 31 | Elvis 32 | Michael Buble -------------------------------------------------------------------------------- /Java 8 Streams/data.txt: -------------------------------------------------------------------------------- 1 | A,12,3.7 2 | B,17,2.8 3 | C,14,1.9 4 | D,23,2.7 5 | E 6 | F,18,3.4 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Joe James 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LinkedList.java: -------------------------------------------------------------------------------- 1 | // Linked List in Java. Written by Joe James. 2 | public class LinkedList { 3 | Node root; 4 | int size; 5 | 6 | public LinkedList() { 7 | root = new Node(); 8 | size = 0; 9 | } 10 | 11 | // Test code - main function 12 | public static void main(String[] args) { 13 | LinkedList ll = new LinkedList(); 14 | System.out.println(ll.getSize()); 15 | ll.add(8); 16 | System.out.println(ll.getSize()); 17 | ll.add(17); 18 | ll.add(5); 19 | ll.add(10); 20 | System.out.println(ll.find(17).getData()); 21 | ll.remove(5); 22 | System.out.println(ll.getSize()); 23 | System.out.println(ll.find(5)); 24 | } 25 | 26 | public void setSize(int s) { 27 | this.size = s; 28 | } 29 | 30 | public int getSize() { 31 | return this.size; 32 | } 33 | 34 | public Node add(int data) { 35 | Node newNode = new Node(data, root); 36 | this.root = newNode; 37 | this.size++; 38 | return newNode; 39 | } 40 | 41 | public Node find(int data) { 42 | Node thisNode = this.root; 43 | 44 | while (thisNode != null) { 45 | if (thisNode.getData() == data) 46 | return thisNode; 47 | thisNode = thisNode.getNextNode(); 48 | } 49 | return null; 50 | } 51 | 52 | public boolean remove(int data) { 53 | Node thisNode = this.root; 54 | Node prevNode = null; 55 | 56 | while (thisNode != null) { 57 | if (thisNode.getData() == data) { 58 | if (prevNode != null) 59 | prevNode.setNextNode(thisNode.getNextNode()); 60 | else 61 | this.root = null; 62 | this.setSize(this.getSize()-1); 63 | return true; 64 | } 65 | prevNode = thisNode; 66 | thisNode = thisNode.getNextNode(); 67 | } 68 | return false; 69 | } 70 | 71 | // Node class 72 | private class Node { 73 | private Node nextNode; 74 | private int data; 75 | 76 | // 0-arg constructor, 1-arg constructor, 2-arg constructor 77 | private Node() { } 78 | 79 | private Node(int val) { 80 | data = val; 81 | } 82 | 83 | private Node(int val, Node next) { 84 | data = val; 85 | nextNode = next; 86 | } 87 | 88 | private void setData(int val) { 89 | this.data = val; 90 | } 91 | 92 | private int getData() { 93 | return this.data; 94 | } 95 | 96 | private void setNextNode(Node n) { 97 | this.nextNode = n; 98 | } 99 | 100 | private Node getNextNode() { 101 | return this.nextNode; 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /ListToArray.java: -------------------------------------------------------------------------------- 1 | // Java: convert ArrayList to String[] 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.*; 6 | 7 | class ListToArray { 8 | public static void main(String[] args) { 9 | // create Array 10 | String[] array = {"Bugatti", "Ferarri", "Lamborghini", "Rolls Royce"}; 11 | 12 | // 3 ways to print Array 13 | System.out.println(Arrays.toString(array)); 14 | 15 | for(String s : array) { 16 | System.out.print(s + ", "); 17 | } 18 | System.out.println(); 19 | 20 | Stream.of(array) 21 | .forEach(System.out::println); 22 | 23 | // 2 ways to convert Array to ArrayList 24 | List arrayList = new ArrayList<>(Arrays.asList(array)); 25 | System.out.println("arrayList: " + arrayList); 26 | 27 | List arrayList2 = new ArrayList<>(List.of(array)); 28 | System.out.println("arrayList2: " + arrayList2); 29 | 30 | // convert ArrayList to Array 31 | String[] array2 = arrayList.toArray(new String[0]); 32 | 33 | // print Array 34 | Stream.of(array2) 35 | .forEach(System.out::println); 36 | 37 | } 38 | } 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /MapFunctions.java: -------------------------------------------------------------------------------- 1 | // Java HashMap 2 | // Joe James 2023 3 | 4 | import java.util.Map; 5 | import java.util.HashMap; 6 | import java.util.Map.Entry; 7 | import java.util.stream.*; 8 | 9 | class MapFunctions { 10 | public static void main (String[] args) { 11 | // 1. Create a HashMap, add kv pairs 12 | Map ages = new HashMap(); 13 | // OR, to initialize capaacity, 14 | // Map ages = new HashMap(100); 15 | ages.put("Avni",11); 16 | ages.put("Bing", 12); 17 | ages.put("Cassie", 13); 18 | ages.put("Devarshi", 14); 19 | System.out.println(ages); 20 | 21 | // 2. Get an item from the map 22 | String person = "Cassie"; 23 | System.out.println(person + " : " + ages.get(person)); 24 | System.out.println("Frank" + " : " + ages.getOrDefault("Frank", 0)); 25 | 26 | // 3. Check for membership 27 | System.out.println("Contains key Avni?: " + ages.containsKey("Avni")); 28 | System.out.println("Contains value 23?: " + ages.containsValue(23)); 29 | 30 | // 4. Remove an item from the map 31 | ages.remove("Bing"); 32 | System.out.println(ages); 33 | ages.remove("Devarshi", 41); 34 | System.out.println(ages); 35 | 36 | // 5. Get count of items in map 37 | System.out.println("Num Items = " + ages.size()); 38 | 39 | // 6. Remove all items from map 40 | ages.clear(); 41 | System.out.println("Empty map? " + ages.isEmpty()); 42 | ages.put("Elena", 15); 43 | ages.put("Frank", 16); 44 | System.out.println(ages); 45 | 46 | // 7. Conditional add & replace 47 | ages.putIfAbsent("George", 23); 48 | ages.putIfAbsent("Elena", 5); 49 | System.out.println(ages); 50 | ages.replace("George", 23, 17); 51 | ages.replace("George", 44, 55); 52 | System.out.println(ages); 53 | 54 | // 8. Get collection of Values 55 | System.out.println(ages.values()); 56 | 57 | // 9. Iterate keys using enhanced for loop 58 | for (String key : ages.keySet()) { 59 | System.out.println(key + " : " + ages.get(key)); 60 | } 61 | 62 | // 10. Iterate KV pairs using enhanced for loop 63 | for (Map.Entry pair : ages.entrySet()) { 64 | System.out.println(pair.getKey() + " : " + pair.getValue()); 65 | } 66 | 67 | // 11. Iterate KV pairs using Java 8 Stream API 68 | ages.entrySet().stream().forEach(pair -> System.out.println(pair.getKey() + " : " + pair.getValue())); 69 | 70 | } 71 | } -------------------------------------------------------------------------------- /MyIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | import java.util.ListIterator; 4 | 5 | public class MyIterator { 6 | 7 | public static void main(String[] args) { 8 | ArrayList cars = new ArrayList<>(); 9 | cars.add("Chevy"); 10 | cars.add("Ford"); 11 | cars.add("Honda"); 12 | cars.add("Mercedes"); 13 | cars.add("Toyota"); 14 | 15 | // for loop 16 | System.out.println("For Loop:"); 17 | for (int i = 0; i < cars.size(); i++) { 18 | System.out.print(cars.get(i) + " "); 19 | } 20 | 21 | // advanced for loop 22 | System.out.println("\n\nAdvanced For Loop:"); 23 | for (String car : cars) { 24 | System.out.print(car + " "); 25 | } 26 | 27 | // while loop 28 | System.out.println("\n\nWhile Loop:"); 29 | int i = 0; 30 | while (i < cars.size()) { 31 | System.out.print(cars.get(i++) + " "); 32 | } 33 | 34 | // Iterator (supports hasNext, next, remove) 35 | System.out.println("\n\nIterator:"); 36 | Iterator iterator = cars.iterator(); 37 | while (iterator.hasNext()) { 38 | System.out.print(iterator.next() + " "); 39 | } 40 | 41 | // ListIterator (supports hasNext, next, remove, hasPrevious, previous, add) 42 | System.out.println("\n\nListIterator:"); 43 | ListIterator li = cars.listIterator(); 44 | while (li.hasNext()) { 45 | System.out.print(li.next() + " "); 46 | } 47 | 48 | // Java 8 Stream 49 | System.out.println("\n\nJava 8 Stream:"); 50 | cars.forEach((car) -> { 51 | System.out.print(car + " "); 52 | }); 53 | } 54 | } 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Primes.java: -------------------------------------------------------------------------------- 1 | // version 1 2 | public class Primes { 3 | 4 | public static void main(String[] args) { 5 | int max = 10; 6 | for (int x = 2; x <= max; x++) { 7 | boolean isPrime = true; 8 | for (int y = 2; y < x; y++) 9 | if (x % y == 0) 10 | isPrime = false; 11 | if (isPrime) 12 | System.out.println(x); 13 | } 14 | } 15 | } 16 | //-------------------------------------------- 17 | // version 2: break 18 | public class Primes { 19 | 20 | public static void main(String[] args) { 21 | int max = 10; 22 | for (int x = 2; x <= max; x++) { 23 | boolean isPrime = true; 24 | for (int y = 2; y < x; y++) 25 | if (x % y == 0) { 26 | isPrime = false; 27 | break; 28 | } 29 | if (isPrime) 30 | System.out.println(x); 31 | } 32 | } 33 | } 34 | //-------------------------------------------- 35 | // version 3: break, add to list 36 | import java.util.ArrayList; 37 | 38 | public class Primes { 39 | 40 | public static void main(String[] args) { 41 | ArrayList primeList = new ArrayList<>(); 42 | 43 | int max = 10000; 44 | for (int x = 2; x <= max; x++) { 45 | boolean isPrime = true; 46 | for (int y = 2; y < x; y++) 47 | if (x % y == 0) { 48 | isPrime = false; 49 | break; 50 | } 51 | if (isPrime) 52 | primeList.add(x); 53 | } 54 | System.out.println(primeList); 55 | } 56 | } 57 | //-------------------------------------------- 58 | // version 4: break, add to list, square root 59 | import java.util.ArrayList; 60 | 61 | public class Primes { 62 | 63 | public static void main(String[] args) { 64 | ArrayList primeList = new ArrayList<>(); 65 | 66 | int max = 200000; 67 | for (int x = 2; x <= max; x++) { 68 | boolean isPrime = true; 69 | for (int y = 2; y < Math.sqrt(x); y++) 70 | if (x % y == 0) { 71 | isPrime = false; 72 | break; 73 | } 74 | if (isPrime) 75 | primeList.add(x); 76 | } 77 | System.out.println(primeList); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /QuickSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Random; 3 | 4 | public class QuickSort { 5 | public void quickSort(int[] A) { 6 | quickSort(A, 0, A.length-1); 7 | } 8 | 9 | private void quickSort(int[] A, int low, int high) { 10 | if (low < high+1) { 11 | int p = partition(A, low, high); 12 | quickSort(A, low, p-1); 13 | quickSort(A, p+1, high); 14 | } 15 | } 16 | 17 | private void swap(int[] A, int index1, int index2) { 18 | int temp = A[index1]; 19 | A[index1] = A[index2]; 20 | A[index2] = temp; 21 | } 22 | 23 | // returns random pivot index between low and high inclusive. 24 | private int getPivot(int low, int high) { 25 | Random rand = new Random(); 26 | return rand.nextInt((high - low) + 1) + low; 27 | } 28 | 29 | // moves all n < pivot to left of pivot and all n > pivot 30 | // to right of pivot, then returns pivot index. 31 | private int partition(int[] A, int low, int high) { 32 | swap(A, low, getPivot(low, high)); 33 | int border = low + 1; 34 | for (int i = border; i <= high; i++) { 35 | if (A[i] < A[low]) { 36 | swap(A, i, border++); 37 | } 38 | } 39 | swap(A, low, border-1); 40 | return border-1; 41 | } 42 | 43 | public static void main(String[] args) { 44 | QuickSort qs = new QuickSort(); 45 | int[] A = {9, 0, 1, 3, 4, 5, 2, 9, 8, 7, 6, 5, 9, 1, 0, 9}; 46 | System.out.println(Arrays.toString(A)); 47 | qs.quickSort(A); 48 | System.out.println(Arrays.toString(A)); 49 | } 50 | } 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java 2 | These files are mainly intended to accompany my series of YouTube tutorial videos here, 3 | https://www.youtube.com/user/joejamesusa 4 | and are mainly intended for educational purposes. 5 | You are invited to subscribe to my video channel, and to download and use any code in 6 | this Java repository, according to the MIT License. 7 | Feel free to post any comments on my YouTube channel. 8 | 9 | Joe James. 10 | Fremont, California 11 | Copyright (C) 2015-2018, Joe James 12 | -------------------------------------------------------------------------------- /SplitString.java: -------------------------------------------------------------------------------- 1 | // Java: Split a String at char 2 | import java.util.Arrays; 3 | 4 | class SplitString { 5 | 6 | public static void main(String[] args) { 7 | String s = "My dog ate my homework; Can I turn it in tomorrow?"; 8 | 9 | String[] ss = s.split(" "); 10 | System.out.println(Arrays.toString(ss)); 11 | 12 | ss = s.split(";"); 13 | System.out.println(Arrays.toString(ss)); 14 | 15 | // you must escape special chars because the split parameter is a regex 16 | // special chars include \ . + ^ $ | ? * ( ) [ { 17 | String t = "54.25-128.17"; 18 | String[] tt = t.split("\\."); 19 | System.out.println(Arrays.toString(tt)); 20 | 21 | // include multiple split chars inside brackets 22 | tt = t.split("[.-]"); 23 | System.out.println(Arrays.toString(tt)); 24 | 25 | } 26 | } 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /StringToInt.java: -------------------------------------------------------------------------------- 1 | // Java - Convert String to an Int 2 | 3 | class StringToInt { 4 | public static void main(String[] args) { 5 | String s = "222"; 6 | int i; 7 | Integer integer; 8 | 9 | // returns an int 10 | i = Integer.parseInt(s); 11 | System.out.println(i + 1); 12 | 13 | // returns an Integer 14 | integer = Integer.valueOf(s); 15 | System.out.println(integer + 2); 16 | 17 | // Best Practice: safely returns an Integer 18 | try { 19 | integer = Integer.valueOf(s); 20 | } catch (NumberFormatException e) { 21 | integer = 0; 22 | } 23 | System.out.println(integer + 3); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Temperature.java: -------------------------------------------------------------------------------- 1 | public class Temperature { 2 | public static void main(String[] args) { 3 | Temperature temperature = new Temperature(); 4 | 5 | double fTemp = 77.5; 6 | double cTemp = temperature.toCelsius(fTemp); 7 | System.out.printf("%.2f Fahrenheit = %.2f Celsius.\n", fTemp, cTemp); 8 | 9 | cTemp = 37.2; 10 | fTemp = temperature.toFahrenheit(cTemp); 11 | System.out.printf("%.2f Celsius = %.2f Fahrenheit.\n", cTemp, fTemp); 12 | } 13 | 14 | public double toCelsius(double f) { 15 | return (f - 32.0) / 1.8; 16 | } 17 | 18 | public double toFahrenheit(double c) { 19 | return (c * 1.8) + 32.0; 20 | } 21 | } -------------------------------------------------------------------------------- /Tree.java: -------------------------------------------------------------------------------- 1 | // Java Binary Search Tree 2 | 3 | public class Tree { 4 | Node root; 5 | 6 | // some basic test code 7 | public static void main(String[] args) { 8 | Tree tree = new Tree(); 9 | int[] items = {5, 8, 7, 1, 9, 3, 0, 4, 6, 2}; 10 | for (int i : items) 11 | tree.insert(i); 12 | 13 | System.out.println("Tree Height: " + tree.getHeight()); 14 | System.out.println("Tree Size: " + tree.getSize()); 15 | System.out.println("Find 3: " + tree.find(3)); 16 | tree.inorder(); 17 | } 18 | 19 | public boolean insert(int val) { 20 | if (root == null) { 21 | root = new Node(val); 22 | return true; 23 | } 24 | else 25 | return root.insert(val); 26 | } 27 | 28 | public boolean find(int val) { 29 | if (root == null) 30 | return false; 31 | else 32 | return root.find(val); 33 | } 34 | 35 | public int getHeight() { 36 | if (root != null) 37 | return root.getHeight(); 38 | else 39 | return 0; 40 | } 41 | 42 | public int getSize() { 43 | if (root != null) 44 | return root.getSize(); 45 | else 46 | return 0; 47 | } 48 | 49 | public void preorder() { 50 | if (root != null) { 51 | System.out.println("Preorder:"); 52 | root.preorder(); 53 | } 54 | } 55 | 56 | public void postorder() { 57 | if (root != null) { 58 | System.out.println("Postorder:"); 59 | root.postorder(); 60 | } 61 | } 62 | 63 | public void inorder() { 64 | if (root != null) { 65 | System.out.println("Inorder:"); 66 | root.inorder(); 67 | } 68 | } 69 | 70 | private class Node { 71 | private Node leftChild; 72 | private Node rightChild; 73 | private int data; 74 | 75 | private Node(int val) { 76 | data = val; 77 | leftChild = null; 78 | rightChild = null; 79 | } 80 | 81 | private boolean insert(int val) { 82 | boolean added = false; 83 | if (this == null) { 84 | this.data = val; 85 | return true; 86 | } 87 | else { 88 | if (val < this.data) { 89 | if (this.leftChild == null) { 90 | this.leftChild = new Node(val); 91 | return true; 92 | } 93 | else 94 | added = this.leftChild.insert(val); 95 | } 96 | else if (val > this.data) { 97 | if (this.rightChild == null) { 98 | this.rightChild = new Node(val); 99 | return true; 100 | } 101 | else 102 | added = this.rightChild.insert(val); 103 | } 104 | } 105 | return added; 106 | } 107 | 108 | private boolean find(int val) { 109 | boolean found = false; 110 | if (this == null) 111 | return false; 112 | else { 113 | if (val == this.data) 114 | return true; 115 | else if (val < this.data && this.leftChild != null) 116 | found = this.leftChild.find(val); 117 | else if (val > this.data && this.rightChild != null) 118 | found = this.rightChild.find(val); 119 | } 120 | return found; 121 | } 122 | 123 | private int getHeight() { 124 | int leftHeight = 0, rightHeight = 0; 125 | 126 | if (this.leftChild != null) 127 | leftHeight = this.leftChild.getHeight(); 128 | 129 | if (this.rightChild != null) 130 | rightHeight = this.rightChild.getHeight(); 131 | 132 | return 1 + Math.max(leftHeight, rightHeight); 133 | } 134 | 135 | private int getSize() { 136 | int leftSize = 0, rightSize = 0; 137 | 138 | if (this.leftChild != null) 139 | leftSize = this.leftChild.getSize(); 140 | 141 | if (this.rightChild != null) 142 | rightSize = this.rightChild.getSize(); 143 | 144 | return 1 + leftSize + rightSize; 145 | } 146 | 147 | private void preorder() { 148 | if (this != null) { 149 | System.out.println(this.data); 150 | if (this.leftChild != null) 151 | this.leftChild.preorder(); 152 | if (this.rightChild != null) 153 | this.rightChild.preorder(); 154 | } 155 | } 156 | 157 | private void postorder() { 158 | if (this != null) { 159 | if (this.leftChild != null) 160 | this.leftChild.postorder(); 161 | if (this.rightChild != null) 162 | this.rightChild.postorder(); 163 | System.out.println(this.data); 164 | } 165 | } 166 | 167 | private void inorder() { 168 | if (this != null) { 169 | if (this.leftChild != null) 170 | this.leftChild.inorder(); 171 | System.out.println(this.data); 172 | if (this.rightChild != null) 173 | this.rightChild.inorder(); 174 | } 175 | } 176 | } 177 | } -------------------------------------------------------------------------------- /bubbleSort.java: -------------------------------------------------------------------------------- 1 | public int[] bubbleSort (int[] list) { 2 | int i, j, temp = 0; 3 | for (i = 0; i < list.length - 1; i++) { 4 | for (j = 0; j < list.length - 1 - i; j++) { 5 | if (list[j] > list[j + 1]) { 6 | temp = list[j]; 7 | list[j] = list[j + 1]; 8 | list[j + 1] = temp; 9 | } 10 | } 11 | } 12 | return list; 13 | } 14 | -------------------------------------------------------------------------------- /insertionSort.java: -------------------------------------------------------------------------------- 1 | // using Array 2 | public int[] insertionSort (int[] list) { 3 | int i, j, key, temp; 4 | for (i = 1; i < list.length; i++) { 5 | key = list[i]; 6 | j = i - 1; 7 | while (j >= 0 && key < list[j]) { 8 | temp = list[j]; 9 | list[j] = list[j + 1]; 10 | list[j + 1] = temp; 11 | j--; 12 | } 13 | } 14 | return list; 15 | } 16 | 17 | // using ArrayList 18 | public ArrayList insertionSort (ArrayList list) { 19 | int i, j, key, temp; 20 | for (i = 1; i < list.size(); i++) { 21 | key = list.get(i); 22 | j = i - 1; 23 | while (j >= 0 && key < list.get(j)) { 24 | temp = list.get(j); 25 | list.set(j, list.get(j + 1)); 26 | list.set(j + 1, temp); 27 | j--; 28 | } 29 | } 30 | return list; 31 | } -------------------------------------------------------------------------------- /mergeSort.java: -------------------------------------------------------------------------------- 1 | public void mergeSort (int[] list, int lowIndex, int highIndex) { 2 | if (lowIndex == highIndex) 3 | return; 4 | else { 5 | int midIndex = (lowIndex + highIndex) / 2; 6 | mergeSort(list, lowIndex, midIndex); 7 | mergeSort(list, midIndex + 1, highIndex); 8 | merge(list, lowIndex, midIndex, highIndex); 9 | } 10 | } 11 | 12 | public void merge(int[] list, int lowIndex, int midIndex, int highIndex) { 13 | int[] L = new int[midIndex - lowIndex + 2]; 14 | 15 | for (int i = lowIndex; i <= midIndex; i++) { 16 | L[i - lowIndex] = list[i]; 17 | } 18 | L[midIndex - lowIndex + 1] = Integer.MAX_VALUE; 19 | int[] R = new int[highIndex - midIndex + 1]; 20 | 21 | for (int i = midIndex + 1; i <= highIndex; i++) { 22 | R[i - midIndex - 1] = list[i]; 23 | } 24 | R[highIndex - midIndex] = Integer.MAX_VALUE; 25 | int i = 0, j = 0; 26 | 27 | for (int k = lowIndex; k <= highIndex; k++) { 28 | if (L[i] <= R[j]) { 29 | list[k] = L[i]; 30 | i++; 31 | } 32 | else { 33 | list[k] = R[j]; 34 | j++; 35 | } 36 | } 37 | } 38 |  -------------------------------------------------------------------------------- /primes.txt: -------------------------------------------------------------------------------- 1 | // version 1 2 | public class Primes { 3 | 4 | public static void main(String[] args) { 5 | int max = 10; 6 | for (int x = 2; x <= max; x++) { 7 | boolean isPrime = true; 8 | for (int y = 2; y < x; y++) 9 | if (x % y == 0) 10 | isPrime = false; 11 | if (isPrime) 12 | System.out.println(x); 13 | } 14 | } 15 | } 16 | -------------------------------------------- 17 | // version 2: break 18 | public class Primes { 19 | 20 | public static void main(String[] args) { 21 | int max = 10; 22 | for (int x = 2; x <= max; x++) { 23 | boolean isPrime = true; 24 | for (int y = 2; y < x; y++) 25 | if (x % y == 0) { 26 | isPrime = false; 27 | break; 28 | } 29 | if (isPrime) 30 | System.out.println(x); 31 | } 32 | } 33 | } 34 | -------------------------------------------- 35 | // version 3: break, add to list 36 | import java.util.ArrayList; 37 | 38 | public class Primes { 39 | 40 | public static void main(String[] args) { 41 | ArrayList primeList = new ArrayList<>(); 42 | 43 | int max = 10000; 44 | for (int x = 2; x <= max; x++) { 45 | boolean isPrime = true; 46 | for (int y = 2; y < x; y++) 47 | if (x % y == 0) { 48 | isPrime = false; 49 | break; 50 | } 51 | if (isPrime) 52 | primeList.add(x); 53 | } 54 | System.out.println(primeList); 55 | } 56 | } 57 | -------------------------------------------- 58 | // version 4: break, add to list, square root 59 | import java.util.ArrayList; 60 | 61 | public class Primes { 62 | 63 | public static void main(String[] args) { 64 | ArrayList primeList = new ArrayList<>(); 65 | 66 | int max = 200000; 67 | for (int x = 2; x <= max; x++) { 68 | boolean isPrime = true; 69 | for (int y = 2; y < Math.sqrt(x); y++) 70 | if (x % y == 0) { 71 | isPrime = false; 72 | break; 73 | } 74 | if (isPrime) 75 | primeList.add(x); 76 | } 77 | System.out.println(primeList); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /selectionSort.java: -------------------------------------------------------------------------------- 1 | public int[] selectionSort (int[] list) { 2 | int i, j, minValue, minIndex, temp = 0; 3 | for (i = 0; i < list.length; i++) { 4 | minValue = list[i]; 5 | minIndex = i; 6 | for (j = i; j < list.length; j++) { 7 | if (list[j] < minValue) { 8 | minValue = list[j]; 9 | minIndex = j; 10 | } 11 | } 12 | if (minValue < list[i]) { 13 | temp = list[i]; 14 | list[i] = list[minIndex]; 15 | list[minIndex] = temp; 16 | } 17 | } 18 | return list; 19 | } 20 | --------------------------------------------------------------------------------