I want extract sublists of an array list based on specific pattern as mentioned below. Please advise.
ArrayList<String> Filelist=new ArrayList<String>();
Filelist.add("abc.123");
Filelist.add("abc.456");
Filelist.add("def.123");
Filelist.add("def.456");
Here I need whatever starts with the first index, say abc to be stored in separate sublist and whatever starts with def need to be stored in separate sublist. The array list will have multiple entries like these, so it has to create separate sublists accordingly.
Map<String, List<String>> filesByPrefix = Filelist.stream()
.collect(Collectors.groupingBy(s -> s.split("\\.")[0]));
or the classic java 7 way.
Map<String, List<String>> map = new HashMap<>();
for (String str : lst) {
String[] splt = str.split("\\.");
if (!map.containsKey(splt[0])) {
map.put(splt[0], new ArrayList<>());
}
map.get(splt[0]).add(str);
}
give it a try :
package main_package;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Stackkkk {
static ArrayList<ArrayList<String>> pattern_lists=new ArrayList<ArrayList<String>>();
public static void main(String[] args) {
ArrayList<String> Filelist=new ArrayList<String>();
Filelist.add("abc.123");
Filelist.add("abc.456");
Filelist.add("def.123");
Filelist.add("def.456");
Filelist.add("def.456");
Filelist.add("def.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
Filelist.add("de1.456");
for(int i=0;i<Filelist.size();i++)
add_to_list(Filelist.get(i));
System.out.println("number of pattern found are :"+pattern_lists.size());
for(int i=0;i<pattern_lists.size();i++)
System.out.println("number of value in pattern "+i+" :"+pattern_lists.get(i).size());
}
public static void add_to_list(String value){
boolean pattern_found=false;
for(int i=0;i<pattern_lists.size();i++){
if(pattern_lists.get(i).get(0).startsWith(value.substring(0, 3))){
//pattern found add it to this list
pattern_lists.get(i).add(value);
pattern_found=true;
}
}
if(!pattern_found){
//create new list and add the value
ArrayList<String> new_list=new ArrayList<String>();
new_list.add(value);
pattern_lists.add(new_list);
}
}
}
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();
});
}
}
I would like to compare two arrays. I have the following
ArrayList<String> time_durations = new ArrayList<String>();
time_durations.add("1200-1304")
time_durations.add("6-7")
Then the other array has the following structure
ArratList<FetchedData> apiresult = new ArrayList<FetchedData>();
apiresult.add(new FetchedData("1200-1304", //an array of data))
The class fetched data has
class FetchedData{
private String duration_range;
private ArrayList data;
//then setters and getters
//and also a constructor
}
So i want to compare the two arrays and get all items contained in time_durations but not in apiresult
Samples of them both in a json format is
time_durations = ["1200-1304", "6-7"]
apiresult = [{duration_range:"1200-1304", data:["item1", "item 2"]}
So by comparison i expect it to return the item in array time_durations6-7 that is index 1
So i have tried
if (Arrays.equals(time_durations, apiresult)) {
//this throws an error
}
But the above attempt doesnt work and am stuck.How do i achieve this?
I have checked on This question but still fails
Your code doesn't work as you expected because the first ArrayList is an array of String and the second is an Array of FetchedData. You basically try to compare two ArrayList of different type and this return false by default.
If you want to reach the goals you must map the ArrayList of FetchedData into an ArrayList of String and with Java8 it is possible to do this with a Map function and after you are enable to comparing the two array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertArrayEquals;
public class TestClass {
#Test
public void arrayListComparation(){
List<String> expected = Arrays.asList("6-7");
ArrayList<String> time_durations = new ArrayList<String>();
time_durations.add("1200-1304");
time_durations.add("6-7");
ArrayList<FetchedData> apiresult = new ArrayList<>();
List<String> data = Arrays.asList("item1","item2");
apiresult.add(new FetchedData("1200-1304", data));
List<String> apiResultDurationRanges = apiresult.stream().map(FetchedData::getDuration_range).collect(toList());
time_durations.removeAll(apiResultDurationRanges);
assertArrayEquals(time_durations.toArray(),expected.toArray());
}
}
In this example you have on time_durations all element that not appear into apiResult
Iterate over the API results, get each duration and put them into a set. Remove the elements of the set from the list.
Set<String> apiDurations = apiresult.stream()
.map(FetchedData::getDuration)
.collect(Collectors.toSet());
time_durations.removeAll(apiDurations);
You can use Collection.removeAll:
List<String> apiResult_durations = apiresult.stream()
.map(FetchedData::getDuration_range)
.collect(Collectors.toList());
time_durations.removeAll(apiResult_durations);
After this code, time_durations is only [6-7]
Important to note that this will modify time_durations inline.
If you'd rather not modify it inline, then you can make a copy:
List<String> time_durations_copy = new ArrayList<>(time_durations);
time_durations_copy.removeAll(apiResult_durations);
I think you need the operation of set difference.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> time_durations = new ArrayList<String>();//The list with some elements
ArrayList<String> otherList = new ArrayList<String>();//Another list
ArrayList<String> difference = new ArrayList<String>();//The result
time_durations.add("1200-1304");//Add some data
time_durations.add("6-7");
otherList.add("1200-1304");
for (int i = 0; i < time_durations.size(); i++) {
if (!otherList.contains(time_durations.get(i))) {
difference.add(time_durations.get(i)); // get all items contained in time_durations but not in apiresult
}
}
for (String string : difference) {
System.out.println(string);
}
}
}
I have defined a few ArrayLists that are already populated. I have the names of all of the ones I want to iterate through in an array 'tagArrays'. Is it possible to iterate through each of them in a similar logic to mine. I know this code is not going to work however I'm not sure how the code is supposed to look. This is my attempt:
These are already populated and are defined in main method.
ArrayList<String> KEYWORDS = new ArrayList<String>();
ArrayList<String> CUSTOMERS = new ArrayList<String>();
ArrayList<String> SYSTEM_DEPS = new ArrayList<String>();
ArrayList<String> MODULES = new ArrayList<String>();
ArrayList<String> DRIVE_DEFS = new ArrayList<String>();
ArrayList<String> PROCESS_IDS = new ArrayList<String>();
This is the logic I'm using
public void genericForEachLoop(POITextExtractor te) {
final String[] tagArrays = {"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"};
ArrayList<String> al = new ArrayList<String>();
for(int i=0; i<tagArrays.length; i++) {
System.out.println(tagArrays[i]);
al = tagArrays[i];
for (String item : al) {
if (te.getText().contains(item)) {
System.out.println(item);
}
}
}
}
I want the for each loop to be different every time e.g. once go through KEYWORDS, then go through CUSTOMERS etc.
You cannot reference variables with string values in Java.
What you try to do could be performed with reflection.
But I don't encourage it : it is less readable, more brittle/error prone and slower as the "classical" way.
As alternative you can provide a varargs of List<String> as last parameter of the method:
public void genericForEachLoop(POITextExtractor te, String[] tagArrays, List<String>... lists ) {
int i = 0;
for(List<String> list : lists) {
System.out.println(tagArrays[i]);
for (String item : list) {
if (te.getText().contains(item)) {
System.out.println(item);
}
}
i++;
}
}
And invoke it in this way :
genericForEachLoop(te,
new String[]{"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"},
KEYWORDS, CUSTOMERS,SYSTEM_DEPS,MODULES,DRIVE_DEFS,PROCESS_IDS);
I have tried following things with respect to Java 8. Below is the working example of your code, I have modified some of the code. Please check.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainClass {
public static void main(String... args) {
String[] strings = {"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"};
ArrayList<String> KEYWORDS = new ArrayList<String>();
KEYWORDS.add("goto");
ArrayList<String> CUSTOMERS = new ArrayList<String>();
CUSTOMERS.add("Royal Lotus");
ArrayList<String> SYSTEM_DEPS = new ArrayList<String>();
SYSTEM_DEPS.add("MAC BOOK");
ArrayList<String> MODULES = new ArrayList<String>();
MODULES.add("TETS MODULE");
ArrayList<String> DRIVE_DEFS = new ArrayList<String>();
DRIVE_DEFS.add("TEST DRIVE");
ArrayList<String> PROCESS_IDS = new ArrayList<String>();
PROCESS_IDS.add("-15153213");
Map<String, List<String>> mapOfLists = new HashMap<>();
mapOfLists.put("KEYWORDS", KEYWORDS);
mapOfLists.put("CUSTOMERS", CUSTOMERS);
mapOfLists.put("SYSTEM_DEPS", SYSTEM_DEPS);
mapOfLists.put("DRIVE_DEFS", DRIVE_DEFS);
mapOfLists.put("PROCESS_IDS", PROCESS_IDS);
mapOfLists.put("MODULES", MODULES);
genericForEachLoop(mapOfLists, strings);
}
public static void genericForEachLoop(Map<String, List<String>> mapOfLists, String[] listsToIterate) {
Arrays.stream(listsToIterate).forEach((listName -> mapOfLists.get(listName).stream().forEach(str -> System.out.println(str))));
}
}
I have taken out the String[] and providing it as an input to method so I can change it. Only those arrays where I want to iterate I can pass them. Further more building on top of #Eran's answer I am using the Map<String, List<String> for storing all the available ArrayLists.
Please modify the code as per your need. I have tried to use the streams and foreach methods from Java8.
Rather creating String array you can create Array of ArrayList, which will help you to iterate dynamically like below.
public static void main(String[] args)
{
ArrayList<String> KEYWORDS = new ArrayList<String>();
ArrayList<String> CUSTOMERS = new ArrayList<String>();
ArrayList<String> SYSTEM_DEPS = new ArrayList<String>();
ArrayList<String> MODULES = new ArrayList<String>();
ArrayList<String> DRIVE_DEFS = new ArrayList<String>();
ArrayList<String> PROCESS_IDS = new ArrayList<String>();
final String[] tagNames = {"KEYWORDS", "CUSTOMERS", "SYSTEM_DEPS", "MODULES", "DRIVE_DEFS", "PROCESS_IDS"};
final List<String> tagNameList=Arrays.asList(tagNames);
final ArrayList[] tagList = { KEYWORDS, CUSTOMERS, SYSTEM_DEPS, MODULES, DRIVE_DEFS, PROCESS_IDS };
for (ArrayList<String> list : tagList) {
for(String str :list){
if(str.contains(""))
{
}
}
}
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.
I have created a list of Strings and I need to reverse the order of them using an iterator. This is what I have but it is not working. Can someone please help me find a way to do this or tell me what I am doing wrong?
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class nameList2
{
public static void main(String[] args)
{
List<String> nameList = new ArrayList<String>();
nameList.add("Joey"); //list of Strings
nameList.add("Nicole");
nameList.add("Lucas");
nameList.add("Bobby");
nameList.add("Michelle");
nameList.add("Allie");
Iterator<String> nameIterator = nameList.iterator(); //iterator
for(String s : nameList) //for, each loop
{
if(nameIterator.hasNext()); //compile list
nameIterator.next();
}
for(String s: nameList) //for, each loop
{
if(nameIterator.hasPrevious()); //error states method cannot find hasPrevious?
System.out.println(nameIterator.previous());
}
}
}
use ListIterator instead of Iterator as :
ListIterator<String> list = nameList.listIterator(nameList.size());
// Iterate in reverse.
while(list.hasPrevious()) {
System.out.println(list.previous());
}
and you can do also as Jonk suggested using Collections.reverse(nameList);
Use two ListIterators, one at the start, one at the end and swap until they meet.
And don't forget the edge case(s)
public static void main(String[] args) {
List<String> nameList = new ArrayList<String>();
nameList.add("Joey"); //list of Strings
nameList.add("Nicole");
nameList.add("Lucas");
nameList.add("Bobby");
nameList.add("Michelle");
nameList.add("Allie");
ListIterator<String> list = nameList.listIterator();
System.out.println("Before Reversed\n");
while(list.hasNext()){
System.out.println(list.next());
}
System.out.println("\nAfter Reversed \n");
while(list.hasPrevious()){
System.out.println(list.previous());
}
}