Skip to content

Instantly share code, notes, and snippets.

@dhval
Last active February 11, 2022 15:00
Show Gist options
  • Save dhval/a245fa99fad5d1acb8ffda8327d5f376 to your computer and use it in GitHub Desktop.
Save dhval/a245fa99fad5d1acb8ffda8327d5f376 to your computer and use it in GitHub Desktop.
Java/CSharp API reference

|--- Strings |--- Char

*** String is immutable so they do not have method like reverse.

  • .toCharArray()
  • .split()

*** StringBuilder is non-synchronized.

  • reverse()
  • sb.length() == 0

*** Can be converted to characters[]

 // ch = "a"
String ch = Character.toString((char) 97);
  • "".toCharArray()
  • charAt()

|--- Numbers |--- Integer

  • Integer.toBinaryString(-10)
  • Integer.MAX_VALUE | Integer.MIN_VALUE

*** Always use Integer.compare() or .equals() to prevent overflow.

*** MIN_VALUE & MAX_VALUE => 2^31-1

Integer.MIN_VALUE || -2147483648 || 1<<31 Integer.MAX_VALUE

*** Largest Prime Number 10^9+7 n % 1000000007

1<<0>>

|--- Numbers |--- Random

new Random().nextInt(range); 

new BigInteger(130, new SecureRandom()).toString(32);

UUID.randomUUID().toString();

RandomStringUtils.randomAlphanumeric(20).toUpperCase();

|--- Date

// Add a month to current date.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);

LocalDate date = LocalDate.now().minusDays(300);

Create a Map of key/value pairs in a single line.

Map<String, String> xpaths = Stream.of(
        new AbstractMap.SimpleEntry<>("PersonGivenName", "//erx:SupervisionPerson/nc:PersonName/nc:PersonGivenName"),
        new AbstractMap.SimpleEntry<>("PersonBirthDate", "//erx:SupervisionPerson/nc:PersonBirthDate/nc:Date")
).collect(Collectors.toMap(e -> e.getKey(), e-> e.getValue()));
map.getOrDefualt(key, def)

|--- List

  • Methods

get, add (pos, el), contains, remove

-- remove will only remove first element if present, returns true or false.
  • Boxing, for a List

    list.remove(Integer.valueOf(i)) or int index = list.indexOf(i); list.remove(index);

|--- Map

Tuple or Key-Value Pairs

  • Create a Map of key/value pairs in a single line. Collections.singletonMap(key, value)

  • Use AbstractMap to create an Entry

Map.Entry<String, Integer> tuple; tuple = new AbstractMap.SimpleEntry<>("Key", 0);

    Map<String, String> xpaths = Stream.of(
            new AbstractMap.SimpleEntry<>("PersonGivenName", "//erx:SupervisionPerson/nc:PersonName/nc:PersonGivenName"),
            new AbstractMap.SimpleEntry<>("PersonBirthDate", "//erx:SupervisionPerson/nc:PersonBirthDate/nc:Date")
    ).collect(Collectors.toMap(e -> e.getKey(), e-> e.getValue()));

Sorting

  • By values, natural order is ascending, list of type Map.Entry
    List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
    list.sort(Map.Entry.comparingByValue());
  • For Reversed, we need to supply type as compiler cannot infer it.
    entries.sort(Entry.<String, Integer>comparingByValue().reversed());

TreeMap

https://stackoverflow.com/questions/38831409/priority-queue-or-min-heap-with-olog-n-deletion-of-arbitrary-node

Reading from IConfiguration, represents key-value pairs from appsettings.json. Similar to @PropertySource from Spring.

List emailTo = _config.GetSection("Email:ToEmails").Get<List>();

Read first item from array.

var item0 = _config.GetSection("MyArray:0");

Queue

  • must be linkedlist and not array list for the queue
  • offer returns false (queue is full) while add throws IllegalStateException
  • peek, poll
    Queue<Map.Entry<Integer, Integer>> entries = new LinkedList<Map.Entry<Integer, Integer>>();

Priority Queue

  • see constructor using lambda expression
  • offer => put msg, peek, poll
  • it is maintained using heap data structure
  • O(1) -> peek, size | O(lg n) -> offer, poll, emove | O(n) remove(obj) since contains(obj) takes n time.
    PriorityQueue<Map.Entry<Character,Integer>> pq = new PriorityQueue<>((a,b)->b.getValue()-a.getValue());

Min and Max Heap

  • Natural order is ascending

