counting the number of duplicates in the linked list Java - java

I'm trying to put the text file into a linkedlist and count how many duplicate words are in the linked list.
Here is my base code.
public class Node{
private Node next;
private String data;
private int Dup_Counter= 0;
public Node(){
this.next = null;
this.data = data;
this.Dup_Counter = 0;
}
public String fiile_Reader() throws FileNotFoundException {
File file = new File("/Users/djhanz/IdeaProjects/datalab2/pg174.txt"); //reading a plain text file
Scanner scan = new Scanner(file);
String fileContent = ""; // initalizing an empty string to put scanned string text file
while (scan.hasNextLine()) {
fileContent = fileContent.concat(scan.nextLine() + "\n"); // scan and put in into string object
}
fileContent = fileContent.replaceAll("\\p{Punct}", ""); // remove all the punctuation characters
fileContent = fileContent.toLowerCase();
return fileContent;
}
public void insert() throws FileNotFoundException{
Node cursor = head;
Single_LL Linked_L = new Single_LL();
String file_content = Linked_L.fiile_Reader();
String[] splitted_File = file_content.split(" ");
for(int i=0 ; i<splitted_File.length; i++){
Linked_L.add(splitted_File[i]);
}
}
public int Word_Counter(String word){
String compare =word;
Node cursor = head;
int counter = 0;
while(cursor!=null){
if (cursor.data.equals(compare)){
counter++;
}
cursor = cursor.next;
}
return counter;
}
public void Dup_Count(){
Node cursor = head.next;
while (cursor != null){
if(head.data == cursor.data){
head.Dup_Counter++;
break;
}
cursor = cursor.next;
System.out.println(cursor.Dup_Counter);
}
head = head.next;
}
public String dup_num(){
Node cursor = head;
String rtn = "";
while (cursor!= null){
if(cursor.Dup_Counter > 20 ){
rtn += cursor.data + " -> ";
}
cursor = cursor.next;
}
return rtn;
}
public static void main(String[] args) throws FileNotFoundException {
Program1 test = new Program1();
String file_content = test.fiile_Reader();
Single_LL Linked_L = new Single_LL();
String[] splitted_File = file_content.split(" ");
int spli_len = splitted_File.length;
for(int i =0; i< spli_len; i++){
Linked_L.add(splitted_File[i]);
}
My approach is that I added anthoer variable in Node Class called dup_counter.
Function Dup_Count() is looping through the linked list and when it sees that duplicate it updates the Node's dup_counter variable.
I'm trying to find words that appeared more than 20 times and dup_num() is my approach to do this. Looping through the linkedlist and if the Node's dup_counter is more than 20 add it to the string and return it. However, Dup_Count() is not in fact updating the dup_count value. Insertion worked fine but I can't seem to find what is wrong with my dup_counter. Can someone please help me fix the bug?

I would recommend trying to simplify your task using a Map as follows
Somehow get all of the words into a collection Collection<String> words. This should be easy to do using the reader code you already have.
Now, to count the number of occurrences of each word, we can use a Map:
Map<Integer, Long> counter = words.stream()
.collect(Collectors.groupingBy(p -> p, Collectors.counting()));
Now you wanted to find all of the words that occurred more than 20 times, you could evaluate
Set<String> wordsOccuringManyTimes = counter
.entrySet().stream()
.filter(e -> e.getValue() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
And if you wanted to get the total sum of all duplicates, you could simply evaluate
int duplicateCount = counter.values().stream().mapToInt(x -> x - 1).sum();

Related

How can I get the count of most duplicated value in a list after sorting it alphabetically?

What is the easiest way to get the most duplicated value in a list and sorted in descending order...
for example:
List<String> list = new ArrayList<>(List.of("Renault","BMW","Renault","Renault","Toyota","Rexon","BMW","Opel","Rexon","Rexon"));
`
"renault" & "rexon" are most duplicated and if sorted in descending order alphabetically I would like to get the rexon.
I think one of the most readable and elegant way would be to use the Streams API
strings.stream()
.collect(Collectors.groupingBy(x -> x, Collectors.counting()))
.entrySet().stream()
.max(Comparator.comparingLong((ToLongFunction<Map.Entry<String, Long>>) Map.Entry::getValue).thenComparing(Map.Entry::getKey))
.map(Map.Entry::getKey)
.ifPresent(System.out::println);
Create a map of names with their corresponding number of occurrences.
Get names and sort them in descending order.
Print the first name that has the highest number of occurrences.
class Scratch {
public static void main(String[] args) {
List<String> list = List.of("Renault","BMW","Renault","Renault","Toyota","Rexon","BMW","Opel","Rexon","Rexon");
Map<String, Integer> duplicates = new HashMap<>();
// 1. Create a map of names with their corresponding
// number of occurrences.
for (String s: list) {
duplicates.merge(s, 1, Integer::sum);
}
// 2. Get names and sort them in descending order.
List<String> newList = new ArrayList<String>(duplicates.keySet());
newList.sort(Collections.reverseOrder());
// 3. Print the first name that has the highest number of
// occurrences.
Integer max = Collections.max(duplicates.values());
newList.stream().filter(name -> duplicates.get(name).equals(max))
.findFirst()
.ifPresent(System.out::println);
}
}
After some time this is what I came with (I only tested it with your example and it worked):
public class Duplicated {
public static String MostDuplicated(String[] a) {
int dup = 0;
int position = -1;
int maxDup = 0;
for(int i = 0; i < a.length; i++) { //for every position
for(int j = 0; j < a.length; j++){ //compare it to all
if(a[i].equals(a[j])) { dup++; } // and count how many time is duplicated
}
if (dup > maxDup) { maxDup = dup; position = i;}
//if the number of duplications
//is greater than the maximum you have got so far, save this position.
else if (dup == maxDup) {
if( a[i].compareTo(a[position]) > 0 ){ position = i; }
//if its the same, keep the position of the alphabetical last
// (if u want the alphabetical first, just change the "<" to ">")
}
}
return a[position]; //return the position you saved
}
}
You are asking to sort the list and then find the most common item.
I would suggest that the easiest way to sort the list is using the sort method that is built into list.
I would then suggest finding the most common by looping with the for..each construct, keeping track of the current and longest streaks.
I like Yassin Hajaj's answer with streams but I find this way easier to write and easier to read. Your mileage may vary, as this is subjective. :)
import java.util.*;
public class SortingAndMostCommonDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Renault","BMW","Renault","Renault","Toyota","Rexon","BMW","Opel","Rexon","Rexon"));
list.sort(Comparator.reverseOrder());
System.out.println(list);
System.out.println("The most common is " + mostCommon(list) + ".");
}
private static String mostCommon(List<String> list) {
String mostCommon = null;
int longestStreak = 0;
String previous = null;
int currentStreak = 0;
for (String s : list) {
currentStreak = 1 + (s.equals(previous) ? currentStreak : 0);
if (currentStreak > longestStreak) {
mostCommon = s;
longestStreak = currentStreak;
}
previous = s;
}
return mostCommon;
}
}
The fast algorithm takes advantage of the fact that the list is sorted and finds the list with the most duplicates in O(n), with n being the size of the list. Since the list is sorted the duplicates will be together in consecutive positions:
private static String getMostDuplicates(List<String> list) {
if(!list.isEmpty()) {
list.sort(Comparator.reverseOrder());
String prev = list.get(0);
String found_max = prev;
int max_dup = 1;
int curr_max_dup = 0;
for (String s : list) {
if (!s.equals(prev)) {
if (curr_max_dup > max_dup) {
max_dup = curr_max_dup;
found_max = prev;
}
curr_max_dup = 0;
}
curr_max_dup++;
prev = s;
}
return found_max;
}
return "";
}
Explanation:
We iterate through the list and keep track of the maximum of duplicates found so far and the previous element. If the current element is the same as the previous one we increment the number of duplicates found so far. Otherwise, we check if the number of duplicates is the bigger than the previous maximum of duplicates found. If it is we update accordingly
A complete running example:
public class Duplicates {
private static String getMostDuplicates(List<String> list) {
if(!list.isEmpty()) {
list.sort(Comparator.reverseOrder());
String prev = list.get(0);
String found_max = prev;
int max_dup = 1;
int curr_max_dup = 0;
for (String s : list) {
if (!s.equals(prev)) {
if (curr_max_dup > max_dup) {
max_dup = curr_max_dup;
found_max = prev;
}
curr_max_dup = 0;
}
curr_max_dup++;
prev = s;
}
return found_max;
}
return "";
}
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Renault","BMW","Renault","Renault","Toyota","Rexon","BMW","Opel","Rexon","Rexon"));
String duplicates = getMostDuplicates(list);
System.out.println("----- Test 1 -----");
System.out.println(duplicates);
list = new ArrayList<>(List.of("Renault","BMW"));
duplicates = getMostDuplicates(list);
System.out.println("----- Test 2 -----");
System.out.println(duplicates);
list = new ArrayList<>(List.of("Renault"));
duplicates = getMostDuplicates(list);
System.out.println("----- Test 3 -----");
System.out.println(duplicates);
}
}
Output:
----- Test 1 -----
Rexon
----- Test 2 -----
Renault
----- Test 3 -----
Renault
Actually, I found a solution which works:
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Renault", "BMW", "BMW", "Renault", "Renault", "Toyota",
"Rexon", "BMW", "Opel", "Rexon", "Rexon"));
Map<String, Integer> soldProducts = new HashMap<>();
for (String s : list) {
soldProducts.put(s, soldProducts.getOrDefault(s, 0) + 1);
}
LinkedHashMap<String, Integer> sortedMap = soldProducts.entrySet()
.stream()
.sorted(VALUE_COMPARATOR.thenComparing(KEY_COMPARATOR_REVERSED))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
String result = "";
for (Map.Entry<String, Integer> s : sortedMap.entrySet()) {
result = s.getKey();
}
System.out.println(result);
}
static final Comparator<Map.Entry<String, Integer>> KEY_COMPARATOR_REVERSED =
Map.Entry.comparingByKey(Comparator.naturalOrder());
static final Comparator<Map.Entry<String, Integer>> VALUE_COMPARATOR =
Map.Entry.comparingByValue();

Adding Values to a LinkedList Not Working

I am trying to do a programming problem a day on leetcode to improve my programming and am having issues adding to a LinkedList in the problem below. I was wondering if anyone could give me some pointers. I know my answer isn't the most efficient, I just wanted to start somewhere and work myself up. Everything within the method is stuff I did so far. I really appreciate any help.
///
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Here's a picture with an example for a possible output:
https://imgur.com/a/g9rlb
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(-1);
ListNode curr = new ListNode(-1);
ListNode newNode = new ListNode(-1);
// Take numbers from linkedList and store in strings
String s1 = "";
String s2 = "";
// String values after being reveresed in the right direction.
String sR1 = "";
String sR2 = "";
while(l1 != null) {
s1 += l1.val;
l1 = l1.next;
}
while(l2 != null) {
s2 += l2.val;
l2 = l2.next;
}
//check
System.out.println(s1);
System.out.println(s2);
//reverse the string;
for(int i = s1.length()-1; i >= 0; i--) {
sR1 += s1.charAt(i);
}
for(int j = s2.length()-1; j >= 0; j--) {
sR2 += s2.charAt(j);
}
//Adding the numbers together to get the final value.
int n3 = Integer.parseInt(sR1) + Integer.parseInt(sR2);
//Converting ints to string so i can parse them into characters that will eventually be parsed into an int to return back to the LinkedList
String fin = Integer.toString(n3);
System.out.println(fin);
//adding the values to my final linked list that i'd be returning here. This is the part that isn't working.
for(int i = 0; i < fin.length()-1; i++){
String s = String.valueOf(fin.charAt(i));
int num = Integer.parseInt(s);
newNode = new ListNode(num);
if(l3.val == -1) {
l3 = newNode;
}
else {
curr = l3;
while(curr.next != null){
curr = curr.next;
}
curr.val = num;
}
}
return l3;
}
Maybe something like this? The concept here is straight forward.
The requirement is to reverse the nodes and adding them. Which means you just need to choose the right data structure to meet this requirement, which provides you last in first out? Stack. Now that you have you data in a stack just pop the items from the stack and add it up and get your expected result.
There are many ways to solve this, Using an ArrayList, using LinkedList, or plain old arrays, but try to correlate the problem with a known data structure and addressing it that way would give you meaningful output consistently. I could have just pointed you to the concept but having this code will help you think on how to address a specific problem based on the user requirement. Cheers, hope it helps.
import java.util.Scanner;
import java.util.Stack;
public class AddTuple {
public static void main(String[] args) {
Stack<Integer> leftTuple = new Stack<Integer>();
Stack<Integer> rightTuple = new Stack<Integer>();
populateTuple(leftTuple, rightTuple, 3);
Stack<Integer> result = addTuples(leftTuple, rightTuple);
System.out.print("Output: {");
int i = 0;
while (!result.isEmpty()) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(result.pop());
i++;
}
System.out.println("}");
}
private static void populateTuple(Stack<Integer> leftTuple, Stack<Integer> rightTuple, int count) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Input: ");
String input = scanner.nextLine();
if (input == null || !input.contains("+") || !input.contains("{")) {
throw new RuntimeException("Usage: {x,y,z} + {a,b,c}");
}
String[] operandSplit = input.split("\\+");
String left = operandSplit[0].trim();
String right = operandSplit[1].trim();
left = left.replaceAll("\\{", "");
left = left.replaceAll("\\}", "");
right = right.replaceAll("\\{", "");
right = right.replaceAll("\\}", "");
String[] leftSplit = left.split(",");
String[] rightSplit = right.split(",");
for (int i = 0; i < leftSplit.length; i++) {
leftTuple.push(Integer.parseInt(leftSplit[i].trim()));
}
for (int i = 0; i < rightSplit.length; i++) {
rightTuple.push(Integer.parseInt(rightSplit[i].trim()));
}
} finally {
scanner.close();
}
}
private static Stack<Integer> addTuples(Stack<Integer> leftTuple, Stack<Integer> rightTuple) {
Stack<Integer> result = new Stack<Integer>();
int carryForward = 0;
while (!leftTuple.isEmpty()) {
int addition = leftTuple.pop() + rightTuple.pop() + carryForward;
if (addition > 9) {
carryForward = 1;
addition = 10 - addition;
}
result.push(addition);
}
return result;
}
}

Determine whether two single-linked lists are identical or not?

I want to determine whether two single-linked lists are identical or not.
If they are identical, the program should print matched letters.
Examples:
murmur and tartar are identical, because they both have the same pattern "abcabc".
AAABBCbbaaa and 11122322111 are identical
Matched letters:
A ↔ 1
B ↔ 2
C ↔ 3
I must use ONLY single linked list.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string:");
String linked1=scanner.nextLine();
System.out.println();
System.out.print("Please enter another string:");
String linked2=scanner.nextLine();
SingleLinkedList SLL1 = new SingleLinkedList();
SingleLinkedList SLL2 = new SingleLinkedList();
for (int i = 0; i < linked1.length(); i++) {
char a=linked1.charAt(i);
a = Character.toLowerCase(a);
SLL1.addToEnd(a);
}
for (int i = 0; i < linked2.length(); i++) {
char a=linked2.charAt(i);
a = Character.toLowerCase(a);
SLL2.addToEnd(a);
}
public class SingleLinkedList{
private Node head;
public SingleLinkedList()
{
head = null;
}
public boolean isEmpty(){
return head == null;
}
public void addToEnd(Object dataToAdd)
{
Node newNode = new Node(dataToAdd);
if(head == null)
{
head = newNode;
}
else
{
Node temp = head;
while(temp.getLink() != null)
{
temp = temp.getLink();
}
temp.setLink(newNode);
}
}
public String display()
{
String output = "";
Node temp = head;
while(temp != null)
{
output += temp.getData() + " ";
temp = temp.getLink();
}
return output;
}
}
You can do it, but it's a tedious work and I haven't got the strength to write the actual code.
You should encode (not encrypt) your sequences.
A trivial way of encoding your list is to iterate it's values, each value you pick must be checked against a seq of already encountered values.
If the value is not present on the check seq, you add it and go on.
At the end of this you will have a seq of unique values ordered as you found them.
Then, for each element of your seq you find which is the position in your check set, and build a new seq of those positions.
You repeat it for both your sequences, and then you can match your encoded sequences.
You should create an indexOf method for your seq to simplify your program.

Ordering java linked list alphabetically (dictionary-like)

I've been working for hours trying to order a linked list of strings alphabetically (dictionary-like). The given string is lowercase only.
For example, input of: "hello my name is albert" will be sorted in the list as: Node 1: albert,
Node 2: hello,
Node 3: is,
etc..
My code so far reads a string like the example above and insert it as nodes - unordered.
I've searched in the web for ways to sort a linked list alphabetically with good performance, and I found Merge Sort can be usefull.
I've changed the merge sort to work for string using compareTo() but my code returns nullPointerException error in the following line:
if(firstList._word.compareTo(secondList._word) < 0){
I'm looking for help to fix the following code or another way for sorting a linked list alphabetically (without Collection.sort)
My full code is (after trying to add the merge sort to work with my code):
public class TextList
{
public WordNode _head;
public TextList()
{
_head = null;
}
public TextList (String text)
{
this._head = new WordNode();
int lastIndex = 0;
boolean foundSpace = false;
String newString;
WordNode prev,next;
if (text.length() == 0) {
this._head._word = null;
this._head._next = null;
}
else {
for (int i=0;i<text.length();i++)
{
if (text.charAt(i) == ' ') {
newString = text.substring(lastIndex,i);
insertNode(newString);
// Update indexes
lastIndex = i;
// set to true when the string has a space
foundSpace = true;
}
}
if (!foundSpace) {
//If we didnt find any space, set the given word
_head.setWord(text);
_head.setNext(null);
}
else {
//Insert last word
String lastString = text.substring(lastIndex,text.length());
WordNode lastNode = new WordNode(_head._word,_head._next);
_head.setNext(new WordNode(lastString,lastNode));
}
sortList(_head);
}
}
private void insertNode(String word)
{
//Create a new node and put the curret node in it
WordNode newWord = new WordNode(_head._word,_head.getNext());
//Set the new information in the head
_head._word = word;
_head.setNext(newWord);
}
private WordNode sortList(WordNode start) {
if (start == null || start._next == null) return start;
WordNode fast = start;
WordNode slow = start;
// get in middle of the list :
while (fast._next!= null && fast._next._next !=null){
slow = slow._next; fast = fast._next._next;
}
fast = slow._next;
slow._next=null;
return mergeSortedList(sortList(start),sortList(fast));
}
private WordNode mergeSortedList(WordNode firstList,WordNode secondList){
WordNode returnNode = new WordNode("",null);
WordNode trackingPointer = returnNode;
while(firstList!=null && secondList!=null){
if(firstList._word.compareTo(secondList._word) < 0){
trackingPointer._next = firstList; firstList=firstList._next;
}
else {
trackingPointer._next = secondList; secondList=secondList._next
;}
trackingPointer = trackingPointer._next;
}
if (firstList!=null) trackingPointer._next = firstList;
else if (secondList!=null) trackingPointer._next = secondList;
return returnNode._next;
}
public String toString() {
String result = "";
while(_head.getNext() != null){
_head = _head.getNext();
result += _head._word + ", ";
}
return "List: " + result;
}
public static void main(String[] args) {
TextList str = new TextList("a b c d e a b");
System.out.println(str.toString());
}
}
In the past i have made a method to sort strings alphabetically in an array as school HW, so umm here it is:
private void sortStringsAlphabetically(){
for (int all = 0; all < names.length; all++) {
for (int i = all + 1; i < names.length; i++) {
if (names[all].compareTo(names[i]) > 0) {
String tmp = names[i];
names[i] = names[all];
names[all] = tmp;
}
}
}
}
This piece of code works for Arrays and specifically for an array of names. You can tweak it to work with the list, it is very simple especially if we consider the wide range of methods in the List interface and all it's implementations.
Cheers.
If you don't wanna to have a huge code who gets every first letter of the word and sort them, do it with Collection.sort()
I don't know what is the proplem on Collection.sort() so use it
Here is a short code, that does exactually this what you want to:
String test = "hello my name is albert";
test = test.replaceAll(" ", "\n");
String[] te = test.split("\n");
List<String> stlist = new ArrayList<String>();
for(String st : te) {
stlist.add(st);
}
Collections.sort(stlist);
Regarding NPE you said it is probably because you are having an null string in head at first and keep adding this in insert method.
this._head = new WordNode();
Also the adding last element is also not proper. Just reuse the insert method like below
insertNode(text.substring(lastIndex,text.length()));
These are the ones I thought having problem when you are converting string to lined list
You can use the below code to handle the first null
private void insertNode(String word) {
if (this._head == null) {
this._head = new WordNode(word, null);
} else {
WordNode newWord = new WordNode(_head._word, _head.getNext());
_head._word = word;
_head.setNext(newWord);
}
}

Search ArrayList for certain character in string

What is the correct syntax for searching an ArrayList of strings for a single character? I want to check each string in the array for a single character.
Ultimately I want to perform multiple search and replaces on all strings in an array based on the presence of a single character in the string.
I have reviewed java-examples.com and java docs as well as several methods of searching ArrayLists. None of them do quite what I need.
P.S. Any pointers on using some sort of file library to perform multiple search and replaces would be great.
--- Edit ---
As per MightyPork's recommendations arraylist revised to use simple string type. This also made it compatible with hoosssein's solution which is included.
public void ArrayInput() {
String FileName; // set file variable
FileName = fileName.getText(); // get file name
ArrayList<String> fileContents = new ArrayList<String>(); // create arraylist
try {
BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
String line = null;
while ((line = reader.readLine()) != null) {
if(line.length() > 0) { // don't include blank lines
line = line.trim(); // remove whitespaces
fileContents.add(line); // add to array
}
}
for (String row : fileContents) {
System.out.println(row); // print array to cmd
}
String oldstr;
String newstr;
oldstr = "}";
newstr = "!!!!!";
for(int i = 0; i < fileContents.size(); i++) {
if(fileContents.contains(oldstr)) {
fileContents.set(i, fileContents.get(i).replace(oldstr, newstr));
}
}
for (String row : fileContents) {
System.out.println(row); // print array to cmd
}
// close file
}
catch (IOException ex) { // E.H. for try
JOptionPane.showMessageDialog(null, "File not found. Check name and directory.");
}
}
first you need to iterate the list and search for that character
string.contains("A");
for replacing the character you need to keep in mind that String is immutable and you must replace new string with old string in that list
so the code is like this
public void replace(ArrayList<String> toSearchIn,String oldstr, String newStr ){
for(int i=0;i<toSearchIn.size();i++){
if(toSearchIn.contains(oldstr)){
toSearchIn.set(i, toSearchIn.get(i).replace(oldstr, newStr));
}
}
}
For the search and replace you are better off using a dictionary, if you know that you will replace Hi with Hello. The first one is a simple search, here with the index and the string being returned in a Object[2], you will have to cast the result. It returns the first match, you were not clear on this.
public static Object[] findStringMatchingCharacter(List<String> list,
char character) {
if (list == null)
return null;
Object[] ret = new Object[2];
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (s.contains("" + character)) {
ret[0] = s;
ret[1] = i;
}
return ret;
}
return null;
}
public static void searchAndReplace(ArrayList<String> original,
Map<String, String> dictionary) {
if (original == null || dictionary == null)
return;
for (int i = 0; i < original.size(); i++) {
String s = original.get(i);
if (dictionary.get(s) != null)
original.set(i, dictionary.get(s));
}
}
You can try this, modify as needed:
public static ArrayList<String> findInString(String needle, List<String> haystack) {
ArrayList<String> found = new ArrayList<String>();
for(String s : haystack) {
if(s.contains(needle)) {
found.add(s);
}
}
return found;
}
(to search char, just do myChar+"" and you have string)
To add the find'n'replace functionality should now be fairly easy for you.
Here's a variant for searching String[]:
public static ArrayList<String[]> findInString(String needle, List<String[]> haystack) {
ArrayList<String[]> found = new ArrayList<String[]>();
for(String fileLines[] : haystack) {
for(String s : fileLines) {
if(s.contains(needle)) {
found.add(fileLines);
break;
}
}
}
return found;
}
You don't need to iterate over lines twice to do what you need. You can make replacement when iterating over file.
Java 8 solution
try (BufferedReader reader = Files.newBufferedReader(Paths.get("pom.xml"))) {
reader
.lines()
.filter(x -> x.length() > 0)
.map(x -> x.trim())
.map(x -> x.replace("a", "b"))
.forEach(System.out::println);
} catch (IOException e){
//handle exception
}
Another way by using iterator
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Naman");
list.add("Aman");
list.add("Nikhil");
list.add("Adarsh");
list.add("Shiva");
list.add("Namit");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.startsWith("Na")) {
System.out.println(next);
}
}
}

Categories