Why am I getting the duplicates more than once? If I have 3 "3s" I get [3,3,3] instead of just [3] - arraylist

package week8;
import java.util.*;
public class ArrayListDup {
//create dumps function
public static List<String> dups(List<String> list) {
List<String> result = new ArrayList<String>();
for(int i = 0;i < list.size();i++) {
for(int j = i + 1;j<list.size();j++) {
if(list.get(i).equals(list.get(j))) {
result.add(list.get(j));
}

Related

How to get sum of a item inside recyclerview?

Suppose two Items 8 and 4 are there in the list. So the Sum I should get is 12. But I am getting result as 84 and not 12. I am a beginner So I don't have an idea what wrong I am doing here.
private void getCreditEntries() {
final String shift = kvName.getText().toString();
final String leaveType = selectLeaveType.getSelectedItem().toString();
final String employeeCode = empCode.getText().toString();
final String calendarYear = selectYear.getText().toString();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("LeaveDetails").child(shift)
.child("Credit").child(employeeCode).child(calendarYear);
DatabaseReference dbRef = reference.child(leaveType);
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<>();
if (!dataSnapshot.exists()) {
creditEntryLayout.setVisibility(View.GONE);
} else {
creditEntryLayout.setVisibility(View.VISIBLE);
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
LeaveCreditData data = snapshot.getValue(LeaveCreditData.class);
list.add(data);
}
rvCreditEntry.setHasFixedSize(true);
rvCreditEntry.setLayoutManager(new LinearLayoutManager(LeaveDetails.this));
rvCreditEntry.setItemAnimator(new DefaultItemAnimator());
leaveCreditAdapter = new LeaveCreditAdapter(list, LeaveDetails.this);
rvCreditEntry.setAdapter(leaveCreditAdapter);
int total = 0;
for(int i = 0; i < list.size(); i++){
total = Integer.parseInt(total + list.get(i).getTotalLeaveCredit());
creditSum.setText(String.valueOf( total));
//Suppose two Items 8 and 4 are there in the list
// So the Sum I should get is 12.
// But I am getting result as 84 and not 12
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(LeaveDetails.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
I simply edited the code as below and achieved what I wanted.
int total = 0;
for(int i = 0; i < list.size(); i++){
total += Integer.parseInt(list.get(i).getTotalLeaveCredit());
creditSum.setText(String.valueOf( total));
}

Comparing to array list through there given index but its returning null exception at file initialization

package adc;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
class Result {
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
public static int sockMerchant(int n, List<Integer> ar) {
// Write your code here
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<=n;j++){
if(ar.get(i)==ar.get(j)){
count++;
}
}
}
return(count);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); ' BufferedWriter(newFileWriter(System.getenv("F:\\")));'
int n = Integer.parseInt(bufferedReader.readLine().trim());
String[] arTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> ar = new ArrayList<>();
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arTemp[i]);
ar.add(arItem);
}
int result = Result.sockMerchant(n, ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Working of code
here inputs are n("number of integer arraylist have")=9
and ar input of arraylist [10, 20, 20, 10, 10, 30, 50, 10, 20]
** In this ar arraylist we have to find the even pair of number and return the number of pair .**
In this example the output is 3.

Find the largest String in the list

I am required to find the largest string in the ArrayList, and the print it. My code is not currently working though.
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
strings = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
String n = reader.readLine();
strings.add(n);
}
String largestString = strings.get(0);
for (int i = 0; i < strings.size(); i++) {
if (strings.get(i).length() > largestString.length()) {
largestString = strings.get(i);
System.out.println(largestString);
}
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String value = null;
int length = 0;
for (int i = 0; i < 5; i++) {
String n = reader.nextLine();
if (n != null && n.length() > length) {
length = n.length();
value = n;
}
}
System.out.println("Largest String : " + value + " of length : " + length);
}

error is occuring while creating custom tokenizer in lucene 7.3

I m trying to create new tokenizer by refering book tamingtext (which uses lucene 3.+ api) using new lucene api 7.3, but it is giving me error as mentioned below
java.lang.IllegalStateException: TokenStream contract violation: reset()/close() call missing, reset() called multiple times, or subclass does not call super.reset(). Please see Javadocs of TokenStream class for more information about the correct consuming workflow.
at org.apache.lucene.analysis.Tokenizer$1.read(Tokenizer.java:109)
at java.io.Reader.read(Reader.java:140)
at solr.SentenceTokenizer.fillSentences(SentenceTokenizer.java:43)
at solr.SentenceTokenizer.incrementToken(SentenceTokenizer.java:55)
at solr.NameFilter.fillSpans(NameFilter.java:56)
at solr.NameFilter.incrementToken(NameFilter.java:88)
at spec.solr.NameFilterTest.testNameFilter(NameFilterTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Here is my SentenceTokenizer class
Initializing method, in older api there was super(Reader); but in current api there is no access to Reader class
public SentenceTokenizer(SentenceDetector detector) {
super();
setReader(reader);
this.sentenceDetector = detector;
}
Here is my reset method
#Override
public void reset() throws IOException {
super.reset();
sentenceDetector = null;
}
When i tried to access this method from custom TokenFilter, I m getting above error
public void fillSentences() throws IOException {
char[] c = new char[256];
int size = 0;
StringBuilder stringBuilder = new StringBuilder();
while ((size = input.read(c)) >= 0) {
stringBuilder.append(c, 0, size);
}
String temp = stringBuilder.toString();
inputSentence = temp.toCharArray();
sentenceSpans = sentenceDetector.sentPosDetect(temp);
tokenOffset = 0;
}
#Override
public final boolean incrementToken() throws IOException {
if (sentenceSpans == null) {
//invoking following method
fillSentences();
}
if (tokenOffset == sentenceSpans.length) {
return false;
}
Span sentenceSpan = sentenceSpans[tokenOffset];
clearAttributes();
int start = sentenceSpan.getStart();
int end = sentenceSpan.getEnd();
charTermAttribute.copyBuffer(inputSentence, start, end - start);
positionIncrementAttribute.setPositionIncrement(1);
offsetAttribute.setOffset(start, end);
tokenOffset++;
return true;
}
Here is my custom TokenFilter class
public final class NameFilter extends TokenFilter {
public static final String NE_PREFIX = "NE_";
private final Tokenizer tokenizer;
private final String[] tokenTypeNames;
private final NameFinderME[] nameFinderME;
private final KeywordAttribute keywordAttribute = addAttribute(KeywordAttribute.class);
private final PositionIncrementAttribute positionIncrementAttribute = addAttribute(PositionIncrementAttribute.class);
private final CharTermAttribute charTermAttribute = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
private String text;
private int baseOffset;
private Span[] spans;
private String[] tokens;
private Span[][] foundNames;
private boolean[][] tokenTypes;
private int spanOffsets = 0;
private final Queue<AttributeSource.State> tokenQueue =
new LinkedList<>();
public NameFilter(TokenStream in, String[] modelNames, NameFinderME[] nameFinderME) {
super(in);
this.tokenizer = SimpleTokenizer.INSTANCE;
this.nameFinderME = nameFinderME;
this.tokenTypeNames = new String[modelNames.length];
for (int i = 0; i < modelNames.length; i++) {
this.tokenTypeNames[i] = NE_PREFIX + modelNames[i];
}
}
//consumes tokens from the upstream tokenizer and buffer them in a
//StringBuilder whose contents will be passed to opennlp
protected boolean fillSpans() throws IOException {
if (!this.input.incrementToken()) return false;
//process the next sentence from the upstream tokenizer
this.text = input.getAttribute(CharTermAttribute.class).toString();
this.baseOffset = this.input.getAttribute(OffsetAttribute.class).startOffset();
this.spans = this.tokenizer.tokenizePos(text);
this.tokens = Span.spansToStrings(spans, text);
this.foundNames = new Span[this.nameFinderME.length][];
for (int i = 0; i < nameFinderME.length; i++) {
this.foundNames[i] = nameFinderME[i].find(tokens);
}
//insize
this.tokenTypes = new boolean[this.tokens.length][this.nameFinderME.length];
for (int i = 0; i < nameFinderME.length; i++) {
Span[] spans = foundNames[i];
for (int j = 0; j < spans.length; j++) {
int start = spans[j].getStart();
int end = spans[j].getEnd();
for (int k = start; k < end; k++) {
this.tokenTypes[k][i] = true;
}
}
}
spanOffsets = 0;
return true;
}
#Override
public boolean incrementToken() throws IOException {
//if there's nothing in the queue
if(tokenQueue.peek()==null){
//no span or spans consumed
if (spans==null||spanOffsets>=spans.length){
if (!fillSpans())return false;
}
if (spanOffsets>=spans.length)return false;
//copy the token and any types
clearAttributes();
keywordAttribute.setKeyword(false);
positionIncrementAttribute.setPositionIncrement(1);
int startOffset = baseOffset +spans[spanOffsets].getStart();
int endOffset = baseOffset+spans[spanOffsets].getEnd();
offsetAttribute.setOffset(startOffset,endOffset);
charTermAttribute.setEmpty()
.append(tokens[spanOffsets]);
//determine of the current token is of a named entity type, if so
//push the current state into the queue and add a token reflecting
// any matching entity types.
boolean [] types = tokenTypes[spanOffsets];
for (int i = 0; i < nameFinderME.length; i++) {
if (types[i]){
keywordAttribute.setKeyword(true);
positionIncrementAttribute.setPositionIncrement(0);
tokenQueue.add(captureState());
positionIncrementAttribute.setPositionIncrement(1);
charTermAttribute.setEmpty().append(tokenTypeNames[i]);
}
}
}
spanOffsets++;
return true;
}
#Override
public void close() throws IOException {
super.close();
reset();
}
#Override
public void reset() throws IOException {
super.reset();
this.spanOffsets = 0;
this.spans = null;
}
#Override
public void end() throws IOException {
super.end();
reset();
}
}
here is my test case for following class
#Test
public void testNameFilter() throws IOException {
Reader in = new StringReader(input);
Tokenizer tokenizer = new SentenceTokenizer( detector);
tokenizer.reset();
NameFilter nameFilter = new NameFilter(tokenizer, modelName, nameFinderMES);
nameFilter.reset();
CharTermAttribute charTermAttribute;
PositionIncrementAttribute positionIncrementAttribute;
OffsetAttribute offsetAttribute;
int pass = 0;
while (pass < 2) {
int pos = 0;
int lastStart = 0;
int lastEnd = 0;
//error occur on below invoke
while (nameFilter.incrementToken()) {
}
}
I have added following changes in my code and it work fine but i m now sure it is correct answer
public SentenceTokenizer(Reader reader,SentenceDetector sentenceDetector) {
super();
this.input =reader;
this.sentenceDetector = sentenceDetector;
}

Iterate on a range of iterable

I have interface that returns a iterable object.
I need to iterate on the first 1000 items of it.
What is the best way to combine iterating using Iterator and stop after a certain count is reached.
Thanks
I'd use a loop that iterates and have a counter variable incremented; then break out of the loop when the counter reaches 1000.
What is your language?
C#:
using System.Linq;
//...
foreach (var item in iface.GetIterable().Take(1000))
{
//...
}
Python:
import itertools
#...
for item in itertools.islice(iface.get_iterable(), 1000):
#...
Make a standard loop that iterates over your collection, but check to see if the index has progress past the target index.
You may want to extract a seperate counter from the main loop index for your specific application.
int stopIndex = 1000;
for (int index = 0; index <= theInterface.Count; index++)
{
// check to see if we're at/past the stopIndex
if (index >= stopIndex)
break;
// we're still within the conditions, so do something with your interface
myObjectType localObject = (MyObjectType)theInterface.IndexOf(index);
}
Here's a test-driven (Java) wrapper around any existing iterator that should do the trick.
package com.playground;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
public class LimitedIterableTest extends TestCase {
private static class LimitedIterator<T> implements Iterator<T> {
private final Iterator<T> original;
private final int limit;
private int index = 0;
public LimitedIterator(Iterator<T> iterator, int limit) {
this.original = iterator;
this.limit = limit;
}
public boolean hasNext() {
return index < limit && original.hasNext();
}
public T next() {
index++;
return original.next();
}
public void remove() {
original.remove();
}
}
private static class LimitedIterable<T> implements Iterable<T> {
private final int limit;
private final Iterable<T> original;
public LimitedIterable(Iterable<T> iterable, int limit) {
this.original = iterable;
this.limit = limit;
}
public Iterator<T> iterator() {
return new LimitedIterator<T>(original.iterator(), limit);
}
}
final Integer[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
final List<Integer> list = Arrays.asList(array);
public void testCount() throws Exception {
assertEquals(10, count(list));
}
public void testLimitedIterable() throws Exception {
Iterable<Integer> limited = new LimitedIterable<Integer>(list, 5);
assertEquals(5, count(limited));
limited = new LimitedIterable<Integer>(list, 50);
assertEquals(10, count(limited));
}
private static <T> int count(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
return count(iterator);
}
private static <T> int count(Iterator<T> iterator) {
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
}