Skip to content

PR - Diogo - Pratica de Lambda #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions src/com/github/deividfrancis/Carrinho.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package com.github.deividfrancis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.github.deividfrancis.backup.Person;

public class Carrinho {
private static List<Produtos> produtoList = new ArrayList<Produtos>();

static {
produtoList.add(new Produtos(744, "Redragon Kumara" , 243.35, "Tecnologia", 'S'));
produtoList.add(new Produtos(850, "Redragon Cobra" , 190.20, "Tecnologia", 'S'));
produtoList.add(new Produtos(022, "SSD M.2" , 102.02, "Tecnologia", 'S'));
produtoList.add(new Produtos(848, "Monitor 24p 165hz" , 1153.0, "Tecnologia", 'N'));
produtoList.add(new Produtos(254, "Oculos de ciclismo" , 104.02, "Esporte" , 'S'));
produtoList.add(new Produtos(78, "Molinete de pesca" , 175.00, "Esporte" , 'N'));
produtoList.add(new Produtos(415, "Tenis allstar" , 167.00, "Vestuario" , 'S'));
produtoList.add(new Produtos(403, "Luva de motociclista" , 134.00, "Vestuario" , 'N'));
produtoList.add(new Produtos(625, "Chave de fenda magnética", 55.00, "Equipamentos", 'S'));
produtoList.add(new Produtos(573, "Tapete Geometrico", 114.00, "Lazer", 'S'));
}


public static void main(String[] args) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não consigo vincular de forma simples qual método é a resposta de cada pergunta, fica como dica adicionar um comentário com a questão para ajudar quem vai corrigir kkk.

// filtroTecnologia();
// filtroEstoqueValor200();
// filtroTemEstoque();
// filtroEsporte();
// filtroPrimeiraEquipamentos();
// agrupaAlfabetica();
// groupByCategoria();
// getMaiorValor();
// getListIds();
}


private static void filtroTecnologia() {
List<Produtos> produtoTempList = Carrinho.produtoList.stream()
.filter(p -> "Tecnologia" == p.getCategoria())
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tem certeza que esse método funcionou? a forma correta de comparar Objetos no java seria utilizar o método .equals

.collect(Collectors.toList());

System.out.println(produtoTempList);
}

private static void filtroEstoqueValor200() {
List<Produtos> produtoTempList = produtoList.stream()
.filter(p -> 'S' == p.getTemEstoque() && p.getValor() > 200.00)
.collect(Collectors.toList());

System.out.println(produtoTempList);
}

private static void filtroTemEstoque() {
List<Produtos> produtoTempList = produtoList.stream()
.filter(p -> 'S' == p.getTemEstoque())
.collect(Collectors.toList());

produtoTempList.stream().forEach(p -> {
System.out.println(p.getNome());
});
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DICA Interessante a forma que foi pensada para resolver essa atividade, talvez outra forma legal de fazer seria aproveitando o stream que fez no começo e adicionando mais uma condição ex:

-		List<Produtos> produtoTempList = produtoList.stream()
+		List<String> produtoNamesList = produtoList.stream()
				.filter(p -> 'S' == p.getTemEstoque())
+				.map(Produtos::getName)
				.collect(Collectors.toList());

}

private static void filtroEsporte() {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O objetivo era fazer a soma do atributo valor da classe Produtos e não fazer fazer a contagem da lista

Long produtoTempList = produtoList.stream()
.filter(p -> "Esporte" == p.getCategoria())
.collect(Collectors.counting());

System.out.println(produtoTempList);
}

private static void filtroPrimeiraEquipamentos() {
Produtos produtoTempList = produtoList.stream()
.filter(p -> p.getCategoria() == "Equipamentos")
.findFirst()
.orElse(null);

System.out.println(produtoTempList);
}

public static void agrupaAlfabetica() {
List<Produtos> produtoTempList = produtoList.stream()
.sorted((x1 , x2) -> x1.getNome().compareTo(x2.getNome()))
.toList();

System.out.println(produtoTempList);
}

public static void groupByCategoria() {
Map<String, List<Produtos>> produtoMap = produtoList.stream().collect(Collectors.groupingBy(Produtos::getCategoria));

System.out.println(produtoMap);
}

private static void getMaiorValor() {
Optional<Produtos> produtoTempList = produtoList.stream()
.sorted((x1 , x2) -> x2.getValor().compareTo(x1.getValor()))
.findFirst();

produtoTempList.stream().forEach(p -> {
System.out.println(p.getCategoria());
});
}
private static void getListIds() {
List <Produtos> produtoTempList = produtoList.stream()
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interessante sua forma de pensar, parabéns por resolver o problema mas tem uma limitação na lógica, imagine que esses ids são informados pelo usuário... seu código não ia suportar, uma forma seria:

List<Integer> ids = Arrays.asList(850, 403, 625);
List <Produtos> produtoTempList = produtoList.stream()
                                 .filter(p -> ids.contains(p.getId()))
				.toList();

.filter(p -> 850 == p.getId() || 403 == p.getId() || 625 == p.getId())
.toList();

System.out.println(produtoTempList);
}
}



55 changes: 55 additions & 0 deletions src/com/github/deividfrancis/Produtos.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.github.deividfrancis;

import java.math.BigDecimal;

public class Produtos {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DICA:

  • Por padrão do design pattern bean o nome da classe não seria no plural ex:
- Produtos
+ Produto
  • Legal a estrutura que você criou a classe (muitos sente dificuldade), uma dica seria para o atributo de categoria utilizar um enum ia deixar seu código mais profissional ; )

private Integer id;
private String nome;
private Double valor;
private String categoria;
private char temEstoque;

public Produtos(Integer id, String name, Double valor, String categoria, char temEstoque) {
this.id = id;
this.nome = name;
this.valor= valor;
this.categoria = categoria;
this.temEstoque = temEstoque;
}

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Double getValor() {
return valor;
}
public void setValor(Double valor) {
this.valor = valor;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public char getTemEstoque() {
return temEstoque;
}
public void setTemEstoque(char temEstoque) {
this.temEstoque = temEstoque;
}

@Override
public String toString() {
return "Id=" + id + ", Nome=" + nome + ", Valor=R$" + valor + ", categoria=" + categoria + ", temEstoque=" + temEstoque +"\n\n";
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.github.deividfrancis;
package com.github.deividfrancis.backup;

import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -60,7 +60,7 @@ private static void groupByLambda() {

imprimeTitulo("groupByLambda");

// Objetivo � agrupar Person pelo sex
// Objetivo � agrupar Person pelo sex

Map<Character, List<Person>> personMap = personList.stream().collect(Collectors.groupingBy(Person::getSex));

Expand All @@ -72,7 +72,7 @@ private static void groupByLambda() {
private static void groupByNormal() {
imprimeTitulo("groupByNormal");

// Objetivo � agrupar Person pelo sex
// Objetivo � agrupar Person pelo sex

Map<Character, List<Person>> personMap = new HashMap<Character, List<Person>>();

Expand All @@ -96,7 +96,7 @@ private static void groupByNormal() {
private static void filtroCompostoLambda() {
imprimeTitulo("filtroCompostoLambda");

// Objetivo � mostrar somente os nomes das person do sexo masculino com age maior que 22;
// Objetivo � mostrar somente os nomes das person do sexo masculino com age maior que 22;

List<String> nomes = personList.stream()
.filter(p -> p.getSex() == 'M')
Expand All @@ -112,7 +112,7 @@ private static void filtroCompostoLambda() {
private static void filtroCompostoNormal() {
imprimeTitulo("filtroCompostoNormal");

// Objetivo � mostrar somente os nomes das person do sexo masculino com age maior que 22;
// Objetivo � mostrar somente os nomes das person do sexo masculino com age maior que 22;

List<String> nomes = new ArrayList<String>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.github.deividfrancis;
package com.github.deividfrancis.backup;

public class Person {

Expand All @@ -13,7 +13,7 @@ public Person(Integer id, String name, char sex, Integer age) {
this.sex = sex;
this.age = age;
}

public Integer getId() {
return id;
}
Expand Down