To check List of String within a String - java

I have a List<String> and List<Object>. Where, in List<String> I have Strings that I want. In another List<Object>, One of the string variable will have all the Strings that I want. How can I get that String or How can I return true when I found all the listOne Strings.
Example:
List<String> listOne = ["I have"," three"," Dollars"]
List<Object> listTwo = [[1,"I have One Dollar", 500],
[2,"I have two Dollars", 541],
[31,"I have three Dollars with card", 568]
[3,"I have three Dollars", 568],
[4,"I have Four Dollars", 521]]
How I can get Fourth object from listTwo when my listOne Strings exactly matched.
Code Part:
Details.java:
public class Details {
int sNo;
String text;
int value;
public int getsNo() {
return sNo;
}
public void setsNo(int sNo) {
this.sNo = sNo;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Main Class:
package com.adp.aca.core.helper.daoimpl;
import java.util.ArrayList;
import java.util.List;
import org.apache.velocity.runtime.directive.Foreach;
public class TestClass {
static int count ;
public static void main(String args[]) {
List<String> listOne = new ArrayList<String>();
listOne.add("I have");
listOne.add(" three");
listOne.add(" Dollars");
List<Details> listTwo = new ArrayList<Details>();
Details detailOne = new Details();
detailOne.setsNo(1);
detailOne.setText("I have One Dollar");
detailOne.setValue(500);
Details detailTwo = new Details();
detailTwo.setsNo(2);
detailTwo.setText("I have two Dollars");
detailTwo.setValue(541);
Details detailThree = new Details();
detailThree.setsNo(31);
detailThree.setText("I have three Dollars with card");
detailThree.setValue(568);
Details detailFour = new Details();
detailFour.setsNo(3);
detailFour.setText("I have three Dollars");
detailFour.setValue(568);
Details detailFive = new Details();
detailFive.setsNo(4);
detailFive.setText("I have Four Dollars");
detailFive.setValue(521);
listTwo.add(detailOne);
listTwo.add(detailThree);
listTwo.add(detailFour);
listTwo.add(detailFive);
listTwo.add(detailTwo);
List<String> actualStrings = new ArrayList<String>();
for (Details detail : listTwo) {
actualStrings.add(detail.getText());
}
/** Ended up here ***/
for (int i = 0; i < actualStrings.size(); i++) {
for (int j=0; j<listOne.size();j++) {
actualStrings.get(i).contains(listOne.get(j));
count=i;
}
}
}
}

static String concat(List<String> l) {
StringBuilder sb = new StringBuilder();
for(String s : l)
sb.append(s);
return sb.toString();
}
static Details getMatch(List<Details> listTwo, String s) {
for (Details d : listTwo) {
if (d.getText().equals(s))
return d;
}
return null;
}
You can use the functions like this:
Detail d = getMatch(listTwo, concat(listOne));

you can build a String from List one and compare with Object list in a loop or you can iterate through 2 list and compare as shown in the pseudo code.
for (Details detail: listTwo) {
String text = detail.getText();
String[] texts = text.split(" ");
List textList = Arrays.asList(texts);
if (texts.length == listOne.size()) {
int count = 0;
for (String val: listOne) {
if (textList.contains(val) count++;
else break;
}
if (count == listOne.size()) {
result = detail;
}
}
else {
break;
}
}

Related

Comparing words

I have problem with my code. I wrote program for count words in text, but I have small problem with patterns which must be search in text. Maybe somebody can help me.
import java.util.*;
class KomparatorLicz implements Comparator<Word> {
#Override
public int compare(Word arg0, Word arg1) {
return arg1.amount - arg0.amount;
}
}
class KomparatorString implements Comparator<Word> {
#Override
public int compare(Word obj1, Word obj2) {
if (obj1.content == obj2.content) {
return 0;
}
if (obj1.content == null) {
return -1;
}
if (obj2.content == null) {
return 1;
}
return obj1.content.compareTo(obj2.content);
}
}
class Word
{
public String content;
public int amount;
public Word(String content, int amount) {
this.content = content;
this.amount = amount;
}
#Override
public String toString() {
return "Word [content=" + content + ", amount=" + amount + "]";
}
}
public class Source4 {
public static float procent(int wordCount, int oneWord)
{
return (((float)oneWord*100)/(float)wordCount);
}
public static void main(String[] args) {
String line, wordsLine[];
String klucze = null;
int valTemp;
int wordCount=0;
int keyWords=0;
HashMap<String, Word> slownik = new HashMap<String, Word>();
ArrayList<Word> lista= new ArrayList<Word>();
ArrayList<Object> keyWordsList = new ArrayList<Object>();
Scanner in = new Scanner(System.in);
String alph = in.nextLine();
keyWords = in.nextInt();
for(int i=0; i<keyWords; i++)
{
klucze = in.next();
keyWordsList.add(klucze);
}
while(in.hasNextLine())
{
line = in.nextLine();
if(line.equals("koniec")) break;
wordsLine = line.split("[^" + alph + "]");
for(String s : wordsLine) {
if(s != null && s.length() > 0)
{
wordCount++;
if(slownik.containsKey(s))
{
valTemp = slownik.get(s).amount;
slownik.remove(s);
valTemp++;
slownik.put(s, new Word(s,valTemp));
}
else
{
slownik.put(s, new Word(s,1));
}
}
}
}
for (String key : slownik.keySet())
{
lista.add(slownik.get(key));
}
Collections.sort(lista, new KomparatorString());
StringBuffer result = new StringBuffer();
int keyWordCounter=0;
int amountBuff=0;
float percentBuff=0;
for (int i = 0; i<lista.size();i++)
{
if(keyWordsList.contains(lista.get(i)))
{
result.append(amountBuff+" "+percentBuff+"%");
amountBuff = 0;
percentBuff = 0;
result.append("\n");
result.append(lista.get(i).amount+" "+(procent(wordCount,lista.get(i).amount)+"%"));
result.append(" "+lista.get(i).content);
result.append("\n");
keyWordCounter+=lista.get(i).amount;
}
else
{
amountBuff+=lista.get(i).amount;
percentBuff+=procent(wordCount,lista.get(i).amount);
}
}
result.append(amountBuff+" "+percentBuff+"%");
System.out.println("Wersja AK");
System.out.println(keyWords+" różnych słów kluczowych");
System.out.println(wordCount+" wystąpień wszystkich słów");
System.out.println(keyWordCounter+" "+procent(wordCount,keyWordCounter)+"% "+" wystąpień słów kluczowych");
System.out.println((wordCount-keyWordCounter)+" "+procent(wordCount,(wordCount-keyWordCounter))+"% wystąpień innych słów");
System.out.println(result);
}
}
It's wrong code if(keyWordsList.contains(lista.get(i))).
You need if(keyWordsList.contains(lista.get(i).content)).

sort two columns in a text file by using java collections framework

I have an input file containing lines like
21,mahesh
12,suresh
23,rajesh
25,lokesh
By using ArrayList I wrote code the code below to handle ascending and descending order
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class FileRead {
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(new FileReader("D:\\Numbers.txt"));
ArrayList<String> al = new ArrayList<String>();
while (s.hasNextLine()) {
String line = s.nextLine();
al.add(line);
}
Collections.sort(al,Collections.reverseOrder());
for (String i: al)
System.out.println(i);
}
}
This yielded the following output
- 25,lokesh
- 23,rajesh
- 21,mahesh
- 12,suresh
$ In the above code, when I take the entire row as a line by using Collections.sort() operation it works.
$ If I take the input like below String column first and integer column next the above code is not working properly it will assign by using String values Alphabetical order,i want to sort the data by using only integer not by String values please help me friends
- mahesh,21
- suresh,12
- rajesh,23
- lokesh,25
First Read the file store it in a Map
Map map = new TreeMap();
while(true)
{
String line = bufferedReader.readLine();
if(line == null)
break;
else {
String arr[] = line.split(",");
for(int i=0;i<arr.length-1;i++)
{
map.put(arr[i],arr[i+1]);
}}
}
Sort it using Comparator
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
Finally displat the result
Map result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());
For acending switch o1 and o2 in when returning from comparator.
For the second type of input
List list = new LinkedList(map.keySet());
Collections.sort(list);
Set set = map.entrySet();
Map result = new LinkedHashMap();
for (Iterator it = set.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());
The following will allow you to parse the information into the appropriate types using a class LineEntry to wrap the data. It will provide the proper sorting on Integer values instead of treating them as Strings and applying alphabetical ordering.
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class FileRead {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(new InputStreamReader(FileRead.class.getResourceAsStream("/numbers.txt")));
s.useDelimiter("[,\\s]");
ArrayList<LineEntry> lineEntryList = new ArrayList<LineEntry>();
while (s.hasNextLine()) {
int amount = s.nextInt();
String value = s.next();
LineEntry lineEntry = new LineEntry(value, amount);
lineEntryList.add(lineEntry);
}
Collections.sort(lineEntryList, Collections.reverseOrder());
for (LineEntry i : lineEntryList) {
System.out.println(i);
}
}
public static class LineEntry implements Comparable<LineEntry>{
private String value;
private Integer amount;
public LineEntry(String value, Integer amount) {
this.value = value;
this.amount = amount;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
#Override
public String toString() {
return "LineEntry{" + "value=" + value + ", amount=" + amount + '}';
}
#Override
public int compareTo(LineEntry o) {
int compareTo = o.getAmount().compareTo(amount);
if (compareTo == 0) {
compareTo = o.getValue().compareTo(value);
}
return compareTo;
}
}
Better to create a different class which contains data in each line seperated by comma as variables of that class so that in future if you have multiple columns data in the same line then the code can be scalable and also you can create custom comparators based on your sort condition:-
public class FileRead {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(new FileReader("E:\\Numbers.txt"));
List<FileObject> al = new ArrayList<FileObject>();
while (s.hasNextLine()) {
String line = s.nextLine();
al.add(new FileObject().createFileObject(line));
}
Collections.sort(al,new FileObjectComparator());
for (FileObject i: al)
System.out.println(i);
}
}
class FileObject {
private int id;
private String name;
public FileObject createFileObject(String line) {
if(line != null && !line.isEmpty()) {
for(String str : line.split(",")) {
str = str.trim();
if(str.matches("([\\d]*)")) {
id = Integer.valueOf(str);
} else {
name = str;
}
}
}
return this;
}
... // getters and setters
#Override
public String toString() {
return "[ID] "+id+ " [Name] "+name ;
}
}
class FileObjectComparator implements Comparator<FileObject> {
#Override
public int compare(FileObject o1, FileObject o2) {
return o2.getId() - o1.getId();
}
}

Convert Linkedlist to ArrayList

I had to write a program to do LZWDecode and I decided to use LinkedList to write the LZWDecode program below but I want to convert it to an ArrayList. Anyone have idea on how I can convert the LinkedList to an ArrayList to make it simpler.
Thanks.
import java.util.*;
public class LZWDecoder {
private final int CLEAR_TABLE=256;
private final int END_OF_DATA=257;
private final int TABLE_SIZE=4096;
private static LinkedList<Integer> input = new LinkedList<Integer>();
#SuppressWarnings("unchecked")
private LinkedList<Integer>[] table
= new LinkedList[TABLE_SIZE];
private LinkedList<Integer> temp = new LinkedList<Integer>();
private int index = 258;
private LinkedList<String> trace = new LinkedList<String>();
private boolean view = true;
private void enterData() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Input Code (EOD = 257):");
int n=0;
while(n!=END_OF_DATA && scan.hasNextInt()){
n = scan.nextInt();
//System.out.println("Adding "+n);
input.add(n);
}
System.out.println("Decoding...\nOutput:");
String code="";
for(int i=0; i<input.size(); i++) {
code+=input.get(i)+" ";
}
trace.add("\nInput: "+code);
//test
/*
while(!input.isEmpty()) {
System.out.println(input.remove());
}
*/
}
private void reset() {
trace.add("Clearing...");
//table.clear();
for(int i=0; i<TABLE_SIZE;i++) {
table[i] = new LinkedList<Integer>();
}
}
private void decode(int c) {
switch(c) {
case CLEAR_TABLE:
trace.add("decode\t"+CLEAR_TABLE+"->[256]");
reset();
break;
case END_OF_DATA:
trace.add("decode\t"+END_OF_DATA+"->[257]");
trace.add("Decoding finished.");
break;
default:
if(c<256) {
trace.add("decode\t"+c+"->["+c+"]");
if(!temp.isEmpty()) append(c);
emit(c);
add(temp);
} else {
trace.add("decode\t"+c+"->["+printTableNode(table[c])+"]");
if(!temp.isEmpty()) append(table[c].get(0));
emit(c, table[c]);
add(temp);
}
}
}
private void emit(int n, LinkedList<Integer> c) {
//int [] a=new int[c.size()];
temp=new LinkedList<Integer>();
for(int i=0; i<c.size(); i++) {
//a[i]=c.get(i);
System.out.print(c.get(i)+" ");
temp.add(c.get(i));
}
trace.add("emit\t"+n+"->"+"["+printTableNode(c)+"]");
}
private void emit(int c) {
//print out output
temp=new LinkedList<Integer>();
temp.add(c);
trace.add("emit\t"+c+"->"+"["+c+"]");
System.out.print(c+" ");
}
/*
private void add(int c) {
//added to table is copied to temp
table[index].add(c);
temp = (LinkedList)table[index].clone();
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
*/
private void add(LinkedList<Integer> c) {
for(int i=0; i<c.size();i++) {
//temp.add(c.get(i));
table[index].add(c.get(i));
}
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
private void append(int c) {
//table[c].add(12);//add what?
//temp.add(c);
table[index].add(c);
trace.add("append\t"+index+"->["+printTableNode(table[index])+"]");
index++;
}
private String printTableNode(LinkedList l) {
String list="";
for(int i=0; i<l.size();i++) {
list+=l.get(i);
if(i<l.size()-1) {
list+=", ";
}
}
return list;
}
private void printTrace() {
System.out.print("Printing Trace...");
for(int i=0; i<trace.size(); i++) {
System.out.println(trace.get(i));
}
}
public static void main(String[] args) {
// TODO code application logic here
LZWDecoder d = new LZWDecoder();
d.enterData();
while(!input.isEmpty()) {
d.decode(input.remove());
}
System.out.print("\n\n");
d.printTrace();
}
}
LinkedList<String> ll= new LinkedList<String>();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
List<String> myAL = new ArrayList<String>(ll);
for (Object alObject : myAL)
System.out.println(alObject);
So as you can easily convert the LinkedList to ArrayList bu using its constructor with passing Collection in it.
Hope it will clear your doubt.
Question is not clear enough.
Do you want to use ArrayList instead of Linked List?
Or do you want to convert a Linked List to an ArrayList?
First of all please declare variables on their interface not on implementation,
i.e
LinkedList<Integer>[] table = new LinkedList[TABLE_SIZE];
Instead use
List<Integer>[] table = new LinkedList[TABLE_SIZE];
Please provide a little more details on what you really looking for ....
If you want an array List from another collection, do this,
List<T> t = new ArrayList<>();
t.addAll(linkedList);
Regards
Lyju

Stable Marriage algorithm java code

I need to implement makeMatches method in stable marriage class.
Code needs to follow this algorithm:
set each person to be free;
while (some man m with a nonempty preference list is free) {
w = first woman on m's list;
if (some man p is engaged to w) {
set p to be free
}
set m and w to be engaged to each other
for (each successor q of m on w's list) {
delete w from q's preference list
delete q from w's preference list
}
}
However I can not find my error. The program makes couples depend on their first choices but after that doesn't continue and set couples.
Could you look at my code and tell me what is wrong with it?
Person.java is provided from instructor:
import java.util.*;
public class Person {
public static final int NOBODY = -1;
private String name;
private List<Integer> preferences;
private List<Integer> oldPreferences;
private int partner;
public Person(String name) {
this.name = name;
preferences = new ArrayList<Integer>();
oldPreferences = new ArrayList<Integer>();
erasePartner();
}
public void erasePartner() {
partner = NOBODY;
}
public boolean hasPartner() {
return partner != NOBODY;
}
public int getPartner() {
return partner;
}
public void setPartner(int partner) {
this.partner = partner;
}
public String getName() {
return name;
}
public boolean hasChoices() {
return !preferences.isEmpty();
}
public int getFirstChoice() {
return preferences.get(0);
}
public void addChoice(int person) {
preferences.add(person);
oldPreferences.add(person);
}
public List<Integer> getChoices() {
return preferences;
}
public int getPartnerRank() {
return oldPreferences.indexOf(partner) + 1;
}
}
And StablaMarriage.java is the one I need to implement code in.
import java.io.*;
import java.util.*;
public class StableMarriage {
public static final String LIST_END = "END";
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("What is the input file? ");
String fileName = console.nextLine();
Scanner input = new Scanner(new File(fileName));
System.out.println();
List<Person> men = readHalf(input);
List<Person> women = readHalf(input);
makeMatches(men, women);
writeList(men, women, "Matches for men");
writeList(women, men, "Matches for women");
}
public static Person readPerson(String line) {
int index = line.indexOf(":");
Person result = new Person(line.substring(0, index));
Scanner data = new Scanner(line.substring(index + 1));
while (data.hasNextInt()) {
result.addChoice(data.nextInt());
}
return result;
}
public static List<Person> readHalf(Scanner input) {
List<Person> result = new ArrayList<Person>();
String line = input.nextLine();
while (!line.equals(LIST_END)) {
result.add(readPerson(line));
line = input.nextLine();
}
return result;
}
public static void makeMatches(List<Person> list1, List<Person> list2) {
for (Person eachMan : list1){
eachMan.setPartner(-1);
}
for (Person eachWoman : list2){
eachWoman.setPartner(-1);
}
for (Person man : list1){
for (Person woman : list2){
while (man.hasChoices() && !man.hasPartner()){
int choosenWoman = man.getFirstChoice();
for (Person p : list1){
if (p.getPartner()== choosenWoman){
p.setPartner(-1);
}
}
man.setPartner(choosenWoman);
list2.get(choosenWoman).setPartner(list1.indexOf(man));
List manList= man.getChoices();
List womanList = woman.getChoices();
for (int q= womanList.size()-1; q>=0; q--){
if(q>womanList.indexOf(list1.indexOf(man)))
manList.remove(manList.indexOf(man.getFirstChoice()));
womanList.remove(q);
}
}
}
}
}
public static void writeList(List<Person> list1, List<Person> list2,
String title) {
System.out.println(title);
System.out.println("Name Choice Partner");
System.out.println("--------------------------------------");
int sum = 0;
int count = 0;
for (Person p : list1) {
System.out.printf("%-15s", p.getName());
if (!p.hasPartner()) {
System.out.println(" -- nobody");
} else {
int rank = p.getPartnerRank();
sum += rank;
count++;
System.out.printf("%4d %s\n", rank,
list2.get(p.getPartner()).getName());
}
}
System.out.println("Mean choice = " + (double) sum / count);
System.out.println();
}
}