PriorityQueue minHeap = new PriorityQueue(); PriorityQueue maxHeap = new PriorityQueue<>(Comparator.reverseOrder());

    public String frequencySort(String s) {
        int[] f = new int[128];
        for(char c : s.toCharArray())
            f[c]++;
        
        // instead of sorting by values we use PQ, reverse order

        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]);
        for(int i = 0; i < f.length; i++)
            pq.offer(new int[] {i, f[i]});
        
        StringBuilder sb = new StringBuilder();

        // since elements at the bottom are '0' frequency

        while(pq.peek()[1] != 0) {
            int[] pair = pq.poll();
            int count = pair[1];
            while(count-- > 0)
                sb.append((char) pair[0]);
        }
        
        return sb.toString();
    }

Read/Write string to file.

try(BufferedWriter w = new BufferedWriter(new FileWriter(path,true)))  
  { w.write(string); }

String srcXml = new String(Files.readAllBytes(new File(file).toPath()), Charset.forName("UTF-8"));

Copy content to another file line by line, using try-with-resource and streams.

try (Stream<String> stream = Files.lines(Paths.get(fileName));
    BufferedWriter writer = Files.newBufferedWriter(Paths.get(outfileName))) {
    stream.forEach(line -> { 
      try {
          writer.write(line);
      } catch (IOException e1) {
          e1.printStackTrace();
      }    
    });
} catch (IOException e) {
  e.printStackTrace();
}

File Streams

Reading a file with InputStreamReader and FileInputStream

InputStreamReader input = new InputStreamReader(new FileInputStream("foo.txt"));

InputStream reads a raw socket (8 bit) data, InputStreamReader transform data to some encoding, BufferedReader is a wrapper for xxxReader.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();

// From ClassLoader, all paths are "absolute" already - there's no context // from which they could be relative. Therefore you don't need a leading slash. InputStream in = this.getClass().getClassLoader() .getResourceAsStream("SomeTextFile.txt"); // From Class, the path is relative to the package of the class unless // you include a leading slash, so if you don't want to use the current // package, include a slash like this: InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

/**

StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString();

public static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A"); return s.hasNext() ? s.next() : ""; }

/**

  • Where is the class loaded from, file:/path/myclass.class
  • */

URL location = String.class.getResource('/'+klass.getName().replace('.', '/')+".class");

Enumeration to Stream SO

  • forEachRemaining provides for consuming all elements
  • Collections.list(Enumeration) copies the entire list.
  • Java 9 nets.asIterator().forEachRemaining(iface -> { ... });
public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(
            new Iterator<T>() {
                public T next() {
                    return e.nextElement();
                }
                public boolean hasNext() {
                    return e.hasMoreElements();
                }
                public void forEachRemaining(Consumer<? super T> action) {
                    while(e.hasMoreElements()) action.accept(e.nextElement());
                }
            },
            Spliterator.ORDERED), false);
}

Without delegating to Iterator.

public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) {
    return StreamSupport.stream(
        new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) {
            public boolean tryAdvance(Consumer<? super T> action) {
                if(e.hasMoreElements()) {
                    action.accept(e.nextElement());
                    return true;
                }
                return false;
            }
            public void forEachRemaining(Consumer<? super T> action) {
                while(e.hasMoreElements()) action.accept(e.nextElement());
            }
    }, false);
}

Use static forEachRemaining SO

public static <T> void forEachRemaining(Enumeration<T> e, Consumer<? super T> c) {
  while(e.hasMoreElements()) c.accept(e.nextElement());
}

Frequency Map

Map<Character, Integer> map = new HashMap<>(); String str = "sfjaklfghbvabjk. jkalf aljfja";

str.chars().forEach(ch -> map.put((char) ch, map.getOrDefault((char)ch,0)+1))

Remove duplicates from a stream

   public static <T> Predicate<T> distinctItem(Function<? super T, ?> func) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(func.apply(t), Boolean.TRUE) == null;
    }

Arrays Comparator

    Arrays.sort(months, Comparator.comparingInt(String::length));
    Arrays.sort(months, (a, b) -> a.length() - b.length());
    Arrays.sort(arr2, Comparator.reverseOrder());

List remove item

    students.removeIf(n -> (n.charAt(0) == 'S'));

    books.stream()
        .filter(b -> b.getIsbn().equals(other))
        .collect(Collectors.toList())


    ListIterator<Book> iter = books.listIterator();
    while(iter.hasNext()){
        if(iter.next().getIsbn().equals(isbn)){
            iter.remove();
        }
    }

Find first item in list

    examples.iterator().next()

Use Filter with findAny to stop execution sooner.

    .filter(num -> num < 4).findAny();

Arrays.asList("10", "6.548", "9.12", "11", "15");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment