Thursday 14 December 2017

Code

How To Find The Most Repeated Word In Text File In Java?

 pramodbablad

2 years ago

Problem :

Write a java program to find the most repeated word in text file. Your program should take one text file as input and find out the most repeated word in that file.

How To Find The Most Repeated Word In Text File In Java?

Step 1 : Create one HashMap object called wordCountMap which will hold words of the input file as keys and their occurrences as values.

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

Step 2 : Create BufferedReader object to read the input text file.

BufferedReader reader = new BufferedReader(new FileReader(“Pass The File Location Here”));

Step 3 : Read all the lines of input text file one by one into currentLine usingreader.readLine() method.

String currentLine = reader.readLine();

Step 4 : Split the currentLine into words by using space as delimiter. UsetoLowerCase() method here if you don’t want case sensitiveness.

String[] words = currentLine.toLowerCase().split(” “);

Step 5 : Iterate through each word of words array and check whether theword is present in wordCountMap. If wordis already present in wordCountMap, update its count. Otherwise insert theword as a key and 1 as its value.

if(wordCountMap.containsKey(word))

         wordCountMap.put(word, wordCountMap.get(word)+1);
}
else
{
         wordCountMap.put(word, 1);
}

Step 6 : Get the mostRepeatedWord and itscount by iterating through each entry of the wordCountMap.

Step 7 : Close the resources.

Java Program To Find The Most Repeated Word In Text File :

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; public class RepeatedWordInFile { public static void main(String[] args) { //Creating wordCountMap which holds words as keys and their occurrences as values HashMap<String, Integer> wordCountMap = new HashMap<String, Integer>(); BufferedReader reader = null; try { //Creating BufferedReader object reader = new BufferedReader(new FileReader("C:\\sample.txt")); //Reading the first line into currentLine String currentLine = reader.readLine(); while (currentLine != null) { //splitting the currentLine into words String[] words = currentLine.toLowerCase().split(" "); //Iterating each word for (String word : words) { //if word is already present in wordCountMap, updating its count if(wordCountMap.containsKey(word)) { wordCountMap.put(word, wordCountMap.get(word)+1); } //otherwise inserting the word as key and 1 as its value else { wordCountMap.put(word, 1); } } //Reading next line into currentLine currentLine = reader.readLine(); } //Getting the most repeated word and its occurrence String mostRepeatedWord = null; int count = 0; Set<Entry<String, Integer>> entrySet = wordCountMap.entrySet(); for (Entry<String, Integer> entry : entrySet) { if(entry.getValue() > count) { mostRepeatedWord = entry.getKey(); count = entry.getValue(); } } System.out.println("The most repeated word in input file is : "+mostRepeatedWord); System.out.println("Number Of Occurrences : "+count); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); //Closing the reader } catch (IOException e) { e.printStackTrace(); } } } }

Input File :

Java JDBC JSP Servlets
Struts Hibernate java Web Services
Spring JSF JAVA
Threads JaVa Concurrent Programming
jAvA Hadoop Jdbc jsf
spring Jsf jdbc hibernate

Output :

The most repeated word in input file is : java
Number Of Occurrences : 5

How To Find All Repeated Words In Text File And Their Occurrences In Java?

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; public class RepeatedWordsInFile { public static void main(String[] args) { //Creating wordCountMap which holds words as keys and their occurrences as values HashMap<String, Integer> wordCountMap = new HashMap<String, Integer>(); BufferedReader reader = null; try { //Creating BufferedReader object reader = new BufferedReader(new FileReader("C:\\sample.txt")); //Reading the first line into currentLine String currentLine = reader.readLine(); while (currentLine != null) { //splitting the currentLine into words String[] words = currentLine.toLowerCase().split(" "); //Iterating each word for (String word : words) { //if word is already present in wordCountMap, updating its count if(wordCountMap.containsKey(word)) { wordCountMap.put(word, wordCountMap.get(word)+1); } //otherwise inserting the word as key and 1 as its value else { wordCountMap.put(word, 1); } } //Reading next line into currentLine currentLine = reader.readLine(); } //Getting all the entries of wordCountMap in the form of Set Set<Entry<String, Integer>> entrySet = wordCountMap.entrySet(); //Creating a List by passing the entrySet List<Entry<String, Integer>> list = new ArrayList<Entry<String,Integer>>(entrySet); //Sorting the list in the decreasing order of values Collections.sort(list, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) { return (e2.getValue().compareTo(e1.getValue())); } }); //Printing the repeated words in input file along with their occurrences System.out.println("Repeated Words In Input File Are :"); for (Entry<String, Integer> entry : list) { if (entry.getValue() > 1) { System.out.println(entry.getKey() + " : "+ entry.getValue()); } } } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); //Closing the reader } catch (IOException e) { e.printStackTrace(); } } } }

Input File :

Java JDBC JSP Servlets
Struts Hibernate java Web Services
Spring JSF JAVA
Threads JaVa Concurrent Programming
jAvA Hadoop Jdbc jsf
spring Jsf jdbc hibernate

Output :

Repeated Words In Input File Are :
java : 5
jdbc : 3
jsf : 3
hibernate : 2
spring : 2

You may

Wednesday 13 December 2017

String and stringbuilder

Mutability Difference:
String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilderStringBuilder is more efficient than StringBuffer.
Situations:
  • If your string is not going to change use a String class because a String object is immutable.
  • If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
  • If your string can change, and will be accessed from multiple threads, use a StringBufferbecause StringBuffer is synchronous so you have thread-safety.

transient


 is a Java keyword which marks a member variable not to be serialized when it is persisted to streams of bytes. 
When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred; they are lost intentionally.

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization.
java serialization
It is mainly used to travel object's state on the network (known as marshaling).
java.io.Serializable interface 

Serializable is a marker interface (has no data member and method). It is used to "mark" java classes so that objects of these classes may get certain capability. The Cloneable and Remote are also marker interfaces.

-->public class Student implements Serializable

eg:

  1. import java.io.Serializable;  
  2. public class Student implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  public Student(int id, String name) {  
  6.   this.id = id;  
  7.   this.name = name;  
  8.  }  
  9. }  



Spring

1.Starting class implements WebApplicationInitializer interface
(org.springframework.web.WebApplicationInitializer)==>and this class will be scanned by Spring on application startup and bootstrapped.
 then overriding "onStartup" method from WebApplicationInitializer interface
 inside this method
        AnnotationConfigWebApplicationContext appContext = new         AnnotationConfigWebApplicationContext();
    appContext.register(ApplicationContextConfig.class);




ServletRegistration.Dynamic dispatcher = container.addServlet(
                "SpringDispatcher", new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

==>here,Dynamic servlet registration way of registering servlets. In Servlets 3 you can avoid creating web.xml and configure application in pure Java
It gives you some advantages like compile time check if everything is fine
in web.xml shows the above things like this
    <servlet>
     <servlet-name>appServlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
      </init-param>
     <load-on-startup>1</load-on-startup>
        </servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
        </servlet-mapping>

2. class which extend WebMvcConfigurerAdapter is used for bean configuration in web.xml or servlet-context.xml that shown in web.xml contextConfigLocation in init-param in xml

    lot @Beans here used in core java code that replaces what we used in web.xml

a) @Bean(name = "viewResolver")   <===>
      <beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">

-->public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
        }

b)addInterceptors

3)Interceptor
    class which implements "HandlerInterceptorAdapter" is act as inteceptor class
