How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.
Related
I am using a 2D LinkedHashSet for my program. I was wondering how I can iterate through the two dimensional HashSet and print its contents without doing this:
System.out.println(name of initialized HashSet)
Here is my code for initialization of the 2D LinkedHashSet:
LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<LinkedHashSet<String>>();
You can use 2 loops for this, similar to how you would for an array:
for (Set<String> innerSet : block) {
for (String string : innerSet) {
System.out.println(string);
}
}
You can also use streams to print each element:
block.stream()
.flatMap(Collection::stream)
.forEach(System.out::println);
If one wants to use a functional solution, one could use the following:
Ideone demo
import java.util.LinkedHashSet;
public class Streamify {
public static void main (final String... args) {
final LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<>();
final LinkedHashSet<String> lineOne = new LinkedHashSet<>();
lineOne.add("Hello");
lineOne.add("World");
block.add(lineOne);
final LinkedHashSet<String> lineTwo = new LinkedHashSet<>();
lineTwo.add("Hi");
lineTwo.add("Universe");
block.add(lineTwo);
block.forEach(line -> {
line.forEach(System.out::print);
System.out.println();
});
}
}
This programm shuffles a source list by pairs. So that original list
"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"
trasfoms to
11^12 19^20 17^18 15^16 1^2 5^6 3^4 13^14 7^8 9^10
The above is true while commented line is uncommented. Now, if line A is commented then all the elements in shuffleList are 19^20.
public class ShuffleService {
public static void shuffleList(List<String> list) {
System.out.println(list);
ArrayList<String[]> shuffleList = new ArrayList<String[]>(10);
String[] arr = new String[2];
boolean flag = false;
int step = 0;
for(String s: list){
if(flag){
arr[1]=s;
} else {
arr[0]=s;
}
flag=!flag;
step++;
if(step==2){
shuffleList.add(arr);
step=0;
//arr = new String[2]; //**line A**
}
}
Collections.shuffle(shuffleList);
for(String[] val: shuffleList){
System.out.print(val[0]);
System.out.print("^");
System.out.println(val[1]);
}
}
public static void main(String[] args) {
String[] a = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"};
List<String> list1 = Arrays.asList(a);
shuffleList(list1);
}
}
So why do I need to uncomment line A in the program to work properly?
Because when you rewrite the values to arr (without remaking it), you're also going to modify the values already in the list.
Adding an object to the list doesn't stop you from modifying it, it will not make copies on its own. By calling new String[2] in your loop you're effectively building a new string array for each pair that you add to the list, which is what you want.
I wrote a program that asks users to input names into an array and then the names are sorted in alphabetical order...The program works good but I was wondering if I could sort each of the names entered by the 2nd, 3rd, or 4th character in each string? For example, if the user entered Bob, Dan, and Kris the program should sort them as Dan, Bob, Kris. This is my program that sorts my array of strings by the first letter of the string:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SortingAnArrayOfStrings {
public static void main(String[] args) {
{
//Ask the user for names to add to the array
List<String> list=new ArrayList<String>();
Scanner in=new Scanner(System.in);
do {
System.out.println(" The names on the list are "+list);
System.out.println("Would you like to add another name to the list? (y/n)");
if (in.next().startsWith("y")) {
System.out.println("Enter:");
list.add(in.next());
}else{break;
}
} while (true);
//display the names that have been added to the array
System.out.println("The names on the list are "+list);
//sort the array of names in alphabetical order
String[] Arr=list.toArray(new String[list.size()]);
String[] stringArray=new String[Arr.length];
for(int i=0;i<Arr.length;i++)
{
for (int j = i+1; j < Arr.length; j++) {
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
String temp=Arr[j];
Arr[j]=Arr[i];
Arr[i]=temp;
}
}
stringArray[i]=Arr[i];
}
//display the sorted list of names
System.out.println("This is the list of names after sorting them in alphabetical order : ");
for(String ss:stringArray){
System.out.print(ss + " ");
}
}
}
}
You could try something like bellow using a custom java.util.Comparator:
String[] names = {"Dan", "Bob", "Kris"};
java.util.Collections.sort(java.util.Arrays.asList(names), new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.charAt(1) - s2.charAt(1);//comparision
}
});
for (String name : names) System.out.println(name);
output:
Dan
Bob
Kris
You could try this, just add a custom comparator by using Lambda expressions if you are using java version 1.8 or above :
list.add("Bob");
list.add("Dan");
list.add("Kris");
Collections.sort(list, (s1, s2) -> {
String sb1 = s1.substring(1);
String sb2 = s2.substring(1);
return sb1.compareTo(sb2);
});
System.out.println("list = " + list);
The Result:
list = [Dan, Bob, Kris]
I haven't tested this one but you could try this one. Replace the condition part of your code by this one.
Though, there may be some performance issue.
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
Replace with:
if (Arr[i].trim().charAt(nthChar) > Arr[j].trim().charAt(nthChar)) {
The nthChar is the character placement to compare.
Here is sample tested code. You need to use comparator so as to implement the order.
Here value of order can be anything based on your requirement. You can replace your current code with this because it is fine for normal sorting as well (based on index 0). It might require some tweaks based on your need.
String str[] = {"abc","bca","avc","ert"};
final int ORDER = 1;
Arrays.sort(str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.toLowerCase().charAt(ORDER) - o2.toLowerCase().charAt(ORDER) ;
}
});
Add different implementations of java.util.Comparator based on the requirement and use
public static <T> void sort(List<T> list,
Comparator<? super T> c) in collections class to sort the list.
You want to use a custom comparator.
My arraylist contains String array objects.
How Can I get all values?
My code is below,
String cordinates1c,cordinates2l,cordinates2m;
String[] array1={cordinates1c,cordinates2l,cordinates2m};
String[] array2={cordinates1c,cordinates2l,cordinates2m};
ArrayList alist=new ArrayList();
alist.add(array1);
alist.add(array2);
//retreieving
for(int i=0;i<alist.size();i++)
System.out.println("arrayList="+alist.get(i));
if I try to retrieve like above it gives,
07-12 12:42:09.977: INFO/System.out(743): arrayList=[[Ljava.lang.String;#43e11b28]
How to do that?
Arrays should be printed with the help of Arrays.toString() or Arrays.deepToString().
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws Exception {
String[][] a = {{"a", "b", "c"}, {"d", "e"}};
System.out.println(Arrays.deepToString(a));
}
}
for(int i=0;i<alist.size();i++) {
for (String a : alist.get(i)) {
System.out.println(a);
}
}
You have to iterate over the array of strings, too.
You can iterate over your List and then use Arrays.toString() or Arrays.deepToString() to print array contents
for (String[] eachArray : alist) {
System.out.println("arrayList=" + Arrays.deepToString(eachArray));
}
ArrayList<String[]> l;
for (String[] a : l) {
for (String s : a) {
System.out.println(s);
}
}
Hoping that you are trying to print the string in array1
ArrayList<String> alist= (ArrayList<String>) Arrays.asList(array1);
Now print the data from alist.
also have a look into alist.addAll(collection)
But following snippet will add array1 and array2 object to your ArrayList, So retrieval you will get an array object
alist.add(array1);
alist.add(array2);
Are you looking for something like this ?
String cordinates1c = "1", cordinates2l = "2", cordinates2m = "3";
String[] array1 = {cordinates1c, cordinates2l, cordinates2m};
String[] array2 = {cordinates1c, cordinates2l, cordinates2m};
List<String []> alist=new ArrayList<String []>();
alist.add(array1);
alist.add(array2);
for (String[] strings : alist) {
System.out.println(StringUtils.join(strings));
}
Output:
123
123
I have a 2D string array consisting of values like as
{ "Home","0.1256784"
"Contact","-0.56789"
"Refer","1.36589"
"Next","3.678456" }
I have to sort the array based upon the second element(double value) and obtain a result such as like
{"Contact","-0.56789"
"Home","0.1256784"
"Refer","1.36589"
"Next","3.678456" }
I have used some bubble sort code to sort it and it works, but and i have to know how can i make the sorting more efficient than my one in faster manner.I tried some code posted previously for the questions related to mine but i can't get the task done.
My Code:
String tt="",tk="";
for(int i=1;i<myarray.length;i++)
{
for(int j=1;j<myarray.length-1;j++)
{
if(Double.parseDouble(myarray[i][1])<Double.parseDouble(myarray[j][1]))
{
tk=myarray[i][1];
tt=myarray[i][0];
myarray[i][1]=myarray[j][1];
myarray[i][0]=myarray[j][0];
myarray[j][1]=myarray;
myarray[j][0]=myarray;
}
}
}
public class Sort2D {
public static void main(String args[]) {
String ss[][] = {
{"Home", "0.1256784"},
{"Contact", "-0.56789"},
{"Refer", "1.36589"},
{"Next", "3.678456"}
};
Arrays.sort(ss, new Comparator<String[]>() {
public int compare(String[] s1, String[] s2) {
double d1 = Double.parseDouble(s1[1]);
double d2 = Double.parseDouble(s2[1]);
return Double.compare(d1, d2);
}
});
for (String[] s : ss) {
System.out.println(s[0] + ": " + s[1]);
}
}
}
If it's a 2d array you can use Array.sort(String[], Comparator<String[]> comparator) and pass a custom comparator, which compares the 2nd element of the sub array.
You can use Arrays.sortsort(Object[] a, Comparator c) and let java take care of it. You may find this link useful
Alternative approach: you could copy the data to a TreeMap (in case all double values are unique) and let the map to the sorting:
Map<Double, String> map = new TreeMap<Double, String>();
for (String[] row:myArray) {
map.put(Double.parseDouble(row[1]), row[1]);
The entrysets iterator now returns the values in ascending sort order.