This is a pice of my code :
ArrayList<String> Alist= new ArrayList<String>();
ArrayList<String> Blist= new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
so i have two array list i want to compare all items and check if they are not equal and if they are to print out only the items that are not equal.
so i make something like this:
http://postimage.org/image/adxix2i13/
sorry for the image but i have somekind of bug when i post here a for looop.
and the result is :
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
i want to print only the 2 that are not equal in the example they are gsm and pc
not equals..:gsm
not equals..:pc
Don't use != to compare strings. Use the equals method :
if (! Blist.get(i).equals(Alist.get(j))
But this wouldn't probably fix your algorithmic problem (which isn't clear at all).
If what you want is know what items are the same at the same position, you could use a simple loop :
int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size());
for (int i=0; i<sizeOfTheShortestList; i++) {
if (Blist.get(i).equals(Alist.get(i))) {
System.out.println("Equals..: " + Blist.get(i));
}
}
If you want to get items that are in both lists, use
for (int i = 0; i < Alist.size(); i++) {
if (Blist.contains(Alist.get(i))) {
System.out.println("Equals..: " + Alist.get(i));
}
}
You can use the RemoveAll(Collection c) on one of the lists, if you happen to know if one list always contains them all.
You could use the following code:
ArrayList<String> Alist = new ArrayList<String>();
ArrayList<String> Blist = new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
for (String a : Alist)
{
for (String b : Blist)
{
if (a.equals(b))
{
System.out.println("Equals " + a);
break;
}
}
}
Output is:
Equals gsm
Equals pc
right now your comparing each element to all of the other ones. Do something like
for (int i = 0; i < Alist.size(); i++) {
if (!Alist.get(i).equals(Blist.get(i)) {
// print what you want
}
}
Thats of course assuming both lists have the same length.
Rather than writing code to manually compare list elements you might consider using Apache Commons Collections.
import org.apache.commons.collections.CollectionUtils;
List listA = ...;
List listB = ...;
Collection intersection = CollectionUtils.intersection(listA, listB);
import java.util.HashSet;
public class CheckSet<T> extends HashSet<T>{
#Override
public boolean add(T e) {
if (contains(e)) {
remove(e);
return true;
} else {
return super.add(e);
}
}
}
Add all elements of both of your lists to a CheckSet intance, and at the end it will only contain the ones not equal.
Here is one way:
public static boolean compare(List<String> first, List<String> second) {
if (first==null && second==null) return true;
if (first!=null && second==null) return false;
if (first==null && second!=null) return false;
if ( first.size()!=second.size() ) return false;
HashMap<String, String> map = new HashMap<String, String>();
for (String str : first) {
map.put(str, str);
}
for (String str : second) {
if ( ! map.containsKey(str) ) {
return false;
}
}
return true;
}
public static void main(String args[] ) throws Exception {
List<String> arrayList1 = new ArrayList<String>();
arrayList1.add("a");
arrayList1.add("b");
arrayList1.add("c");
arrayList1.add("d");
List<String> arrayList2 = new ArrayList<String>();
arrayList2.add("a");
arrayList2.add("b");
arrayList2.add("c");
arrayList2.add("d");
boolean isEqual = false;
if(arrayList1.size() == arrayList2.size()){
List<String> arrayListTemp = new ArrayList<String>();
arrayListTemp.addAll(arrayList1);
arrayListTemp.addAll(arrayList2);
HashSet<Object> hashSet = new HashSet<Object>();
hashSet.addAll(arrayListTemp);
if(hashSet.size() == arrayList1.size() &&
hashSet.size() == arrayList2.size()){
isEqual = true;
}
}
System.out.println(isEqual);
}
we can compare two different size arrayList in java or Android as follow.
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
array1.add("1");
array1.add("2");
array1.add("3");
array1.add("4");
array1.add("5");
array1.add("6");
array1.add("7");
array1.add("8");
array2.add("1");
array2.add("2");
array2.add("3");
array2.add("4");
for (int i = 0; i < array1.size(); i++) {
for (int j=0;j<array2.size();j++) {
if (array1.get(i) == array2.get(j)) {
//if match do the needful
} else {
// if not match
}
}
}
import java.util.Arrays;
public class ExampleContains {
public static boolean EligibleState(String state){
String[] cities = new String[]{"Washington", "London", "Paris", "NewYork"};
boolean test = Arrays.asList(cities).contains(state)?true:false;
return test;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(EligibleState("London"));
}
}
Related
I have the following which is of type ArrayList<List<String>>
Array_AcidExp[[Statistics (pH), Upright, Recumbent, Total], [Upright, Normal, Recumbent, Normal, Total, Normal], [Clearance pH : Channel 7], [Minimum, 4.69, , 2.42], [Maximum, 7.88, , 7.51, , 7.88], [Mean, 6.33, , 6.41, , 6.37], [Median, 6.62, , 6.40, , 6.49]]
I have tried the following without any luck:
for (int i = 0; i < Arr_AcidExp_pattern_table2d.size(); i++) {
Arr_AcidExp_pattern_table2d.removeAll(Collections.singleton(null));
Arr_AcidExp_pattern_table2d.get(i).removeAll(Collections.singleton(" "));
}
What should I do to get rid of the empty elements?
This will remove all internal nulls
for (List<String> internal : Array_AcidExp) {
if (internal != null) {
for (int i = 0; i < internal.size(); i++) {
if (internal.get(i) == null) {
internal.remove(i)
}
}
}
}
Did not run it ...
you can use removeIf() in java8 as well
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("yo");
list.add(null);
list.add(" ");
System.out.println(list);
list.removeIf(new Predicate<String>() {
#Override
public boolean test(String t) {
// removes all the elements from the list, for which the
// following condition returns true
return t == null || t.equals(" ");
}
});
System.out.println(list);
}
I'm making a program where it takes a list of elements in an arraylist and using recursion, gets the even and odd elements. For instance, if it were {1,2,3,4,5,6}. It would return {1,3,5} because they have an even element placement.
I figured out how to do it for even numbers without a hitch, but I can't seem to make it work for odds.
Here is the error:
java.lang.ArrayIndexOutofBoundsException:
-1 (in java.util.ArrayList)
Here is my even code:
public static ArrayList<Integer> even(ArrayList<Integer> tList)
{
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int temp = newList.size();
if (newList.size()<=0)// The list is empty or has one element)
{
return newList;// Return the list as is – no need to reverse!
}
else
{
if(newList.size()%2==0)
temp = newList.remove(newList.size()-2);
newList.remove(newList.size()-1);
newList = ListMethods.even(newList);
if (temp!=0)
newList.add(temp);
}
return newList;
}
Odd Code: (this is where I get the error)
public static ArrayList<Integer> odd(ArrayList<Integer> tList)
{
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int temp = newList.size();
if (newList.size()<=0)// The list is empty or has one element)
{
return newList;// Return the list as is – no need to reverse!
}
else
{
if(newList.size()%2==1)
temp = newList.remove(newList.size()-1);
newList.remove(newList.size()-1);
newList = ListMethods.odd(newList);
if (temp!=0)
newList.add(temp);
}
return newList;
}
Deep Clone:
public static ArrayList<Integer> deepClone(ArrayList<Integer> tList)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : tList)
{
list.add(new Integer(i));
}
return list;
}
My Tester Code:
import java.util.ArrayList;
import java.util.Scanner;
public class ListMethodsRunner
{
public static void main(String[] args)
{
ArrayList<Integer> tempList = ListMethods.makeList(100);
System.out.println("What would you like to do to this ArrayList? Type the number.");
System.out.println("1. Show Even Elements");
System.out.println("2. Show Odd Elements");
System.out.println(" ");
Scanner input = new Scanner(System.in);
int z = input.nextInt();
if(z==1)
tempList = ListMethods.even(tempList);
if(z==2)
tempList = ListMethods.odd(tempList);
if (tempList.size() == 0)
{
System.out.println("The list is empty");
}
else
{
for (Integer i : tempList)
{
System.out.println(i);
}
}
}
}
Nevermind guys, I figured it out by myself.
public static ArrayList<Integer> odd(ArrayList<Integer> tList)
{
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int temp = newList.size();
if (newList.size()<=0)// The list is empty or has one element)
{
return newList;// Return the list as is – no need to reverse!
}
else
{
if(newList.size()%2==0) // I had `1` here instead of `0`
temp = newList.remove(newList.size()-1);
newList.remove(newList.size()-1);
newList = ListMethods.odd(newList);
if (temp!=0)
newList.add(temp);
}
return newList;
I am not sure if the above code will work in case you have odd number of entries May be you can use something like below :
public static ArrayList<Integer> returnList(ArrayList<Integer> tList,boolean flag){
int size=tList.size();
int t;
//print odd positions - flag is true
if(flag){
if(size>0 && size%2==0){
t = tList.remove(size-1);
tList=returnList(tList,flag);
tList.add(t);
}
else if(size%2 == 1){
t = tList.remove(size-1);
tList=returnList(tList,flag);
}
else{
}
System.out.println("Printing.."+tList);
}
else{
}
return tList;
}
My code is:
public class Main{
public static void main(String[] args){
WordGroup wordgroupOne= new WordGroup ("You can discover more about a person in an hour of play than in a year of conversation");
WordGroup wordgroupTwo= new WordGroup ( "When you play play hard when you work dont play at all");
String[] quoteOne = wordgroupOne.getWordArray();
String[] quoteTwo = wordgroupTwo.getWordArray();
for (String words : quoteOne){
System.out.println(words);
}
for (String words : quoteTwo){
System.out.println(words);
}
}
}
WordGroup class:
import java.util.HashSet;
import java.util.HashMap;
public class WordGroup {
public String words;
public WordGroup (String getWords){
words = getWords.toLowerCase();
}
public String[] getWordArray(){
return words.split(" ");
}
public HashSet<String> getWordSet(){
HashSet<String> set = new HashSet<String>();
String[] p = getWordArray();
for (String items : p){
set.add(items);
}
System.out.println(set);
return set;
}
public HashMap<String, Integer> getWordCounts() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] q = getWordArray();
for (String stuff : q) {
Integer oldVal = map.get(stuff);
if (oldVal == null){
oldVal = 0;
}
map.put(stuff, oldVal+1);
}
System.out.println(map);
return map;
}
}
What I am trying to do is use the getWordSet() method using the two WordGroups and
iterate or loop over the HashSet returned and print the words from it.
Call getWordCounts() on the two WordGroups. Use keySet() to retrieve the set of keys. Loop over this set and print out the word and its count for both WordGroups.
Use the getWordSet() method to make complete set of all the words from both WordGroups.
Loop over the new HashSet to print a complete list of all words with the sum counts from each of the hashmaps.
I am struggling with all of these. Any help is much appreciated!!
If you want to create a combined list or set, you will have to merge the lists together and the maps together. I leave that exercise to you.
public static void main(String[] args)
{
WordGroup wg1 = new WordGroup(
"You can discover more about a person in an hour of play than in a year of conversation");
WordGroup wg2 = new WordGroup(
"When you play play hard when you work dont play at all");
wg1.processWord();
// iterate through all the distinct words
Set<String> dw1 = wg1.getDistinctWords();
for (String s : dw1)
{
System.out.println(s);
}
// use map entry to iterate through the entry set
Map<String, Integer> wc1 = wg1.getWordCounts();
for (Map.Entry<String, Integer> entry : wc1.entrySet())
{
if (entry != null)
{
// use stringbuilder to build a temp string
// instead of using +
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
System.out.println(sb);
}
}
}
public class WordGroup
{
// as a class, made the results of the process private
private String originalWord;
// we declare generic versions of the Collections, instead of the specific
// implementation
private Set<String> distinctWords;
private Map<String, Integer> wordCounts;
public WordGroup(String s)
{
this.originalWord = s;
// here we declare and initialize the specific implementation
this.distinctWords = new HashSet<String>();
this.wordCounts = new HashMap<String, Integer>();
}
public void processWord()
{
List<String> toProcess = getWordList();
if (toProcess != null && !toProcess.isEmpty())
{
for (String s : toProcess)
{
// the set will automatically figure out if it should be in the
// set or not.
this.distinctWords.add(s);
// call the update or insert method
upsertString(s);
}
}
}
// this splits the string into a list
// you could probably use a utility class from guava or something to do this
// but i have coded a naive version
private List<String> getWordList()
{
List<String> splitList = new ArrayList<String>();
// check to see if there is anything there
if (this.originalWord != null && !this.originalWord.isEmpty())
{
String lowered = this.originalWord.toLowerCase();
String[] splits = lowered.split(" ");
if (splits != null)
{
int iSize = splits.length;
if (iSize > 0)
{
// basically create a string
for (int i = 0; i < iSize; i++)
{
splitList.add(splits[i]);
}
}
}
}
return splitList;
}
// helper method to see if we need to add to the count
private void upsertString(String s)
{
if (s != null && !s.isEmpty())
{
if (this.wordCounts != null)
{
// default to 1, if its an insert
Integer newCount = 1;
// if it already exists we want to update
if (this.wordCounts.containsKey(s))
{
Integer currentCount = this.wordCounts.get(s);
if (currentCount != null)
{
// update the count by 1
newCount += currentCount;
}
}
// insert the new item
// or overwrite, because it is the same key to the new count
this.wordCounts.put(s, newCount);
}
}
}
public String getOriginalWord()
{
return this.originalWord;
}
public void setOriginalWord(String originalWord)
{
this.originalWord = originalWord;
}
public Set<String> getDistinctWords()
{
return this.distinctWords;
}
public void setDistinctWords(Set<String> distinctWords)
{
this.distinctWords = distinctWords;
}
public Map<String, Integer> getWordCounts()
{
return this.wordCounts;
}
public void setWordCounts(Map<String, Integer> wordCounts)
{
this.wordCounts = wordCounts;
}
}
I have array list like this
ArrayList list = new ArrayList();
list.add("somethingold");
list.add(3);
list.add("somethingnew");
list.add(5);
Now if I print the list output will be like:
[somethingold, 3, somethingnew, 5 ]
Here i want to fetch only integer elements.
I want the output like, if it is an integer put it in some other list, else in one more list.
This is what i want:
[3,5]
[somethingold, somethingnew]
have you tried this?:
if(list.get(0) instanceof Integer) {
// is an integer
} else if (list.get(0) instanceof String) {
// is a String
}
Looping through each element in List
for loop:
for (int i = 0; i < list.size(); i++) {
if (list.get(i) instanceof Integer) {
// do your stuff
}
if (list.get(i) instanceof String) {
// do your stuff
}
}
for-each loop:
for (Object obj: list) {
if (obj instanceof Integer) {
// do your stuff
}
...
}
You can achieve it using instanceof operator.
for (Object object : list)
{
if(object instanceof Integer)
{
System.out.println(object); // Integer
}
else if(object instanceof String)
{
System.out.println(object); // String
}
}
its very simple. Just two lines of code
string[] stringList = list.OfType<string>().ToArray();
Int32[] intList = list.OfType<Int32>().ToArray();
It is recommended that should create typed Collection like List<Integer> or List<String> if you are using java 1.5+.
In case of generic array you can use instanceOf operator to differentiate .
for(Object obj: list){
if(obj instanceOf Ineteger){
...
}else if(obj instanceOf String){
...
}
}
you are trying to go over the JDK API , that was one of the most important reason why Generics were introduced in java, to provide you type safe collections.
And you have no need to worry while adding or fetching the elements(no explicit typecasting required).
A friendly suggestion go by the book.
Thanks
You want [3,5] [somethingold, somethingnew] which looks already like 2 separate lists.
So you could do
class IntegersAndStrings {
private final List<String> strings = new ArrayList<String>();
private final List<Integer> ints = new ArrayList<Integer>();
public void add(int i) {
ints.add(Integer.valueOf(i));
}
public void add(String s) {
strings.add(s);
}
#Override
public String toString() {
return ints.toString() + strings.toString();
}
}
and use it like before
class Main {
public static void main(String[] args) {
IntegersAndStrings list = new IntegersAndStrings();
list.add("somethingold");
list.add(3);
list.add("somethingnew");
list.add(5);
System.out.println(list);
}
}
and the output would be
[3, 5][somethingold, somethingnew]
You have to fetch list of objects by using for-loop, in that you can find out string and integers.
Below example shows how to get the values..
ArrayList list = new ArrayList();
for (Object o : list) {
if (o.getClass().equals(Integer.TYPE)) {
...
}
else if (o.getClass().equals(String.class)) {
...
}
}
Collections.sort(list);
int index = 0;
for (Object obj: list) {
index ++;
if (obj instanceof String) {
break;
}
}
List<Integer> integerList = list.subList(0.index);
List<String> stringList = list.subList(index,list.size());
System.out.println(integerList);
System.out.println(stringList);
Try this, i hope it works
Using guava library you can do it like this:
System.out.println(
Iterators.toString(Iterators.filter(list.iterator(), String.class)));
System.out.println(
Iterators.toString(Iterators.filter(list.iterator(), Integer.class)));
I have 2 Strings:
A1=[Rettangolo, Quadrilatero, Rombo, Quadrato]
A2=[Rettangolo, Rettangolo, Rombo, Quadrato]
I want to obtain this: "I have found "Quadrilatero", instead of "Rettangolo" ".
If I use removeAll() or retainAll() it doesn't work because I have 2 instances of "Rettangolo".
In fact, if I use a1.containsAll(a2), I get true and I want false.
Thanks all for considering my request.
Use the remove method from ArrayList. It only removes the first occurance.
public static void main(String []args){
//Create ArrayLists
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
ArrayList<String> a1=new ArrayList(Arrays.asList(A1));
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
ArrayList<String> a2=new ArrayList(Arrays.asList(A2));
// Check ArrayLists
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
// Find difference
for( String s : a1)
a2.remove(s);
// Check difference
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
}
Result
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo, Rettangolo, Rombo, Quadrato]
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo]
These two classes might help. Let me know how I can improve this further.
Feel free to use the code below in your own work.
I must point out that the current code does not take care of repeated list elements.
import java.util.List;
public class ListDiff<T> {
private List<T> removed;
private List<T> added;
public ListDiff(List<T> removed, List<T> added) {
super();
this.removed = removed;
this.added = added;
}
public ListDiff() {
super();
}
public List<T> getRemoved() {
return removed;
}
public List<T> getAdded() {
return added;
}
}
Util class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListUtil {
public static <T> ListDiff<T> diff(List<T> one, List<T> two) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
if (!two.contains(elementOne)) {
//element in one is removed from two
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
if (!one.contains(elementTwo)) {
//element in two is added.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static <T> ListDiff<T> diff(List<T> one, List<T> two, Comparator<T> comparator) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
boolean found = false;
//loop checks if element in one is found in two.
for (int j = 0; j < two.size(); j++) {
T elementTwo = two.get(j);
if (comparator.compare(elementOne, elementTwo) == 0) {
found = true;
break;
}
}
if (found == false) {
//element is not found in list two. it is removed.
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
boolean found = false;
//loop checks if element in two is found in one.
for (int j = 0; j < one.size(); j++) {
T elementOne = one.get(j);
if (comparator.compare(elementTwo, elementOne) == 0) {
found = true;
break;
}
}
if (found == false) {
//it means element has been added to list two.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static void main(String args[]) {
String[] arr1 = { "london", "newyork", "delhi", "singapore", "tokyo", "amsterdam" };
String[] arr2 = { "london", "newyork", "delhi", "singapore", "seoul", "bangalore", "oslo" };
ListDiff<String> ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2));
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2), new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}); //sample for using custom comparator
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
}
}
Here are three solutions.
An implementation that uses a remove method.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
List<String> temp = new ArrayList<String>(list1);
temp.removeAll(list2);
return temp.size() == 0;
}
A solution that sorts then compares.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
Collections.sort(list1);
Collections.sort(list2);
for (int i=0;i<list1.size();i++){
if (!list1.get(i).equals(list2.get(i)))
return false;
}
return true;
}
And, just for fun, you could do this by doing a word count difference between the two arrays. It wouldn't be the most efficient, but it works and possibly could be useful.
public static boolean same(List<String> list1, List<String> list2){
Map<String,Integer> counts = new HashMap<String,Integer>();
for (String str : list1){
Integer i = counts.get(str);
if (i==null)
counts.put(str, 1);
else
counts.put(str, i+1);
}
for (String str : list2){
Integer i = counts.get(str);
if (i==null)
return false; /// found an element that's not in the other
else
counts.put(str, i-1);
}
for (Entry<String,Integer> entry : counts.entrySet()){
if (entry.getValue() != 0)
return false;
}
return true;
}
This will find the intersection between two arrays for this specific case you have explained.
String[] A1 = { "Rettangolo", "Quadrilatero", "Rombo", "Quadrato" };
String[] A2 = { "Rettangolo", "Rettangolo", "Rombo", "Quadrato" };
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(A1));
ArrayList<String> a2 = new ArrayList<String>(Arrays.asList(A2));
a1.removeAll(a2);
System.out.println("I have found " + a1);
I hope this will help you
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.addAll(Arrays.asList(A1));
set2.addAll(Arrays.asList(A2));
set1.removeAll(set2);
System.out.println(set1);// ==> [Quadrilatero]