it overriding  "preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)" method

4)@Configuration & @Bean Annotations
Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.

   -->package com.tutorialspoint;
     import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
     @Bean
     public HelloWorld helloWorld(){
      return new HelloWorld();
     }
   }

  equal to

<beans>
   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" />
</beans>

5)@ComponentScan("com.leejo")
Spring needs to know the packages to scan for annotated components. We can use @ComponentScan annotation to specify the base packages to scan. Any class which is annotated with @Component will be scanned for registered.

 6)@EnableWebMvc
     is used to enable Spring MVC
@EnableWebMvc is equivalent to <mvc:annotation-driven /> in XML
It enables support for @Controller-annotated classes that use @RequestMapping to map incoming requests to a certain method.

7)@PropertySource("classpath:some.properties")
<context:property-placeholder location="some.properties"/>
  equall to
    @Configuration
@PropertySource("classpath:some.properties")
public class ApplicationConfiguration

8)If you are using Java based configuration in your application you can enable annotation-driven injection by using AnnotationConfigApplicationContext to load your spring configuration as below:
@Configuration
@ComponentScan("com.baeldung.autowire.sample")
public class AppConfig {}

As an alternative, in Spring XML, it can be enabled by declaring it in Spring XML files like so:
<context:annotation-config/>

@Autowired and Optional Dependencies--->
          public class FooService {

              @Autowired(required = false)
                private FooDAO dataAccessor;
   
                  }

9)@Scope("session")
  The spring framework supports following five scopes. Out of which three scopes are supported only in web ApplicationContext.
    a.Singleton--Return a single bean instance per Spring IoC container
    b.Prototype--Return a new bean instance each time when requested
c.Request-- Return a single bean instance per HTTP request. *
d.Session--Return a single bean instance per HTTP session. *
e.Global Session--Return a single bean instance per global HTTP session. *

site:- https://www.tutorialspoint.com/spring/spring_bean_scopes.htm

10)Controller using @Controller
   The @Controller annotation is used to mark any java class as a controller class.
   The @RequestMapping annotation is used to indicate the type of HTTP request.
 
11)@Repository
  @Repository is an annotation that marks the specific class as a Data Access Object, thus clarifying it's role. Other markers of the same category are @Service and @Controller
   @Autowired is an annotation with a completely different meaning: it basically tells the DI container to inject a dependency.
 
12)@Service
  annotate classes at service layer level.
  annotation is used in your service layer and annotates classes that perform service tasks, often you don't use it but in many case you use this annotation to represent a best practice. For example, you could directly call a DAO class to persist an object to your database but this is horrible. It is pretty good to call a service class that calls a DAO. This is a good thing to perform the separation of concerns pattern.

13)Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection.

@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); registry.addResourceHandler("/uploads/**").addResourceLocations("/uploads/"); registry.addResourceHandler("/albums/**").addResourceLocations("/albums/"); }

==>pending
CascadeType

fetch = FetchType.LAZY,fetch = FetchType.EAGER 

Caching in Hibernate

Sieilaization
synchronisation
Cloneable ,how to create copy of object

Thursday 7 December 2017

Generics in Java

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any
type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

List list = new ArrayList(); 
list.add("hello"); 
String s = (String) list.get(0);//typecasting 
After Generics, we don't need to typecast the object.

List<String> list = new ArrayList<String>(); 
list.add("hello"); 
String s = list.get(0); 

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

List<String> list = new ArrayList<String>(); 
list.add("hello"); 
list.add(32);//Compile Time Error
Syntax to use generic collection

ClassOrInterface<Type>
Example to use Generics in java

ArrayList<String>