Java Code Examples for java.util.ArrayList.forEach()

The following are Jave code examples for showing how to use forEach() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hashsdn-controller   File: DistributedShardedDOMDataTree.java   Source Code and License Vote up 6 votes
void resolveShardAdditions(final Set<DOMDataTreeIdentifier> additions) {
    LOG.debug("{}: Resolving additions : {}", memberName, additions);
    final ArrayList<DOMDataTreeIdentifier> list = new ArrayList<>(additions);
    // we need to register the shards from top to bottom, so we need to atleast make sure the ordering reflects that
    Collections.sort(list, (o1, o2) -> {
        if (o1.getRootIdentifier().getPathArguments().size() < o2.getRootIdentifier().getPathArguments().size()) {
            return -1;
        } else if (o1.getRootIdentifier().getPathArguments().size()
                == o2.getRootIdentifier().getPathArguments().size()) {
            return 0;
        } else {
            return 1;
        }
    });
    list.forEach(this::createShardFrontend);
}
 
Example 2
Project: BEAST   File: FileLoaderTest.java   Source Code and License Vote up 6 votes
/**
 * Test of getNewUniqueName method, of class FileLoader.
 */
@Test
public void testGetNewUniqueName() {
    System.out.println("getNewUniqueName");

    String pathToDir = "/src/test/testfiles/";

    ArrayList<String> usedNames = new ArrayList<>();

    File folder = new File(pathToDir);
    File[] listOfFiles = folder.listFiles();

    if (listOfFiles != null) {
        for (File file : listOfFiles) {
            if (file.isFile()) {
                usedNames.add(file.getName());
            }
        }
    }
    String result = FileLoader.getNewUniqueName(pathToDir);
    assert (result != null);
    usedNames.forEach((filename) -> {
        assert (!(filename.equals(result)));
    });
    
}
 
Example 3
Project: SubtitleDownloader   File: HTTPRequest.java   Source Code and License Vote up 6 votes
public void sendDownloadRequestsOpenSub(ArrayList<VideoInfo> videoInfoArray, String lang) {
    videoInfoArray.forEach((videoInfo) -> {
        try {
            if (!videoInfo.getChecksumHash().equals("") && !videoInfo.isDownloaded()) {
                String subtitle = sendGetSubtitleOpenSub(videoInfo.getChecksumHash(), videoInfo.getFileByteLength(), lang);
                if (subtitle != null && !subtitle.equals("")) {
                    videoInfo.setSubtitle(subtitle);
                    videoInfo.setDownloaded(true);
                }
                System.out.println("subtitlemanager.HTTPRequest.sendDownloadRequestsOpenSub() subtile == null = " + (videoInfo.getSubtitle() == null) + " hash = " + videoInfo.getChecksumHash() + " fileName = " + videoInfo.getFullFilePath());;
            } else {
                if (!videoInfo.isDownloaded()) {
                    System.out.println("subtitlemanager.HTTPRequest.sendDownloadRequestsOpenSub() Hash for file = " + videoInfo.getFullFilePath() + " is " + videoInfo.getChecksumHash());
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(HTTPRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
}
 
Example 4
Project: brModelo   File: CopFormatacao.java   Source Code and License Vote up 6 votes
public void Colar(FormaElementar var) {
    if (copiado == null) {
        return;
    }
    if (var instanceof Forma) {
        if (((Forma) var).editFonte) {
            var.setFont(fonteCopiada);
        }
    }
    ArrayList<InspectorProperty> dest = Resuma(var.GenerateFullProperty());
    ArrayList<InspectorProperty> aColar = new ArrayList<>();

    ArrayList<String> tmp = new ArrayList<>();
    dest.forEach(it -> {
        tmp.add(it.property);
    });
    copiado.stream().filter(c -> tmp.indexOf(c.property) > -1).forEach(ac -> {
        aColar.add(ac);
    });

    aColar.forEach(ac -> {
        var.getMaster().ColeFormatacao(var, ac, ac.valor_string);
    });
}
 
Example 5
Project: Algorithms-4-everyone   File: InsertionSort.java   Source Code and License Vote up 5 votes
/**
 * Tester method
 */
public static void main(String... args) {

    // Example 1 : sorting an ArrayList of integers
    InsertionSort<Integer> sortIntegers = new InsertionSort<>();
    ArrayList<Integer> elements = new ArrayList<>(
            Arrays.asList(98, 56, 42, 78, 36, 4, 12, 2)
    );
    sortIntegers.sort(elements);
    elements.forEach(element -> System.out.print(element + " "));

    // Example 2 : sorting an array of strings
    InsertionSort<String> sortStrings = new InsertionSort<>();
    String[] data = {"echo", "foxtrot", "charlie", "alpha", "bravo", "delta"};
    sortStrings.sort(data);
    System.out.println("\n" + Arrays.toString(data));

    // Example 3 : sorting an empty array
    InsertionSort<Character> sortChars = new InsertionSort<>();
    Character[] chars = new Character[0];
    sortChars.sort(chars);
    System.out.println(Arrays.toString(chars));

    // Example 4 : sorting an already sorted ArrayList of Integers
    ArrayList<Integer> sorted = new ArrayList<>(
            Arrays.asList(2, 4, 12, 36, 42, 56, 78, 98)
    );
    sortIntegers.sort(sorted);
    elements.forEach(element -> System.out.print(element + " "));
    System.out.println();

    // Example 5 : sorting a list that is sorted in reverse order
    final List<String> words = Arrays.asList(
            "foxtrot", "echo", "delta", "charlie", "bravo", "alpha");
    List<String> result = sortStrings.sort(words);
    result.forEach(element -> System.out.print(element + " "));
    System.out.println();
}
 
Example 6
Project: BEAST   File: CodeArrayListBeautifier.java   Source Code and License Vote up 5 votes
/**
 * adds an ArrayList with the indenting
 *
 * @param arrayList the added ArrayList
 */
public void addArrayList(ArrayList<String> arrayList) {
    if (arrayList != null) {
        arrayList.forEach((singleItem) -> {
            this.add(singleItem);
        });
    }
}
 
Example 7
Project: StickyChunk   File: CommandUnload.java   Source Code and License Vote up 5 votes
private Consumer<CommandSource> unloadAll(Player player) {
	return src -> {
		ArrayList<LoadedRegion> loadedRegions = Lists
			.newArrayList(dataStore.getPlayerRegions(player.getUniqueId()));

		loadedRegions.forEach(loadedRegion ->
			dataStore.deletePlayerRegion(loadedRegion.getOwner(), loadedRegion.getUniqueId())
		);
	};
}
 
Example 8
Project: xcc   File: LCSSA.java   Source Code and License Vote up 5 votes
/**
 * Process all loops in the entire function.
 * @param loop
 * @return
 */
@Override
public boolean runOnLoop(Loop loop, LPPassManager ppm)
{
	predCache.clear();
	li = (LoopInfo) getAnalysisToUpDate(LoopInfo.class);
	dt = (DomTree) getAnalysisToUpDate(DomTree.class);

	loopBlocks = new ArrayList<>(loop.getBlocks());
	ArrayList<BasicBlock> exitBlocks = loop.getExitingBlocks();

	ArrayList<Instruction> affectedValues = new ArrayList<>();
	getLoopValueUsedOutsideLoop(loop, affectedValues, exitBlocks);

	// If no values are affected, we can save a lot of work, since we know that
	// nothing will be changed.
	if (affectedValues.isEmpty())
		return false;

	// Iterate over all affected values for this loop and insert Phi nodes
	// for them in the appropriate exit blocks
	affectedValues.forEach(var->
	{
		processInstruction(var, exitBlocks);
	});
	return true;
}
 
Example 9
Project: WC   File: ChestManager.java   Source Code and License Vote up 5 votes
public void openChest(Chest chest, Player p){
    AllItems items = new AllItems();

    if (cooldown.isCoolingDown(chest)) {
        WCTWD.getPlayer(p).sendMessage("&cEste cofre está en cooldown. Tiempo &6" + cooldown.getTimeLeft(chest));
        return;
    }
    cooldown.setOnCooldown(chest);

    Inventory inv = Bukkit.createInventory(null, 36, ChatColor.RED + "Cofre de Recursos");

    //Ajustar cantidad
    int i1 = r.nextInt(3);
    int i2 = r.nextInt(3);
    int i3 = r.nextInt(2);

    ArrayList<ItemStack> aleatorios = new ArrayList<>();

    for (int i = 0; i < i1; i++) {
        if (r.nextInt(4) > 1) aleatorios.add(items.weapons.get(r.nextInt(items.weapons.size())));
    }
    for (int i = 0; i < i2; i++) {
        if (r.nextInt(4) > 1)  aleatorios.add(items.health.get(r.nextInt(items.health.size())));
    }
    for (int i = 0; i < i3; i++) {
        if (r.nextInt(3) == 2)  aleatorios.add(items.weapons2.get(r.nextInt(items.weapons2.size())));
    }

    aleatorios.forEach(i -> setItem(inv, getSlot(r, inv), i));
    p.closeInventory();
    p.openInventory(inv);
}
 
Example 10
Project: xcc   File: Init.java   Source Code and License Vote up 5 votes
public DagInit(Init val, String vn,  ArrayList<Pair<Init, String>> args)
{
    super(new RecTy.DagRecTy());
    this.val = val;
    varName = vn;
    this.args = new ArrayList<>(args.size());
    argNames = new ArrayList<>(args.size());
    args.forEach(pair->{
        this.args.add(pair.first);
        argNames.add(pair.second);
    });
}
 
Example 11
Project: sic-public   File: MainFrame.java   Source Code and License Vote up 5 votes
public void addAlerta(ArrayList<AlertaInternacional> al){
    
    //for(int i=0;i<=al.length;i++){
    //   dtm.setRowCount(dtm.getRowCount()+1);
    // dtm.setValueAt(al[i], i, 0);
    //}
    //TODO: TRABAJANDO AQUI
    i=0;
    al.forEach((_item) -> {
        
        if(!al.isEmpty()){
            dtm.setRowCount(al.size());
            //showMessageDialog(null, _item.toString()+"\n ID: "+_item.getId()+"\nSize: "+al.size());
            dtm.setValueAt(_item, i, 0);
            if (i <= al.size()) {
                i++;
            } else {

            }
        }else{
            
        }
        
        
        //valor, row, columna(titulo cabeza)
        //dtm.setValueAt(a, i, 0);
    });
}
 
Example 12
Project: LD38   File: UIScene.java   Source Code and License Vote up 5 votes
public void input(){
	ArrayList<ClickType> clicks = new ArrayList<ClickType>();
	
	for(int k : Keyboard.events){
		clicks.add(new ClickType(false, k));
	}
	
	//focused element listens to the keyboard clicks
	for(ClickType click : clicks){
		options[current].onClick(click);
	}
	
	clicks.clear();
	
	for(int m : Mouse.events){
		clicks.add(new ClickType(true, m));
	}
	
	Vector2f mPos = scene.flipY(Mouse.x, Mouse.y);
	
	if(clicks.size() != 0){
		for(UIElement option : options){
			if(option.contains(mPos)){
				clicks.forEach((click)->option.onClick(click));
			}
		}
		clicks.clear();
	}
	
	Input();
}
 
Example 13
Project: converter   File: Converter.java   Source Code and License Vote up 5 votes
public final EnumMap<Category, ArrayList<UnitDefinition>> getAllUnitDefinitions() {
    final EnumMap<Category, ArrayList<UnitDefinition>> UNIT_TYPES    = new EnumMap<>(Category.class);
    final ArrayList<Category>                          CATEGORY_LIST = new ArrayList<>(Category.values().length);
    CATEGORY_LIST.addAll(Arrays.asList(Category.values()));
    CATEGORY_LIST.forEach(category -> UNIT_TYPES.put(category, new ArrayList<>()));
    for (UnitDefinition unitDefinition : UnitDefinition.values()) {
        UNIT_TYPES.get(unitDefinition.UNIT.getCategory()).add(unitDefinition);
    }
    return UNIT_TYPES;
}
 
Example 14
Project: StickyChunk   File: SqlDatabase.java   Source Code and License Vote up 4 votes
public void saveRegionData(ArrayList<LoadedRegion> data) {
	data.forEach(this::saveRegionData);
}
 
Example 15
Project: StickyChunk   File: CommandList.java   Source Code and License Vote up 4 votes
/**
 * Callback for the execution of a command.
 *
 * @param src  The commander who is executing this command
 * @param args The parsed command arguments for this command
 * @return the result of executing this command
 * @throws CommandException If a user-facing error occurs while executing this command
 */
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
	if (!(src instanceof Player))
		return execServer(src, args);

	User user = args.<User>getOne(USER).orElse((Player) src);
	List<Text> listText = Lists.newArrayList();
	ArrayList<LoadedRegion> loadedRegions = dataStore.getPlayerRegions(user);

	Text header = Text.of(
		"Listing ",
		TextColors.GOLD, loadedRegions.size(),
		TextColors.RESET, " region(s) across ",
		TextColors.GOLD, dataStore.getPlayerRegionWorlds(user).size(),
		TextColors.RESET, " worlds"
	);

	if (loadedRegions.isEmpty())
		header = Text.of(TextColors.RED, "There are no loaded regions to display");

	loadedRegions.forEach(region -> listText.add(Text.of(
		TextColors.GOLD, region.getChunks().size(),
		TextColors.GREEN, Text.of(" [", (region.getType() == LoadedRegion.ChunkType.WORLD) ? 'W' : 'P', "]")
			.toBuilder().onHover(TextActions.showText(Text.of(TextColors.GREEN,
				(region.getType() == LoadedRegion.ChunkType.WORLD) ? "World" : "Personal"
			))),
		TextColors.WHITE, (region.getChunks().size() > 1) ? " chunks in world " : " chunk in world ",
		TextColors.GOLD, region.getWorld().getName(),
		TextColors.WHITE, " from (", TextColors.LIGHT_PURPLE, region.getRegion().getFrom().getX(), TextColors.WHITE,
		", ", TextColors.LIGHT_PURPLE, region.getRegion().getFrom().getZ(), TextColors.WHITE, ")",
		TextColors.WHITE, " to (", TextColors.LIGHT_PURPLE, region.getRegion().getTo().getX(), TextColors.WHITE,
		", ", TextColors.LIGHT_PURPLE, region.getRegion().getTo().getZ(), TextColors.WHITE, ")"
	)));

	PaginationList.builder()
		.title(Text.of(TextColors.GOLD, "Loaded Regions"))
		.padding(Text.of(TextColors.GOLD, TextStyles.STRIKETHROUGH, "-"))
		.header(header)
		.contents(listText)
		.sendTo(src);

	return CommandResult.success();
}
 
Example 16
Project: n4js   File: NpmExportWizard.java   Source Code and License Vote up 4 votes
@Override
public void init(IWorkbench targetWorkbench, IStructuredSelection currentSelection) {

	// this.selection = currentSelection;

	List<?> selectedResources = IDE.computeSelectedResources(currentSelection);
	List<IProject> workspaceProjects = Arrays.asList(ResourcesPlugin.getWorkspace().getRoot().getProjects());

	// Find all selected projects
	Set<IProject> projects = selectedResources.stream()
			.filter(m -> m instanceof IResource)
			.map(m -> ((IResource) m).getProject())
			.filter(p -> p.isOpen()) // only open projects
			.collect(Collectors.toSet());
	// make the behavior predictable by ordering:
	TreeSet<IProject> sortedProjects = Sets
			.<IProject> newTreeSet((a, b) -> a.getName()
					.compareToIgnoreCase(b.getName()));
	sortedProjects.addAll(projects);

	// 0) turn into IN4JSProject and give and process further.
	// a) find out which projects fulfill the npm-"exportable"-contract
	// b) give back a list to the user what to export,
	// c) disable things not fullfilling the contract.
	// d) take choosing from the list and pass to exporter in non-ui package.

	// 0)
	List<IN4JSEclipseProject> rawN4jsProjects = Lists.newArrayList();
	iP2in4jsP = HashBiMap.create();
	for (IProject iProject : workspaceProjects) {
		IN4JSEclipseProject mappedIn4jsProject = map2In4js(iProject);
		if (mappedIn4jsProject != null) {
			rawN4jsProjects.add(mappedIn4jsProject);

			iP2in4jsP.put(iProject, mappedIn4jsProject);
		}
	}

	// filter out Non-N4JS-projects from initial selection.
	sortedProjects.retainAll(iP2in4jsP.keySet());

	// filter out all non-N4JS-projects from the workspace projects.
	ArrayList<IProject> filteredWorkspaceProjects = new ArrayList<>(workspaceProjects);
	filteredWorkspaceProjects.retainAll(iP2in4jsP.keySet());

	setWindowTitle("N4JS to npm Export");
	setNeedsProgressMonitor(true);

	Map<IProject, Boolean> selectedProjects = new HashMap<>();
	// Add all workspace projects to list, default selection value is false
	filteredWorkspaceProjects.forEach(project -> selectedProjects.put(project, false));
	// Override selection value for all initially selected projects
	sortedProjects.forEach(project -> selectedProjects.put(project, true));

	// exportPage = new ExportSelectionPage("Export Page", rawN4jsProjects, labelProvider);
	exportPage = new ExportSelectionPage("Export Page", selectedProjects);
	if (runTools())
		toolRunnerPage = new NpmToolRunnerPage("npm Execution Page");
	comparePage = new PackageJsonComparePage("Compare package.json Page");

	pageListener = new IPageChangedListener() {

		@Override
		public void pageChanged(PageChangedEvent event) {
			if (event.getSelectedPage() == comparePage) {
				udpatePackagJasonComparison();
			}
		}
	};
}
 
Example 17
Project: brModelo   File: FormaArea.java   Source Code and License Vote up 4 votes
public void comandoUnCapture() {
    ArrayList<FormaElementar> overme = WhoIsOverMe();
    overme.forEach((el) -> {
        PerformLigacao(el, false);
    });
}
 
Example 18
Project: H-Uppaal   File: ProjectPaneController.java   Source Code and License Vote up 4 votes
private void sortPresentations() {
    final ArrayList<Component> sortedComponentList = new ArrayList<>();
    componentPresentationMap.keySet().forEach(sortedComponentList::add);
    sortedComponentList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
    sortedComponentList.forEach(component -> componentPresentationMap.get(component).toFront());
}
 
Example 19
Project: StickyChunk   File: DataStore.java   Source Code and License Vote up 4 votes
public void addUsers(ArrayList<UserData> userDatas) {
	userDatas.forEach(user -> loadedUsers.put(user.getUniqueId(), user));
}
 
Example 20
Project: WC   File: MobAttack.java   Source Code and License Vote up 4 votes
public static void giantAttacks(Giant boss, Player damager){
    int attack = r.nextInt(8);
    List<Player> near = new ArrayList<>();

    boss.getNearbyEntities(7, 7, 7).forEach(en -> {
        if (en instanceof Player) {
            near.add((Player) en);
        }
    });

    switch (attack){
        case 0:
            near.forEach(p -> {
                if (!p.equals(damager)) {
                    p.getWorld().strikeLightningEffect(p.getLocation());
                    p.damage(0.5);

                    if (r.nextBoolean()) p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 40, 0));
                    if (r.nextBoolean()) p.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 30, 0));
                }
            });

            damager.getWorld().strikeLightningEffect(damager.getLocation());
            damager.damage(0.5);

            if (r.nextBoolean()) damager.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 40, 0));
            if (r.nextBoolean()) damager.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 30, 0));
            break;
        case 1:
            ArrayList<Location> locs = Utils.getCircle(boss.getEyeLocation(), 7, 30);

            locs.forEach(l -> { //Change Color
                ParticleEffect.REDSTONE.display(new ParticleEffect.OrdinaryColor(100, 60, 50), l, 50);
                ParticleEffect.REDSTONE.display(new ParticleEffect.OrdinaryColor(200, 60, 50), l.subtract(0, 7, 0), 50);
            });

            near.forEach(p -> {
                if (!p.equals(damager)) {
                    ParticleEffect.EXPLOSION_NORMAL.display(new Vector(0, 0, 0), 4, p.getLocation(), 50);
                    p.damage(0.5);
                }
            });

            ParticleEffect.EXPLOSION_NORMAL.display(new Vector(0, 0, 0), 4, damager.getLocation(), 50);
            damager.damage(0.5);
            break;
        case 2:
            if (boss.getHealth() + 20 >= boss.getMaxHealth()) boss.setHealth(boss.getMaxHealth());
            boss.setHealth(boss.getHealth() + 20);
            break;
        default:
            break;
    }
}