logo
down
shadow

Convert from String to a Java enum with large amount of values


Convert from String to a Java enum with large amount of values

By : user2952313
Date : November 19 2020, 12:41 AM
it should still fix some issue You want a Map, but how to populate it neatly? Enums don't allow you to initialize a static fields before the enum instances are initialized, but there's a neat little trick, called the Initialization-on-demand holder idiom, that makes using a statically initialized map needed for this functionality easy to implement:
code :
public enum Code {
    CODE_1("string1"),
    CODE_2("string2"),
    CODE_3("string3"),
    // etc
    ;

    private static class Holder {
        static Map<String, Code> CODE_MAP = new HashMap<>();
    }

    private final String code;

    private Code(String code) {
        this.code = code;
        Holder.CODE_MAP.put(code, this);
    }

    public String getCode() {
        return this.code;
    }

    public Code convertFromString(String code) {
        return CODE_MAP.get(code);
    }
}


Share : facebook icon twitter icon
Java - how to efficiently store a large amount of String arrays

Java - how to efficiently store a large amount of String arrays


By : Hassan Hafez
Date : March 29 2020, 07:55 AM
like below fixes the issue Maybe this article can be of some help :
http://www.javamex.com/tutorials/memory/string_saving_memory.shtml
Checking string for large amount of different, incremental values

Checking string for large amount of different, incremental values


By : Kay Hubbard
Date : March 29 2020, 07:55 AM
should help you out Currently I am checking a string for the following: , I think this regex should do it:
code :
String parseCommand = "vlan4094";
if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" +
                                 "[1-9][0-9]{0,2}|" +
                                 "40(9[0-4]|[0-8][0-9])).*"))
   System.out.println("matches");
String parseCommand = "vlan4094";
if (parseCommand.startsWith("vlan"))
{
   int v = Integer.parseInt(parseCommand.substring(4));
   if (v >= 1 && v <= 4094)
      /* do stuff */
}
parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1") 
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3") 
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5") 
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7") 
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
parseCommand.matches(".*?Fa1/[0-9].*")
Java incrementing every character in a string by a large amount?

Java incrementing every character in a string by a large amount?


By : Michelsup
Date : March 29 2020, 07:55 AM
it should still fix some issue First I'm going to remove all of the I/O (except for outputting the result), get rid of the decryption piece for brevity, and write encrypt(String) and encrypt(char) as pure functions.
code :
public class EncryptionMain {

    public static void main(String args[]){
        System.out.println(encrypt("Hello"));
    }

    static String encrypt(String plaintext) {
        StringBuilder ciphertext = new StringBuilder(plaintext);
        for (int i = 0; i < ciphertext.length(); i++) {
            ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
        }
        return ciphertext.toString();
    }

    static char encrypt(char c) {
        int switchInc = 1; // 0 = BACK 1 = FORWARD

        for(int e = 0; e < 1000; e++){
            if (c == '!') {
                switchInc = 1;
            } else if (c == '~') {
                switchInc = 0;
            }

            switch (switchInc) {
                case 0: c--; break;
                default: c++; break;
            }
        }
        return c;
    }
}
public class EncryptionMain {

    public static void main(String args[]){
        System.out.println(encrypt("Hello"));
    }

    static String encrypt(String plaintext) {
        StringBuilder ciphertext = new StringBuilder(plaintext);
        for (int i = 0; i < ciphertext.length(); i++) {
            ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
        }
        return ciphertext.toString();
    }

    static int switchInc = 1; // 0 = BACK 1 = FORWARD

    static char encrypt(char c) {

        for(int e = 0; e < 1000; e++){
            if (c == '!') {
                switchInc = 1;
            } else if (c == '~') {
                switchInc = 0;
            }

            switch (switchInc) {
                case 0: c--; break;
                default: c++; break;
            }
        }
        return c;
    }
}
package cipher;

public final class Cipher {

    public Cipher(Range range, int key) {
        this.range = range;
        this.key = key;
    }

    public final Range range;
    public final int key;

    public String encrypt(String plaintext) {
        return cipher(plaintext, key);
    }

    public String decrypt(String ciphertext) {
        return cipher(ciphertext, -key);
    }

    String cipher(String in, int n) {
        StringBuilder out = new StringBuilder(in.length());
        for (int i = 0; i < in.length(); i++) {
            out.append(range.shift(in.charAt(i), n));
        }
        return out.toString();
    }
}
package cipher;

public final class Range {

    public final char min;
    public final char max;
    public final int size;

    public static Range inclusive(char min, char max) {
        return new Range(min, max);
    }