confused about Return Value

I'm working on a project called MovieDatabase. For my methods searchTitle, searchGenre, searchDirector, and searchYear, the methods are supposed to take a substring and see if they can be found anywhere in the database. What I have now compiles but when I test the methods from the BlueJ project they return only null. What do I change to make them return the right things? Here is my code in its entirety (P.S. there's a separate class called MovieEntry that handles the get methods):
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<String> searchTitle(String substring){
for (MovieEntry m : Database)
if(m.getTitle().contains(substring)){
System.out.println(m.getTitle());
}
return null;
}
public ArrayList<String> searchGenre(String substring){
for (MovieEntry m : Database)
if(m.getGenre().contains(substring)){
System.out.println(m.getGenre());
}
return null;
}
public ArrayList<String> searchDirector (String substring){
for (MovieEntry m : Database)
if(m.getDirector().contains(substring)){
System.out.println(m.getDirector());
}
return null;
}
public ArrayList<MovieEntry> searchYear(int year){
ArrayList<MovieEntry> yearMatches = new ArrayList<MovieEntry>();
for (MovieEntry m : Database) {
if (m.getYear() == year) {
yearMatches.add(m);
}
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <MovieEntry> Matches = new ArrayList<MovieEntry>();
for(MovieEntry m : Database){
if(m.getYear() >= from && m.getYear() <= to){
Matches.add(m);
}
}
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File("movies"));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
ArrayList <String> gList = new ArrayList<String>();
for(MovieEntry m : Database){
String g = m.getGenre();
if(gList.contains(g) == false){
gList.add(g);
}
}
return gList.size();
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector();
if(dList.contains(d) == false){
dList.add(d);
}
}
return dList.size();
}
// public String listGenres(){
// ArrayList <String> genreList = new ArrayList<String>();
// return genreList;
// }
}
You must modify methods of the following nature
public ArrayList<String> search*(String substring){
Remove System.out.println. Instead, add match to a new array list of strings.
public ArrayList<String> searchTitle(String substring){
ArrayList<String> matches = new ArrayList<String>();
for (MovieEntry m : Database)
if(m.getTitle().contains(substring)){
matches.add(m.getTitle());
}
return matches;
}
Wherever you are calling the searchTitle(), check resulting arraylist for isEmpty() to make sure that the result is not empty.

Categories

Resources