Friday, 15 September 2023

How to convert Alphanumeric to Numeric String

 

Hi.

have you faced scenarios like you have alphanumeric String and you have requirement to use numeric String to fullfil your requirement, like if need to convert in other data type later.


so here is Magic in below programe:- 


package com.neesri.sorting;


public class AlphanumericToNumeric {


public static void main(String[] args) {

// convert alphanumeric string into numeric string

String str = "a12334tyz78x";

str = str.replaceAll("[^\\d]", "");


System.out.println("Alphanumeric string to Number "+ str);

}

}

======output====


Alphanumeric string to Number 1233478


Happy Learning :) 

How many ways can convert HashMap to List

Hi,

Today we will talk about how we can convert Hashmap into ArrayList.

1. we have converted keys of HashMap into List.

2. we have converted all values of Map into List.

3. we have converted all entries(key  & values) of HashMap into List.

In below i have explained programme stepwise:- 

package com.neesri.sorting;

 

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map.Entry;

import java.util.Set;

 

public class ConvertMapToList {

     // we can convert Hashmap into Arraylist through three ways

     public static void main(String[] args) {

 

           HashMap<String, Integer> hashmapObj = new HashMap<>();

           hashmapObj.put("Zimbabwe", 600);

           hashmapObj.put("India", 700);

           hashmapObj.put("SriLanka", 400);

           hashmapObj.put("Nepal", 800);

 

           // 1-----convert Hashmap Key into List

           // using keyset method retun set view

           Set<String> setViewOfMapKeys = hashmapObj.keySet();

           // convert set into list

           List<String> listObj = new ArrayList<>(setViewOfMapKeys);

 

           System.out.println("Hashmap Keys into list------>");

           for (String printList : listObj) {

                System.out.println(printList);

           }

 

           // 2. Convert Hashmap Values into List

 

           Collection<Integer> values = hashmapObj.values();

           List<Integer> list = new ArrayList<>(values);

           System.out.println("Hashmap values into List----->");

           for (Integer hashmapValuesIntoList : list) {

                System.out.println(hashmapValuesIntoList);

           }

 

           // 3. Convert hashmap all entries into List

 

           Set<Entry<String, Integer>> entriesObjSet = hashmapObj.entrySet();

           List<Entry<String, Integer>> listEntries = new ArrayList<>(entriesObjSet);

 

           // System.out.println("Hashmap all entries into List======>");

           /*

            * for(Object obj:listEntries) {

            *

            * System.out.println(obj); }

            */

           // OR

 

           /*

            * for(Entry<String, Integer> obj:listEntries) {

            *

            * System.out.println(obj); }

            */

 

           // OR

           System.out.println("Printing thorough iterator======>");

           Iterator<Entry<String, Integer>> iterator = listEntries.iterator();

 

           while (iterator.hasNext()) {

                Entry<String, Integer> entry = iterator.next();

 

                System.out.println(entry);

           }

 

     }

 

}

 

==============OUTPUT======

Hashmap Keys into list------>

SriLanka

Zimbabwe

Nepal

India

Hashmap values into List----->

400

600

800

700

Printing thorough iterator======>

SriLanka=400

Zimbabwe=600

Nepal=800

India=700

 

 

Happy Learning :) 

Saturday, 26 August 2023

Tricky question

 

In a social media application, You have a collection of posts, where each post can have multiple comments. 

To retrieve all the comments from all the posts and represents them as a single stream,
Which java Stream operation would you use?

 

The correct answer is flatmap().

So what is flatmap, flatMap() = Flattening + map()

It is an intermediate operation that is always lazy as described in Java Stream API

flattening means,  merging multiple collections/arrays into one.

OR,

Flattening is the process of converting several lists of lists and merge all those lists to create a single list containing all the elements from all the lists.

Flattening Example

Consider the following lists of lists:

Before Flattening: [[1, 2, 3, 4], [7, 8, 9, 0], [5, 6], [12, 18, 19, 20, 17], [22],[23,24,25,26,27]]

After Flattening: [1, 2, 3, 4, 7, 8, 9, 0, 5, 6, 12, 18, 19, 20, 17, 22,23,24,25,26,27]

Syntax

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)


  • R represents the element type of the new stream.
  • mapper is a non-interfering, stateless function to apply to each element which produces a stream of new values.
  • The method returns a new stream of objects of type R.

Similar flatMap() Methods

IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)

Some examples where flatMap can be used are:
Count of words of a text file.
Convert a Nested List into a single List.
Convert a Nested Array into a single Lis

Wednesday, 19 April 2023

How Many ways we can print Array in Java

 

Hi Friends,

Today i am going to show how many ways we can print Array in Java.

As we know following points:- 

Java array is a data structure where we can store the elements of the same data type.

The elements of an array are stored in a contiguous memory location. 

So, we can store a fixed set of elements in an array.

The index of an array starts from 0. 


there are following ways to print array:

Friday, 14 April 2023

How to change font size in Eclipse or STS for Java text editors?

 As Many of us face this issue, while using STS or Eclipse.

Also you you change theme Light to Dark mode then also need to change font size otherwise it would looks like very light.

So i am providing you steps to do it.

1.Go to Window tab of Eclipse or STS.

2.Click on Prefences

3.General → Appearance → Colors and Fonts → Java Editor text font

Please see below image and do the same.



Thanks,

Happy Learning

Saturday, 26 June 2021

Find Smallest and Largest elements in an Array - Java Program

Problem Statements:-  

You are given an array of numbers. You need to find smallest and largest numbers in the array.

Solutions:- 

  1. Initialize two variable largest and smallest with array[0] 
  2. Iterate over array If current element is greater than largest, then assign current element to largest. If current element is smaller than smallest, then assign current element to smallest. 
  3. You will get smallest and largest element in the end.

Java code to find Smallest and Largest Element in an Array :

package com.datastructure.Array;

public class LargestAndSmallestElementsInArray {

            public static void main(String[] args) {

             int arrays[] = { 2, 5, 3, 1, 6, 7, 8, 9, 2, 4, 5, 9 };

              findLargestAndSmallestElementsInArray(arrays);

}

   private static void findLargestAndSmallestElementsInArray(int[] arrays) {


int smallestElements = arrays[0];

int largestElements = arrays[0];


for (int i = 0; i < arrays.length; i++) {


if (arrays[i] > largestElements) {

largestElements = arrays[i];


} else if (arrays[i] < smallestElements) {

smallestElements = arrays[i];

}

}

                 System.out.println("Smallest elements in array is : " + smallestElements);

                 System.out.println("Largest elements in array is : " + largestElements);

}

}

Output:-

Smallest elements in array is : 1

Largest elements in array is : 9


Thank you

Happy Learning


Monday, 18 May 2020

ConcurrentHashMap Concept

CONCURRENTHASHMAP

Hashtable and SynchronizedMap both acquires lock on entire Map object which provides thread-safety, but not good performance as at a time only one thread can access that Map instance.

To overcome this issue, ConcurrentHashMap was introduced in Java 5 along with other concurrent classes like CountDownLatch, CyclicBarrier,  CopyOnWriteArrayList, BlockingQueue within java.util.Concurrent package.

More than one threads can read and write concurrently in ConcurrentHashMap and still it provides thread-safety. Amazing, isn't it? How is it implemented internally?


Well, ConcurrentHashMap divides the Map instance into different segments. And each thread acquires lock on each segment. By default it allows 16 threads to access it simultaneously without any external synchronization i.e. by default concurrency level is 16. We can also increase or decrease the default concurrency level while creating ConcurrentHashMap by using below constructor :

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)

Concurrency-Level (default value 16): Defines the number which is an estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this  many threads. 

Load-Factor (default value 0.75: It's a threshold, used to control resizing.

Initial Capacity  (default value 16): The implementation performs internal sizing to accommodate these many elements.

When we say, ConcurrentHashMap locks only part of it.It actually locks a Segment. So  if two threads are  writing different segments in same ConcurrentHashMap, it allows write operation without any conflicts.

So Segments are only for write operations. In case of read operation, it allows full concurrency and provides most recently updated value using volatile variables.

 ConcurrentHashMap class declaration

public class ConcurrentHashMap<K,V>  
extends AbstractMap<K,V>  
implements ConcurrentMap<K,V>, Serializable 

 ConcurrentHashMap Constructor : 

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)

Can Multiple thread write in the same segment?

No. Thread acquires a lock on segment in put() operation and at a time only one thread can write in that segment.

Can two threads write in the different segment?

Yes. Two threads are allowed to write concurrently in different segments.

Can Multiple thread read from the same segment?

Yes. Thread doesn't acquire a lock on segment in get() operation and any number of threads can read from the same segment.

If one thread is writing in a segment, can another thread read from that segment()?

Yes. but in this case last updated value will be seen by the reading thread.

Can ConcurrentHashMap use Null keys and values?

ConcurrentHashMap doesn't allow null keys and null values.

If we choose ConcurrenyLevel as 10 then what will be size of Segment array? Is Segment array size exactly same as concurrenyLevel? If No, then how is the Segment array size calculated?

Segment array size is calculated based on concurrenyLevel specified but it doesn't mean it will be exactly same as concurrenyLevel.

If concurrenyLevel is 10 then Segment array size will be 16.

Segment array size = 2 to the power x, where result should be >= concurrenyLevel(in our case it is 10)
Segment array size = 2 to the power x >= 10

Segment array size = 2 ^ 1 = 2   >= 10 (False)
Segment array size = 2 ^ 2 = 4   >= 10 (False)
Segment array size = 2 ^ 3 = 8   >= 10 (False)
Segment array size = 2 ^ 4 = 16 >= 10 (True)

Segment array size is 16.

Example: 2
concurrenyLevel = 8 then Segment array size = ?
Find 2 ^ x >= 8

2 ^ 1 >= 2
2 ^ 2 >= 4
2 ^ 3 >= 8
Segment array size will be 8.