    Range(char min, char max) {
        this.min = min;
        this.max = max;
        size = max - min + 1;
    }

    /** Shift c up by i places, wrapping around to the
     * beginning of the range when it reaches the end. */
    public char shift(char c, int i) {
        return (char) (min + mod(c - min + i, size));
    }

    /** x mod a */
    static int mod(int x, int a) {
        return ((x % a) + a) % a;
    }
}
package cipher;

import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

public class CipherTest {

    @Test
    public void testZeroKey() throws Exception {
        Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 0);
        assertEquals(cipher.encrypt("abcxyz"), "abcxyz");
        assertEquals(cipher.decrypt("abcxyz"), "abcxyz");
    }

    @Test
    public void testOneKey() throws Exception {
        Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 1);
        assertEquals(cipher.encrypt("abcxyz"), "bcdyza");
        assertEquals(cipher.decrypt("bcdyza"), "abcxyz");
    }

    @Test
    public void testSizePlusOneKey() throws Exception {
        Cipher cipher = new Cipher(Range.inclusive('a', 'z'), 27);
        assertEquals(cipher.encrypt("abcxyz"), "bcdyza");
        assertEquals(cipher.decrypt("bcdyza"), "abcxyz");
    }
}
package cipher;

import org.testng.Assert;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static cipher.Range.mod;

public class RangeTest {

    @Test
    public void testSize() {
        Assert.assertEquals(Range.inclusive('a', 'c').size, 3);
    }

    @Test
    public void testMod() throws Exception {
        assertEquals(mod(-2, 5), 3);
        assertEquals(mod(-1, 5), 4);
        assertEquals(mod(0, 5), 0);
        assertEquals(mod(1, 5), 1);
        assertEquals(mod(2, 5), 2);
        assertEquals(mod(3, 5), 3);
        assertEquals(mod(4, 5), 4);
        assertEquals(mod(5, 5), 0);
        assertEquals(mod(6, 5), 1);
    }

    @Test
    public void testShift() throws Exception {
        Range r = Range.inclusive('a', 'd');
        Assert.assertEquals(r.shift('a', -2), 'c');
        Assert.assertEquals(r.shift('a', -1), 'd');
        Assert.assertEquals(r.shift('a', 0), 'a');
        Assert.assertEquals(r.shift('a', 1), 'b');
        Assert.assertEquals(r.shift('a', 2), 'c');
        Assert.assertEquals(r.shift('a', 3), 'd');
        Assert.assertEquals(r.shift('a', 4), 'a');
        Assert.assertEquals(r.shift('a', 5), 'b');
    }
}
How can I learn a large amount of java concepts in a short amount of time?

How can I learn a large amount of java concepts in a short amount of time?


By : Bhagabat Behera
Date : March 29 2020, 07:55 AM
this will help I guess, you should check the official documentation and the tutorials provided there - as @ChrisK suggested (for completness, here is the link again).
Additionally, you could check those links:
Need a fast method to convert large amount of double to string

Need a fast method to convert large amount of double to string


By : John Dorean
Date : March 29 2020, 07:55 AM
Hope this helps I am writing a results output module for a high speed computing program. ,
fast method to convert large amount of double to string
Related Posts Related Posts :
  • Passing HttpServletResponse in Spring Boot controller method
  • Failed to load libraries: [netty_tcnative_linux_arm_32, netty_tcnative_linux_arm_32_fedora, netty_tcnative_arm_32, netty
  • How to build a small documents storage?
  • Getting pixel position of a text in an image
  • How do I get a list of Methods called from a Class in Eclipse IDE?
  • Convert string to day of week (not exact date)
  • Unable to understand how rounding is working for decimal digits (Java)
  • How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)
  • JTable Renderer not working with RowSorter?
  • From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?
  • jUnit tests work in Eclipse, but fail in ant - java.lang.RuntimeException: Stub
  • How do i add a tooltip to existing gwt Textbox?
  • actor replying to non-actor
  • Google Cloud Messaging - server connection
  • Which classes are unmodifiable and cannot be intrumented and is there a way to bypass it?
  • Java & Jersey 1.17: Custom default response headers
  • Java rounding error
  • Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?
  • Arquillian test class variables lose value
  • java.util.ConcurrentModificationException while inserting in ArrayList
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • Elegant way to create one of a large number of classes
  • Java fx binding styles
  • Summing weights based on string in large file
  • Android ListView setOnItemClickListener not working
  • How is the Java Bootstrap Classloader loaded?
  • Check object is blank
  • Add image between text in JEditorPane
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org